Repository navigation
refactor(events): deslop listener and disposal plumbing - #164221
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
|
Codex review: blocked before merge. Reviewed October 3, 2026, 8:09 AM ET / 12:09 UTC (Revision 4). ClawSweeper reviewWhat this changesThe PR consolidates listener registration and cleanup across runtime owners and plugins, fixes stale unsubscribe handles, and stabilizes a browser regression test. Merge readiness⛔ Blocked before merge - 1 item remains This PR remains useful against current main, and no blocking introduced defect was found. The earlier migration-proof blocker is unsupported by the inspected diff. Priority: P2 Review scores
Verification
How this fits togetherListeners carry runtime, channel, and Gateway updates to subscribed consumers, including the Control UI. Their cleanup owners must remove retired subscriptions without interrupting replacements or leaking temporary handlers. flowchart TD
A[Runtime and channel updates] --> B[Existing listener owners]
C[Consumer subscriptions] --> B
B --> D[Notification callbacks]
D --> E[Agents and Control UI]
F[Unsubscribe or shutdown] --> G[Owner cleanup]
G --> B
Before merge
Agent review detailsSecurityNone. PR surfaceSource -151, Tests +171, Other 0. Total +20 across 80 files. View PR surface stats
Review metricsNone. Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Keep cleanup with the existing owners, preserving replacement subscriptions and releasing only the handlers acquired by a failed bind attempt. Do we have a high-confidence way to reproduce the issue? Yes, from source: dispose a subscription, register its replacement, then repeat the old disposer; current main deletes the replacement bucket. The HTTP regression exercises synchronous native bind rejection, but neither scenario was executed in this review. Is this the best way to solve the issue? Yes. Reusing equivalent helpers and repairing bucket retirement at each existing owner preserves the established contracts without adding another registry or public API. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 5f52ff0f863c. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles)
|
Reuse canonical listener registration and matching isolated notifications. Remove single-subscriber and single-cleanup registries plus unused listener compatibility paths. Preserve callback ordering and resource ownership. Fix stale unsubscribe handles dropping replacement observers and synchronous HTTP listen failures leaking temporary handlers. Add owner-boundary regressions for both cases.
Keep async capture finalizers on their typed owner, preserve native HTTP error handling during synchronous bind cleanup, and retain the audio waiter scheduling boundary. Prune the assertion baseline for the removed Copilot compatibility cast.
6449398 to
32fb7b4
Compare
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
* origin/main: fix(test): restore fixture state and await async completion (#164222) refactor(sessions): stage and settle pending inputs in workers (#164284) fix: speech-only replies fail when models include reasoning (#164285) fix(nextcloud-talk): avoid webhook migration for unconfigured channels fix: guide background skill reviews through Workshop proposals (#164292) test(build): reject AI dependencies in retained config repairs refactor(channels): require canonical private-network settings (#163535) fix(memory): migrate embedding cache in bounded batches and record oversized rows (#164303) feat(state): incognito actor memory and Codex history routing (P5c, inactive) (#164224) refactor(synology-chat): remove unused route account ID (#164280) test(ui): await web push preference publications (#164295) perf(scripts): avoid compiler projects for runtime import parsing (#164243) fix(worktrees): create workspaces from nested Windows repositories (#164249) test(agents,channels,cli): remove low-value tests (batch d173) (#164302) perf(workboard): serve cards per board revision and push changes instead of polling (#164301) refactor(sqlite): deslop sqlite stores (#164271) chore(ui): refresh control ui locales (#164299) refactor(events): deslop listener and disposal plumbing (#164221) fix: canonicalize fresh worker reasoning signatures (#164287)
) * refactor(events): deslop listener and disposal plumbing Reuse canonical listener registration and matching isolated notifications. Remove single-subscriber and single-cleanup registries plus unused listener compatibility paths. Preserve callback ordering and resource ownership. Fix stale unsubscribe handles dropping replacement observers and synchronous HTTP listen failures leaking temporary handlers. Add owner-boundary regressions for both cases. * test(events): preserve native HTTP listeners in cleanup regression * fix(events): preserve callback and terminal-close contracts Keep async capture finalizers on their typed owner, preserve native HTTP error handling during synchronous bind cleanup, and retain the audio waiter scheduling boundary. Prune the assertion baseline for the removed Copilot compatibility cast. * test(ui): await restored roster before asserting event reads
What Problem This Solves
Listener registration and teardown repeat small local registries and compatibility paths, and stale unsubscribe handles can silently remove replacement observers.
User Impact
Replacement subscriptions keep receiving updates after an old disposer runs again. A synchronous HTTP bind failure releases its temporary listeners. Callback ordering, error isolation, replay, cleanup ownership, config, protocol, and visible UI remain unchanged.
Why This Change Was Made
void/off()subscription fallback; the pinned SDK returns an unsubscribe function.Fixes found along the way
Guard retired keyed subscriptions in MCP context, session maintenance, tool activity, model-catalog updates, SDK reconnects, and LLM activity. Add regressions at each owner boundary. Release both temporary HTTP listeners when native
listen()throws synchronously, with a real-server regression that never opens a port.Evidence
nice -n 15fallback. Owned leases were completed, stopped, or released. Final Linux repair proof used Blacksmith Testboxtbx_01m40q0381hefeh3w72hd5hb4v(lease workflow); command exit codes own the proof result because stopping the lease can cancel its hosting workflow.on()forms return unsubscribe functions. No dependency or public SDK export was added.CI corrections and inherited failure
The first hosted run caught two callback typing/lint issues, the required assertion-baseline shrink, and an audio ordering regression. Those are addressed: async finalizers retain their original typed registration, synchronous HTTP listen failures clean up and rethrow into the Promise executor, the Copilot assertion count shrinks from 2 to 1, and the original meeting waiter remains unchanged. Its
Promise.racescheduling boundary is required for final audio to carryclosed: true; the existing audio boundary test passes without altered assertions.Four
attempt-stream-prepare.test.tscases fail withterminal.readSanitizedResult is not a function. The same failures appear on hourly main CI job 111175455568, main headf323437952ccee1fc7abc06bab6eb6f7a376c726, independently of this PR. The test, mock fixture, stream-preparation owner, and tool-search executor have identical blobs in that main run and this PR. The unchanged mock constructs a terminal object without the reader that main's executor now requires; the property access fails before activity creation or transcript writes. These cases use a plain fake session, not the changed session cleanup path, and activity notifications are mocked. No inherited main fixture repair is included. Main subsequently repaired that fixture in commitb1c49290c8d5335331c63fc176d75a80805fa953; the final PR merge validation includes that owner fix.The second hosted CI run 37116543498 exposed a race in
chat-subagent-waiting.e2e.test.ts: returning to the retained parent schedules child-roster hydration after 250 ms, but the test measured request counts before that hydration finished. The test now holds that exact request, releases a response with a distinct child label, and waits for the label to render before measuring event-only updates. Transcript assertions are scoped to the active pane so hidden retained panes cannot produce duplicate matches. The exact no-extra-request assertion remains unchanged.The repair passed 20 Linux browser executions (
--repeats 19), taking 123.29 seconds of test time and 138.02 seconds wall time. A temporary production mutation deliberately added a read on the settled-to-waiting transition: the unchanged assertion failed with expected 3, received 4. The production file was restored byte-for-byte. The 55 sibling tests and all 1,132 plugin-contract tests also passed on the same Blacksmith lease, and both cycle analyzers reported zero. Three consecutive runs of the original 82-file UI shard passed all 391 cases each. The shard replay initially exposed a missing Playwright FFmpeg asset on the disposable lease; installing that required asset resolved all eight setup failures without source changes. The negative control was not repeated after it had established the intended failure.ClawSweeper completed the earlier review of
6449398ad1fd89a836d195c53a73612b09204a54with no introduced defect. Its mechanical data-model compatibility checkbox is unsupported by the diff and contradicted by its technical review:device-scope-upgrade.tsonly replaces equivalent Set registration with the canonical helper; no migration, storage shape, or upgrade contract changes.Final hosted CI and inherited-only exception
Final-head CI 37121575413 at
32fb7b416af2f0b9c0d842acce1d5db34c8aa325passed every selected job exceptchecks-node-changed-compact-large-21-1and its aggregate gate. The repaired UI shard passes.The sole failed case is
server-endpoint-compaction.test.ts→ “leaves a missing canonical checkpoint window to client budget compaction”:Cannot add property providerReplay, object is not extensibleat test line 255 /openai-responses-compaction-replay.ts:127. The same case fails on the current independent peer CI job 111201356130, peer head3a118d68bc6e0989b657dbcd00b9882dda9a0ca0.Main commit
e40ed06f23cb8bd939c9a6ff537eba7136074686made appended messages immutable. This unchanged fixture attempts to mutate a transcript-owned message before calling the compaction operation; production compaction already clones its owner message. The test, capture helper, append/persistence owners, and freeze helper are unchanged between our CI baseline and tested merge. Our listener changes do not execute on the failing setup path. The fixture repair is already owned by #163471; no duplicate repair is included. This qualifies for the explicitly authorized inherited-only CI exception; CI is retained as failed, and security/review gates remain enforced.Regression test wall times
All commands used
node scripts/run-vitest.mjs <file> --maxWorkers=1, at nice level 15. These are measured local wall times, including worker preparation; hosted CI timing is tracked separately.src/config/sessions/session-accessor.sqlite-maintenance-age.test.tssrc/agents/mcp-app-model-context.test.tssrc/agents/embedded-agent-runner/run/tool-activity-heartbeat.test.tssrc/gateway/server/http-listen.test.tsui/src/lib/model-catalog-store.test.tspackages/ai/src/utils/llm-request-activity.test.tsandpackages/sdk/src/transport.test.ts(one invocation)The HTTP regression compares the complete pre-call listener lists, preserving Node's own listener as well as the caller's.
Focused test selection
Size-sorted production coverage log
Listener and disposal coverage
This cross-cutting lane inventories concrete listener registries, subscription/disposal owners and teardown wrappers; unrelated modules are outside the pattern. Sizes use the starting main revision
54d008b6dae. Every actual candidate over 200 lines is marked READ with its simplification or retention reason. Regex false positives are explicit. Existing native-language and dependency-specific lifecycles remain with their owners.apps/macos/Sources/OpenClaw/GatewayConnection.swiftsrc/infra/diagnostic-events.tssrc/gateway/node-registry.tsextensions/tlon/src/monitor/index.tssrc/auto-reply/reply/queue/drain.tsscripts/dev/realtime-talk-live-smoke.tssrc/gateway/watch-node-http.tsapps/macos/Sources/OpenClaw/GatewayEndpointStore.swiftscripts/lib/managed-child-process.mtssrc/commands/models/list.probe.tscreateAuthProbeWorkalready owns the run/drain barrier. Probe finalization closes run admission first, then after physical work drains attempts session removal, snapshot invalidation, exact-path agent-database disposal, and directory removal sequentially, continuing after every cleanup error. It preserves a single error's identity or throws an orderedAggregateErrorwhose cause is the first failure. Best-effort cleanup would swallow the required failure; disposal stacks would change ordering/error shape. The outer state-owner release uses nestedfinallyso signal listeners detach even if state-lock release fails, and is itself delayed through the same work barrier. The rest of the file is probe target/auth selection and result projection outside x11 scope.src/agents/sessions/extensions/runner.tsextensions/copilot/src/event-bridge.tssrc/agents/sessions/agent-session-base.tsui/src/components/session-data-controller.tssrc/state/openclaw-state-db-cache.tsui/src/pages/custodian/custodian-session-store.tssrc/plugins/plugin-instance.tssrc/gateway/exec-approval-lifecycle.tssrc/gateway/server-chat-state.tssrc/agents/auth-profiles/runtime-snapshots.tsextensions/matrix/src/matrix/sdk/client-base.tssrc/infra/agent-run-registry.tspackages/agent-core/src/agent.tssrc/config/sessions/session-transcript-reconcile.tssrc/gateway/session-row-projection-record.tssrc/gateway/control-ui-session-pr-subscriptions.tssrc/process/supervisor/adapters/child.tscreateProcessAdapterEventsalready owns replayable exit/error observations; native child and pipe listeners implement separate close, drain, IPC, and tree-extinction barriers. The small FIFOoutputUnsubscribers.splice(0)loop deliberately drains before stream destruction, keeps error/Node-close bookkeeping attached during destruction, and is fail-fast. A generic disposal stack would reverse ordering or alter error aggregation/continuation; isolating notification helpers would alter fail-fast semantics.extensions/discord/src/voice/realtime-speaker-session.tsui/src/app/gateway-store.tssrc/infra/sqlite-worker-broker.tssrc/auto-reply/reply/reply-run-registry.state.tsscripts/lib/cross-os-release-checks/process.tssrc/gateway/server-methods/sessions-patch-engine.tsui/src/lib/sessions/index.tsextensions/matrix/src/matrix/sdk/verification-manager.tssrc/config/sessions/session-accessor.sqlite-reclamation-worker-lifetime.tsaddAbortListenerand the canonical transport-end observer. Idle-drain disposal is tied to renewed use; process/pressure/owner registrations are deliberately retained after uncertain cleanup so explicit retirement can retry, and removed only after native exit or released task custody is proven.ui/src/lib/sessions/session-roster-refresh.tsui/src/lib/chat/outbox-store.tssrc/config/runtime-snapshot.tssrc/gateway/github-personal-oauth.tsui/src/components/mcp-app-view.tsui/src/lib/session-progress-cards.tsscripts/run-oxlint.mtsui/src/lib/sessions/session-roster-observations.tssrc/process/gateway-work-admission.tssrc/agents/code-mode-state.tspackages/gateway-client/src/protocol-client.tssrc/agents/provider-local-service.tssrc/gateway/worker-environments/placement-turn-authority.tssrc/infra/agent-events.tssrc/gateway/worker-environments/session-attachment-service.tssrc/plugin-sdk/api-baseline-declaration-closure.tsui/src/pages/chat/chat-state-controller.tsui/src/lib/channels/index.tsapps/android/wear/src/main/java/ai/openclaw/wear/WearTalkAvatar.ktui/src/pages/systems/systems-controller.tssrc/state/openclaw-state-db-async-lifecycle.tsui/src/lib/session-pull-requests.tsui/src/pages/config/talk-page.tssrc/gateway/desktop/session-registry.tssrc/gateway/mcp-http.tsui/src/plugins/control-ui-runtime.tsui/src/lib/chat/chat-metadata-store.tssrc/agents/embedded-agent-runner/run/attempt.tssrc/agents/mcp-ui-resource.tssrc/infra/sqlite-snapshot-single-flight.tssrc/gateway/sessions-history-http.tsui/src/app/native-conversation-bridge.tssrc/gateway/mcp-grant-store.tssrc/gateway/portals/portal-http-proxy.tssrc/gateway/server/ws-connection/worker-connection.tssrc/gateway/server-methods/models-auth-status.tssrc/agents/tool-search-catalog.tssrc/agents/embedded-agent-subscribe.tssrc/gateway/worker-environments/store-projection.tssrc/worker/worker-connection.tssrc/gateway/worker-environments/store.tssrc/gateway/server/ws-connection/authenticated-request-dispatch.tsextensions/whatsapp/src/session.tsui/src/app/session-placement-startup.runtime.tssrc/agents/embedded-agent-runner/run/attempt-tool-prepare.tssrc/gateway/server/plugins-http.tssrc/agents/cli-runner/execute-events.tssrc/agents/embedded-agent-runner/run/lane-controller.tssrc/commands/doctor/shared/context-engine-host-compat.tsrunBestEffortCleanup, a disposal stack, or an aggregate helper does not preserve this first-failure warning contract without restoring equivalent local policy. No listener registry, redundant subscription owner, or unused disposal layer is present elsewhere in the fully read file.ui/src/lib/model-catalog-store.tsextensions/memory-core/src/memory/manager-search-knn-subprocess.tssrc/gateway/server-http-upgrades.tsapps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatSessionHoverCardFacts.swiftsrc/plugins/host-hook-cleanup.tsui/src/pages/plugin/logbook-controller.tsui/src/lib/agents/index.tsui/src/pages/new-session/draft-preference-state.tsui/src/app/session-placement-startup.tsui/src/app/native-device-settings.tssrc/agents/embedded-agent-runner/run/attempt-settle.tssrc/gateway/desktop/rfb-preauth.tsscripts/e2e/lib/plugin-lifecycle-matrix/measure.mjsui/src/app/overlays.tssrc/infra/oauth-loopback-callback.tsracePromiseWithAbortSignalis not equivalent to its local DNS abort wait: it changes the exactOAuth callback cancellederror consumed by OAuth callers to anAbortErrorwith different message/cause and settlement mechanics. Generalizing it solely for this caller would replace 13 direct lines with new policy.src/infra/worker-native-handle.tssrc/gateway/server-methods/session-catalog-list-lifetime.tsextensions/discord/src/voice/audio-transport.tssrc/config/sessions/session-accessor.sqlite-archive.tsracePromiseWithAbortSignalwould reject after admission and change the error shape. Worker result/error listeners deliberately settle only on exit, when SQLite/file handles are closed.src/state/user-profile-events.tssrc/gateway/desktop/observe-bridge.tssrc/infra/sqlite-readonly-native-resource.client.tsfinallyremoval and cannot be replaced by an abort race because cancellation must wait for a real RPC child-close acknowledgement. Session maps retain native custody after transport failure until a close reply or acknowledged closed state permits release.ui/src/lib/model-catalog-cache.tssrc/claws/provenance-runtime-read.tssrc/infra/unhandled-rejections.tspackages/ai/src/stream.tssrc/gateway/desktop/node-stream-broker.tssrc/process/spawn-broker/child.tsui/src/app/boot-record.tsui/src/app/agent-selection.tssrc/gateway/server-cron-lazy.tssrc/state/user-github-connections.tssrc/node-host/plugin-node-host.tssrc/secrets/private-plan-file.tsIDisposableis embedded C# implementing Win32 SafeFileHandle custody, not duplicated JavaScript disposal infrastructure. Itsfinallycalls dispose after ACL verification/publication failure; disposal arms delete-on-close before handle release and attempts explicit deletion only when arming fails. Descriptor memory is separately freed inOpen'sfinally. Replacing these native phases with the TypeScript helpers is not possible and collapsing them changes private-file failure semantics.src/gateway/operator-role-policy.tssrc/gateway/desktop/managed-linux-audio.tssrc/infra/worker-task-pool-retirement.tscreateRetainedOperationandrunBestEffortCleanup. Rotation snapshots tasks/slots, waits tasks before native retirement, joins artifact cleanup after native shutdown, and retains failed custody for retry.service()must advance synchronously without waiting for Promise reactions, so straight-line async teardown is not equivalent. Completion callbacks deliberately execute directly/fail-fast after native listener removal;notifyListenerswould isolate failures and change dispatch/retry behavior.src/config/sessions/session-accessor.sqlite-maintenance-age.tssrc/skills/runtime/refresh-state.tssrc/gateway/node-runner-inventory-runtime.tssrc/infra/sqlite-wal-checkpoint.tssrc/plugins/install-runtime-batch.tsui/src/lib/chat/outbox-store-projection.tspackages/sdk/src/transport.tssrc/worker/worker-connection-frames.tsextensions/openai/realtime-quicksilver-socket.tssrc/gateway/server-shared-auth-generation.tssrc/gateway/server-broadcast-narration.tssrc/gateway/http-common.tsui/src/app/bootstrap-theme.tssrc/gateway/desktop/rfb-probe.tssrc/media/store.read-scope.tssrc/config/sessions/session-transcript-reconcile-pool.tssrc/config/sessions/session-accessor.sqlite-archive-session.tsui/src/pages/chat/chat-pane-sidebar-layout.tsui/src/app/config.tsui/src/app/mentions.tssrc/hooks/internal-hooks.tssrc/agents/mcp-app-model-context.tssrc/config/sessions/session-turn.tsui/src/lib/sessions/session-managed-list-refresh.tssrc/skills/runtime/session-snapshot.tssrc/gateway/chat-abort-lifecycle-internal.tssrc/gateway/worker-environments/project-setup-script.tsextensions/tlon/src/settings.tsui/src/lib/agents/roster-activity-store.tssrc/gateway/desktop/audio-bridge.tsextensions/discord/src/voice/realtime-recording.tssrc/agents/mcp-stdio-client.tsui/src/components/session-data-controller-events.tsui/src/pages/model-setup/first-run-activation-receipt.tssrc/agents/auth-profiles/shared-store-bootstrap.tsextensions/workboard/browser/widgets/runtime.tsui/src/lib/config/runtime-config-capability.tssrc/agents/mcp-transport.tssrc/gateway/server-broadcast-live-text.tssrc/agents/prepared-model-runtime.resources.tsextensions/openai/realtime-quicksilver-sideband.tssrc/gateway/cli-session-history.claude-snapshot.tssrc/infra/embedded-question-broker.tssrc/infra/kysely-sync-cache-state.tsui/src/lib/agents/identity.tsextensions/discord/src/monitor/gateway-supervisor.tssrc/agents/session-maintenance/coordinator.tssrc/process/terminal-pty-node.tssrc/gateway/talk/session-registry.tsextensions/codex/src/session-catalog-events.tsextensions/codex/src/app-server/server-requests.tssrc/process/terminal-pty-bun.tsextensions/whatsapp/src/inbound/message-debounce.tssrc/gateway/session-event-prepared-row.tsextensions/diagnostics-otel/src/service-exporter-health.tsui/src/pages/chat/chat-settings-patches.tsextensions/workboard/src/store-runtime.tssrc/infra/worker-task-pool-resources.tssrc/agents/prepared-model-runtime.publication-events.ts