Skip to content

Commit 357087b

Browse files
authored
refactor(gateway): lifecycle-owned ambient state via factory-registered drains (#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.
1 parent fa0e298 commit 357087b

49 files changed

Lines changed: 699 additions & 167 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ a5f59c9acbcaa3f82247bf806eb5ba08032373fb853719f0ec9457690f16fc70 module/media-m
8888
c5e3eb1a584f4b8126d9d6c177a840ec9103671e8d1242634ee67db9b5b9e573 module/media-understanding
8989
c0ffaed532578cf33493992e1ff806b2268b8e3774a92edbaede5cf5bda162a6 module/media-understanding-runtime
9090
bebd2931dc51d67c063ff19fa1c278f8dcfe00ab23cfbd480d47329ea8e5088e module/meeting-runtime
91-
aec2225e0341aea994c2d5dd0e642e9c44281ba0aee445574e2355eda4225945 module/memory-core-host-engine-foundation
91+
ea56ea0455c62f292e1c7b3e56cac6eb3fea00e548f9ab2f4a69e0b41b0a2d96 module/memory-core-host-engine-foundation
9292
00d6f8bc78256558972d431b7983d7b774e0a98d802a1eec533d2cae1e1f1986 module/memory-host-core
9393
87b7a3206346c0d4b294fb3a2395cbaabc3e73ff8b1b9ea925bc3aade3e52687 module/messaging-targets
9494
5011823e5530df577d800e2b910c4b4f49b59084aa1df3bc03e3962ad3aee279 module/model-session-runtime
@@ -138,7 +138,7 @@ ff35f9f74d35d37a2eb6126b57f3dc5a4d580b6222fe3a34c9368779ad32eab7 module/state-p
138138
1b5b9a4532db991fce807ba736b550de27aa5f9de2e1f508a8f4f09cae76ea29 module/telegram-account
139139
110944726884fca94f38c9c329b5950629438b9a719f4782c4beeade8bd67746 module/temp-path
140140
0e230313a7a27a915a7aa399c0afd94c4c3e10d485c7b513e757f41bfc362dbe module/text-chunking
141-
25b5366f5d0f5826f520f847e0ae701936e97302d5ac62042d65f5be0f6974d2 module/text-runtime
141+
2a9971449c5e31c61a715e8ae2d99ac7453690f595c84f4daf85b640bb711689 module/text-runtime
142142
a94c9ff59cc361b04f8731a47d722c4bc88cfabf942221369a8cb67bdcda7249 module/tool-plugin
143143
89846974257b7551d46a514902998d0592fc67b1d8ce036c6514d7b9cd1bc159 module/tool-results
144144
9d6ab352913a573b226e054e1dc8c6d088493aea9954950c65585923b5b6895a module/tool-send

‎packages/memory-host-sdk/src/host/embeddings-worker.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -648,6 +648,12 @@ async function drainRetainedWorkerClients(): Promise<void> {
648648
return await drain;
649649
}
650650

651+
/** Waits for provider creation to settle, then closes every retained worker client. */
652+
export async function drainRetainedLocalEmbeddingWorkerClients(): Promise<void> {
653+
await workerProviderCreationTail;
654+
await drainRetainedWorkerClients();
655+
}
656+
651657
/** Create the public local embedding provider backed by the child worker client. */
652658
export async function createLocalEmbeddingWorkerProvider(
653659
options: EmbeddingProviderOptions,

‎scripts/plugin-sdk-surface-report.mjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,8 @@ export function readPluginSdkSurfaceBudgets(env = process.env) {
269269
),
270270
publicWildcardReexports: readPluginSdkSurfaceBudgetEnv(
271271
"OPENCLAW_PLUGIN_SDK_MAX_PUBLIC_WILDCARD_REEXPORTS",
272-
82,
272+
// -1: text-runtime now names its global-singleton exports explicitly.
273+
81,
273274
env,
274275
),
275276
};

‎src/acp/runtime/registry.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,15 @@ function resolveAcpRuntimeRegistryGlobalState(): AcpRuntimeRegistryGlobalState {
2121
const processStore = process as NodeJS.Process & Record<PropertyKey, unknown>;
2222
const existing = processStore[ACP_RUNTIME_REGISTRY_STATE_KEY];
2323
if (existing) {
24-
return existing as AcpRuntimeRegistryGlobalState;
24+
(globalThis as Record<PropertyKey, unknown>)[ACP_RUNTIME_REGISTRY_STATE_KEY] = existing;
2525
}
2626
const created = resolveGlobalSingleton<AcpRuntimeRegistryGlobalState>(
2727
ACP_RUNTIME_REGISTRY_STATE_KEY,
2828
() => ({
2929
backendsById: new Map<string, AcpRuntimeBackend>(),
3030
}),
31+
(state) => state.backendsById.clear(),
32+
"plugin-registry",
3133
);
3234
// ACP runtime backends are registered from bundled plugin code and read from
3335
// core/test code. In Vitest and Jiti, those can run in different globalThis

‎src/agents/agent-lifecycle-registry.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@ import type { OpenClawStateDatabaseOptions } from "../state/openclaw-state-db-co
1717
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
1818

1919
const AGENT_LIFECYCLE_KEY = Symbol.for("openclaw.agentLifecycle");
20-
const agentLifecycle = resolveGlobalMap<string, "deleting" | "deleted">(AGENT_LIFECYCLE_KEY);
20+
const agentLifecycle = resolveGlobalMap<string, "deleting" | "deleted">(
21+
AGENT_LIFECYCLE_KEY,
22+
"close-and-restart",
23+
);
2124

2225
export class AgentDeletionAuthorityRollbackError extends AggregateError {}
2326

‎src/agents/child-admission.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { resolveGlobalMap } from "../shared/global-singleton.js";
2+
13
export type ChildAdmissionCap =
24
| "subagents.maxSpawnDepth"
35
| "subagents.maxChildrenPerAgent"
@@ -16,7 +18,10 @@ type ChildAdmissionParams = {
1618
} & ({ collect: false } | { collect: true; totalChildren: number; maxTotalChildren: number });
1719

1820
/** ACP child keys deduplicate task rows; symbols keep anonymous starts distinct. */
19-
const pendingChildAdmissions = new Map<string, Set<string | symbol>>();
21+
const pendingChildAdmissions = resolveGlobalMap<string, Set<string | symbol>>(
22+
Symbol.for("openclaw.pendingChildAdmissions"),
23+
"close-only",
24+
);
2025

2126
type ReservableChildAdmission = { ok: true } | { ok: false };
2227

‎src/agents/harness/gateway-question.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type {
44
QuestionRequestQuestion,
55
QuestionWaitAnswerResult,
66
} from "../../../packages/gateway-protocol/src/schema/questions.js";
7+
import { resolveGlobalMap } from "../../shared/global-singleton.js";
78
import type { EmbeddedRunAttemptParams } from "../embedded-agent-runner/run/types.js";
89
import {
910
buildAgentHarnessUserInputAnswers,
@@ -32,6 +33,7 @@ type PendingAgentQuestion = {
3233
questions: readonly AgentHarnessUserInputQuestion[];
3334
gatewayCall: AgentHarnessQuestionGatewayCall;
3435
registration: Promise<unknown>;
36+
rejectRegistration: (error: unknown) => void;
3537
attachRegistration: (promise: Promise<unknown>) => void;
3638
answer?: Promise<QuestionWaitAnswerResult>;
3739
bufferedAnswers?: AgentHarnessUserInputAnswers;
@@ -40,7 +42,16 @@ type PendingAgentQuestion = {
4042
resolving: boolean;
4143
};
4244

43-
const pendingAgentQuestions = new Map<string, PendingAgentQuestion>();
45+
const pendingAgentQuestions = resolveGlobalMap<string, PendingAgentQuestion>(
46+
Symbol.for("openclaw.pendingAgentQuestions"),
47+
(questions) => {
48+
const error = new Error("gateway lifecycle ended before question registration completed");
49+
for (const state of questions.values()) {
50+
state.rejectRegistration(error);
51+
}
52+
questions.clear();
53+
},
54+
);
4455

4556
function readQuestionErrorReason(error: unknown): string | undefined {
4657
if (!error || typeof error !== "object") {
@@ -149,6 +160,7 @@ export function registerPendingAgentQuestion(params: {
149160
...params,
150161
sessionKey,
151162
registration,
163+
rejectRegistration,
152164
attachRegistration: (promise) => {
153165
if (registrationAttached) {
154166
throw new Error("gateway question registration already attached");

‎src/agents/sessions/tools/file-mutation-queue.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,12 @@
55
*/
66
import { realpathSync } from "node:fs";
77
import { resolve } from "node:path";
8+
import { resolveGlobalMap } from "../../../shared/global-singleton.js";
89

9-
const fileMutationTails = new Map<string, Promise<void>>();
10+
const fileMutationTails = resolveGlobalMap<string, Promise<void>>(
11+
Symbol.for("openclaw.fileMutationTails"),
12+
"close-only",
13+
);
1014

1115
function getMutationQueueKey(filePath: string): string {
1216
const resolvedPath = resolve(filePath);

‎src/audit/message-audit-events.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { resolveGlobalSet } from "../shared/global-singleton.js";
12
/** Trusted in-process message lifecycle stream for durable audit projection. */
23
import { notifyListeners, registerListener } from "../shared/listeners.js";
34
import type { MessageAuditEventInput } from "./audit-event-types.js";
@@ -13,7 +14,10 @@ export type TrustedMessageAuditEvent = TrustedMessageAuditEventVariant<MessageAu
1314

1415
type MessageAuditListener = (event: TrustedMessageAuditEvent) => void;
1516

16-
const listeners = new Set<MessageAuditListener>();
17+
const listeners = resolveGlobalSet<MessageAuditListener>(
18+
Symbol.for("openclaw.messageAuditListeners"),
19+
"close-and-restart",
20+
);
1721

1822
/** Emit only closed metadata. This stream is intentionally not part of the plugin SDK. */
1923
export function emitTrustedMessageAuditEvent(event: TrustedMessageAuditEvent): void {

‎src/auto-reply/dispatch.ts‎

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ import {
2222
resolveCommandTurnTargetSessionKey,
2323
} from "./command-turn-context.js";
2424
import { withReplyDispatcher } from "./dispatch-dispatcher.js";
25+
import {
26+
foregroundReplyFenceByKey,
27+
type ForegroundReplyFenceState,
28+
notifyForegroundReplyFenceWaiters,
29+
} from "./foreground-reply-fence-state.js";
2530
import { setReplyPayloadMetadata } from "./reply-payload.js";
2631
import type { CommandSessionMetadataChange } from "./reply/command-session-metadata.js";
2732
import { dispatchReplyFromConfig } from "./reply/dispatch-from-config.js";
@@ -46,15 +51,6 @@ import type { ReplyPayload } from "./types.js";
4651

4752
type InternalDispatchReplyOptions = Omit<InternalGetReplyOptions, "onBlockReply">;
4853

49-
type ForegroundReplyFenceState = {
50-
generation: number;
51-
visibleDeliveryGeneration: number;
52-
activeDispatches: number;
53-
activeGenerations: Map<number, number>;
54-
suspendedGenerations: Set<number>;
55-
waiters: Set<() => void>;
56-
};
57-
5854
type ForegroundReplyFenceSnapshot = {
5955
key: string;
6056
generation: number;
@@ -65,7 +61,6 @@ type ReplyPayloadRunState = {
6561
runId?: string;
6662
};
6763

68-
const foregroundReplyFenceByKey = new Map<string, ForegroundReplyFenceState>();
6964
const replyPayloadSendingDispatchers = new WeakSet<ReplyDispatcher>();
7065

7166
function applyRuntimeToolsAllow(
@@ -146,14 +141,6 @@ function beginForegroundReplyFence(
146141
};
147142
}
148143

149-
function notifyForegroundReplyFenceWaiters(state: ForegroundReplyFenceState): void {
150-
const waiters = [...state.waiters];
151-
state.waiters.clear();
152-
for (const resolve of waiters) {
153-
resolve();
154-
}
155-
}
156-
157144
function setForegroundReplyFenceAdmissionWaiting(
158145
snapshot: ForegroundReplyFenceSnapshot | undefined,
159146
waiting: boolean,

0 commit comments

Comments
 (0)