Skip to content

refactor(gateway): lifecycle-owned ambient state via factory-registered drains - #118271

Merged
steipete merged 3 commits into
mainfrom
refactor/ambient-state-lifecycle-owners
Aug 3, 2026
Merged

steipete merged 3 commits into
mainfrom
refactor/ambient-state-lifecycle-owners

Conversation

@steipete

@steipete steipete commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The conversation-binding pilot (#118075) established the pattern: ambient module state needs a lifecycle owner. A read-only inventory of current main found 44 hand-verified sites that lack one — cross-request pending state (agent questions, conversation turns, placement claim waiters, agent-job maps with live timers, MCP grants), plus listener/registry sets that accumulate across lifecycles. Worse, the tree has a structural asymmetry: close-path owners don't run on in-process SIGUSR1 restart and restart-path owners don't run on close, so each lifecycle leaks through the other.

Why This Change Was Made

Ownership moved to the factory instead of 44 hand-wired clears. resolveGlobalSingleton now accepts an owner class at slot creation:

  • close-and-restart — clears on terminal close and SIGUSR1 restart (default for runtime state)
  • close-only — preserves serialization tails across in-process restart where clearing a promise chain would break ordering
  • plugin-registry — clears inside clearActivePluginRegistry for plugin-contributed registrations

Drain ordering is deliberate: the gateway drain runs after plugin cleanup and before secret-snapshot clearing; the SIGUSR1 drain runs before durable task reload; plugin host runtime state clears in finally after plugin cleanup — this also delivers the highest-value single fix from the inventory (wiring clearPluginHostRuntimeState into registry clearing; it was previously reachable only from the test reset).

Conversions are semantic, not just map-dropping: pending question/turn/placement waiters are rejected or settled so no promise dead-ends at shutdown; agent-job timers are canceled; MCP watchers are canceled and awaited. Sites where clearing would violate serialization or need channel-specific teardown are explicitly deferred with reasons (table in the report below).

Named LOC tradeoff: production +525/−118 (net +407). The growth is the semantic cancellation paths for live timers, waiters, and OS resources — the alternative (silent map clears) would trade a leak class for a dead-ended-promise class. The deleted per-site *ForTest resets and the removed restart/close asymmetry are the structural payback.

User Impact

Gateway close and in-process restart now start from a clean slate: no stale pending approvals, no orphaned waiters resolving into the next lifecycle, no duplicate listener dispatch after restart, and minted MCP grants do not survive termination.

Deferred (explicit, with reasons)

Stateful target drivers (atomic builtin-registration reset needed), task-flow registry (SQLite-backed, reloads), health registry (extension WeakSet), before-agent-reply (ALS scope, not a registry), fire-and-forget hooks (needs generation-aware cancellation), session/store/SQLite writer queues (clearing promise tails violates serialization), extension candidates (need channel/plugin teardown owners).

Evidence

  • 734 focused tests passed; 150 highest-risk rerun after final extraction
  • Both core tsgo lanes; changed-file format/lint; runtime import cycles 0; madge 0; full build clean
  • Structured autoreview clean

Dist-driven lifecycle proof

Exact head 599cbbb67c3864494c1a8c35512dbdf643fd14ef; direct dist/entry.js; ephemeral OPENCLAW_STATE_DIR and TMPDIR; dynamically allocated loopback-only port; --allow-unconfigured; channel startup skipped; child environment scrubbed to proof-only variables. The proof slots use the public lifecycle API and log only when their real reset callback executes.

Close transcript:

[proof-runner] healthz=200
2026-08-02T16:27:31.896-07:00 [gateway] ready
2026-08-02T16:27:33.167-07:00 [gateway] received SIGTERM; shutting down
[ambient-proof] plugin-registry drained armed=true
[ambient-proof] factory close-and-restart drained armed=true
[ambient-proof] factory close-only drained armed=true
2026-08-02T16:27:33.362-07:00 [shutdown] completed cleanly in 138ms
[proof-runner] exit=0

SIGUSR1 restart transcript (close-only emits no marker during the restart phase):

[proof-runner] initial-healthz=200
2026-08-02T16:26:50.908-07:00 [gateway] received SIGUSR1; restarting
2026-08-02T16:26:50.909-07:00 [gateway] restart trace: restart.signal.received signal=SIGUSR1 reason=SIGUSR1 force=false waitMs=default
2026-08-02T16:26:50.911-07:00 [gateway] restart trace: restart.drain activeTasks=0 activeRuns=0 timedOut=false
2026-08-02T16:26:50.970-07:00 [gateway] restart trace: restart.close.session-end-drain reason=gateway_restarting
[ambient-proof] plugin-registry drained armed=true
[ambient-proof] factory close-and-restart drained armed=true
2026-08-02T16:27:00.542-07:00 [shutdown] completed cleanly in 9577ms
2026-08-02T16:27:01.515-07:00 [gateway] restart mode: in-process restart (OPENCLAW_NO_RESPAWN)
[ambient-proof] factory close-and-restart drained armed=true
2026-08-02T16:27:01.528-07:00 [gateway] restart trace: restart.next-start
2026-08-02T16:27:02.622-07:00 [gateway] ready
2026-08-02T16:27:02.623-07:00 [gateway] restart trace: restart.ready
[proof-runner] restart-healthz=200
[proof-runner] close-only-drained-during-restart=false
[proof-runner] final-SIGTERM-exit=0

Verdict:

{"head":"599cbbb67c3864494c1a8c35512dbdf643fd14ef","distEntry":"dist/entry.js","isolatedLoopback":true,"ephemeralStateRemoved":true,"close":{"health":200,"drainOrder":["plugin-registry","close-and-restart","close-only"],"cleanShutdown":true,"exit":0},"restart":{"initialHealth":200,"returnedHealth":200,"pluginRegistryDrainObserved":true,"closeAndRestartDrainObserved":true,"closeOnlyDrainedDuringRestart":false,"returnedReady":true,"finalExit":0}}

Maintainer decision: the optional lifecycle-reset parameters on resolveGlobalSingleton/resolveGlobalMap are accepted as additive public SDK surface; existing external plugin call sites are unaffected (prior signatures unchanged, defaults preserve prior behavior), manifest regenerated per the gate's intentional-change flow.

🤖 Generated with Claude Code

@steipete
steipete marked this pull request as ready for review August 2, 2026 22:40
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime cli CLI command changes agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Aug 2, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 2, 2026
@clawsweeper

clawsweeper Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 2, 2026, 8:47 PM ET / August 3, 2026, 00:47 UTC.

ClawSweeper review

What this changes

This PR registers process-local gateway, plugin, agent, and session state with lifecycle-specific drains so shutdown, in-process restart, and plugin-registry replacement settle waiters, cancel timers, and clear stale registries.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 5 items remain

Keep this PR open for maintainer review. The lifecycle design is coherent and the current-head source preserves close-only state during SIGUSR1 restart, but the final head adds an agent-job listener-lifecycle change after the submitted runtime transcript and expands an existing public Plugin SDK helper without visible maintainer confirmation in the supplied discussion.

Priority: P2
Reviewed head: 2071a826e4d7c807043734d6b09e217188c9cad7
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation and focused source coverage are solid, but current-head real behavior proof and SDK-contract confirmation remain merge gates.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The PR includes a strong terminal transcript for an earlier head, but current head adds the agent-job listener lifecycle repair; provide a redacted current-head dist-driven close and SIGUSR1 transcript before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The PR includes a strong terminal transcript for an earlier head, but current head adds the agent-job listener lifecycle repair; provide a redacted current-head dist-driven close and SIGUSR1 transcript before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 7 items Lifecycle factory contract: The branch extends the shared singleton helpers with reset callbacks and three lifecycle classes, retaining object identity while drain callbacks clear or settle state.
Restart and close paths distinguish close-only state: Gateway close selects restart draining when a restart is expected, and the drain implementation excludes close-only registrations for that event; terminal close still drains them.
Focused regression coverage: The branch adds unit coverage for repeated drains, async reset completion, failure aggregation, and close-only state surviving a restart drain, plus close and restart integration seams that assert an opted-in slot is cleared before the next start.
Findings None None.
Security None None.

How this fits together

Gateway, agent, session, and plugin flows create process-local maps and listeners that can outlive a request. Gateway close and SIGUSR1 restart invoke lifecycle drains so the next server lifecycle does not inherit stale state, while plugin-registry replacement clears plugin-contributed registrations separately.

flowchart LR
  A[Agent, session, and plugin activity] --> B[Process-local registries]
  C[Gateway close or SIGUSR1 restart] --> D[Lifecycle drain coordinator]
  E[Plugin registry replacement] --> F[Plugin-registry drain]
  D --> G[Settled waiters and cancelled timers]
  F --> G
  G --> H[Clean next gateway lifecycle]
Loading

Decision needed

Question Recommendation
Should the optional reset callback and lifecycle classification on the public Plugin SDK singleton helpers be accepted as a permanent external plugin contract? Approve the additive SDK contract: Keep the lifecycle registration arguments public, document their shutdown/restart semantics in the PR rationale, and require refreshed exact-head runtime proof before merge.

Why: The implementation preserves existing call signatures, but it changes the behavior and supported capabilities of helpers exported from an established SDK subpath; the supplied PR body alone is not maintainer-visible approval.

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The PR includes a strong terminal transcript for an earlier head, but current head adds the agent-job listener lifecycle repair; provide a redacted current-head dist-driven close and SIGUSR1 transcript before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - The optional reset callback and lifecycle classification extend the existing public Plugin SDK singleton helpers; the PR body asserts approval, but the supplied discussion has no visible maintainer confirmation of the permanent external contract.
  • Resolve merge risk (P1) - The dist-driven lifecycle transcript is for 599cbbb, not current head 2071a82, which adds the agent-job listener-lifecycle repair.
  • Complete next step (P2) - A maintainer must decide the public Plugin SDK contract, and the contributor must refresh real behavior proof on the final head; neither is a safe automated repair task.
Agent review details

Security

None.

PR surface

Source +399, Tests +132, Generated 0, Other +1. Total +532 across 49 files.

View PR surface stats
Area Files Added Removed Net
Source 42 541 142 +399
Tests 5 154 22 +132
Docs 0 0 0 0
Config 0 0 0 0
Generated 1 2 2 0
Other 1 2 1 +1
Total 49 699 167 +532

Review metrics

Metric Value Why it matters
Public lifecycle helper expansion 2 existing SDK helpers gain optional reset/lifecycle controls Existing plugin callers retain the old signatures, but the new controls create a compatibility-sensitive external lifecycle contract.

Stored data model

Persistent data-model change detected: durable storage schema: src/gateway/worker-environments/placement-turn-claims.ts, serialized state: src/gateway/server-methods/session-typing-state.ts, serialized state: src/gateway/session-reset-service.ts, unknown-data-model-change: src/gateway/session-reset-service.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Confirm the SDK contract and refresh runtime proof (recommended)
    Record maintainer acceptance of the public lifecycle helper semantics, then rerun the redacted dist-driven close and SIGUSR1 proof on current head before merging.
  2. Narrow the public surface
    If lifecycle reset registration is not intended for external plugins, retain the internal cleanup refactor but remove the new public helper capability.

Technical review

Best possible solution:

Retain one lifecycle-owner mechanism, obtain explicit maintainer confirmation that its SDK-facing arguments are a supported public contract, and publish a redacted current-head dist-backed close/SIGUSR1 transcript that covers the final agent-job listener change.

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

Yes, source-reproducible: the close and SIGUSR1 paths select distinct lifecycle drain events, and focused tests exercise the drain contract. The supplied real runtime transcript is not current-head evidence because it predates the final agent-job listener change.

Is this the best way to solve the issue?

Unclear pending maintainer approval: a single factory-owned drain is a maintainable repair for shared runtime state, but exposing reset registration through the public Plugin SDK must be explicitly accepted rather than inferred from an additive signature.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 18c9f27e2de3.

Labels

Label justifications:

  • P2: This is a broad internal lifecycle refactor with meaningful operational impact, but the available evidence does not establish an active user-facing outage.
  • merge-risk: 🚨 compatibility: The PR expands public singleton helper behavior used by plugins and must establish the intended long-term SDK contract before merge.
  • merge-risk: 🚨 availability: The new drain coordinator runs in gateway shutdown and in-process restart paths, so an incorrect callback or ordering choice can disrupt restart completion.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR includes a strong terminal transcript for an earlier head, but current head adds the agent-job listener lifecycle repair; provide a redacted current-head dist-driven close and SIGUSR1 transcript before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Lifecycle factory contract: The branch extends the shared singleton helpers with reset callbacks and three lifecycle classes, retaining object identity while drain callbacks clear or settle state. (src/shared/global-singleton.ts:26, 2071a826e4d7)
  • Restart and close paths distinguish close-only state: Gateway close selects restart draining when a restart is expected, and the drain implementation excludes close-only registrations for that event; terminal close still drains them. (src/gateway/server-close.ts:1061, 2071a826e4d7)
  • Focused regression coverage: The branch adds unit coverage for repeated drains, async reset completion, failure aggregation, and close-only state surviving a restart drain, plus close and restart integration seams that assert an opted-in slot is cleared before the next start. (src/shared/global-singleton.test.ts:72, 2071a826e4d7)
  • Public Plugin SDK surface: The existing public global-singleton SDK subpath re-exports both helpers, so their new optional reset and lifecycle arguments are an additive external contract; the generated SDK baseline also changes on this branch. (src/plugin-sdk/global-singleton.ts:4, 2071a826e4d7)
  • Final-head provenance: The current branch head is the follow-up commit restoring agent wait-listener lifecycle behavior; the submitted dist-driven transcript instead identifies earlier head 599cbbb. (src/gateway/server-methods/agent-job.ts:65, 2071a826e4d7)
  • Current-main and release check: The PR head is not an ancestor of the checked-out current main, and no local release tag contains current main; this is unmerged, main-only work rather than a completed implementation. (src/shared/global-singleton.ts:26, 18c9f27e2de3)

Likely related people:

  • steipete: Current-main blame attributes the shared singleton helper to Peter Steinberger, and the branch history shows the same author built the lifecycle refactor, SDK-baseline update, and final agent-listener correction. (role: feature owner and recent area contributor; confidence: high; commits: 07b8018fe02f, 3477ff9fa790, 2071a826e4d7; files: src/shared/global-singleton.ts, src/gateway/server-close.ts, src/gateway/server-methods/agent-job.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Publish redacted dist-backed close and SIGUSR1 restart output for 2071a82, including the final agent-job path.
  • Obtain a maintainer-visible decision on whether the lifecycle arguments are supported Plugin SDK API.

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 (5 earlier review cycles)
  • reviewed 2026-08-02T22:46:15.536Z sha d118bf8 :: needs real behavior proof before merge. :: [P1] Preserve or explicitly approve the Plugin SDK helper contract
  • reviewed 2026-08-02T22:58:40.741Z sha 564ddae :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-02T23:19:53.862Z sha 599cbbb :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-02T23:34:22.628Z sha 599cbbb :: needs maintainer review before merge. :: none
  • reviewed 2026-08-03T00:39:29.488Z sha 517a44372e4b0ec5dfe63521e8c3511627eabe20 :: needs real behavior proof before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Aug 2, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 2, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Aug 2, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 2, 2026
@steipete
steipete force-pushed the refactor/ambient-state-lifecycle-owners branch from 599cbbb to 517a443 Compare August 3, 2026 00:32
Keep agent-job data process-shared while preserving module-local event subscription ownership. Ratchet the public wildcard budget down after replacing text-runtime's wildcard singleton export with named exports.
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 Aug 3, 2026
@steipete
steipete force-pushed the refactor/ambient-state-lifecycle-owners branch from 517a443 to 2071a82 Compare August 3, 2026 00:41
@steipete
steipete merged commit 357087b into main Aug 3, 2026
123 checks passed
@steipete
steipete deleted the refactor/ambient-state-lifecycle-owners branch August 3, 2026 01:06
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 3, 2026
…ed drains (openclaw#118271)

* refactor(runtime): own ambient state lifecycle cleanup

* chore(plugin-sdk): refresh additive API baseline

* fix(runtime): restore agent wait listener lifecycle

Keep agent-job data process-shared while preserving module-local event subscription ownership. Ratchet the public wildcard budget down after replacing text-runtime's wildcard singleton export with named exports.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant