Skip to content

Commit c6d6706

Browse files
authored
perf(agents): reuse gateway plugin generation for prepared model runtime (#126630)
* perf(agents): reuse gateway plugin generation for prepared model runtime The model-runtime sidecar rebuilt two broad plugin registries on gateway startup: 167 imports across 84 plugins (83 loaded twice) with 82 forced TypeScript transformations, ~39.6s of a ~50s source-checkout startup. - Reuse the active gateway registry for inbound dispatch when the gateway-bindable subagent mode, workspace, and manifest identity of the requesting snapshot generation all match; fall back to isolated loading otherwise. - Seed the runtime registry from the inbound registry's plugin ids instead of a second unscoped broad load. - Prefer built plugin artifacts on the agents lane, matching the gateway loader; externally-packaged plugins no longer force source transforms. Measured (M3 Ultra, dist build, median of 3): sidecars.model-runtime 33.93s -> 0.379s; gateway readiness 41.69s -> 7.58s; plugin imports 167 -> 18; TypeScript transformations 82 -> 0. * fix(agents): keep source artifacts on isolated agent registry loads The full agents lane caught ~20 Code Mode regressions from preferring built artifacts on the agents loader lane: in a source checkout a stale dist silently replaces edited plugin source. The gateway-generation reuse already removes the broad re-imports that made source transforms expensive, so the artifact preference is unnecessary for the startup win and unsafe for dev checkouts. * fix(agents): bind gateway registry reuse to the current metadata generation Reuse authority is identity-based: the requesting snapshot must be the process-current published generation. Bundled manifest records compare by id+origin only, so an equivalence check alone could let an older or leaked active registry serve a different generation's plugins. * perf(agents): resolve prepared-runtime metadata through the current generation The sidecar acquired its snapshot with loadPluginMetadataSnapshot, which always constructs a fresh object, so the generation-identity reuse guard could never hold in the gateway and inbound loads stayed isolated. Resolve through the slot-probing entry instead; the published current generation satisfies the read and registry reuse engages. Test updates: model the current-generation identity in the reuse fixture, drop stale preferBuiltPluginArtifacts expectations from the isolated-load fixtures, and add a negative case proving a non-current generation refuses reuse. * perf(agents): inherit gateway artifact preference when extending its generation The runtime-registry delta load re-imported teams-meetings and zoom-meetings channel graphs through forced source transforms (~9.2s) even though the reused gateway generation had already realized them from built artifacts. When the inbound registry is the active gateway registry, the delta load now inherits the generation owner's built-artifact preference; isolated loads keep source truth, so source-executed tests and dev flows are unaffected. Measured (M3 Ultra, dist build, 3 runs): sidecars.model-runtime 289-331ms (baseline 33,930ms); gateway ready 3.7-4.0s (baseline 41.7s); forced source transforms 0 (baseline 82). * test(agents): count both slot-probing metadata resolutions in static startup The prepared cold plugin context now resolves through the canonical slot-probing entry, joining the model-id normalization lane's existing resolution. Both share the published generation; the eager-work protections remain the catalog laziness assertions. * refactor(agents): compose generation reuse with lifecycle artifact selection Rebase over #125957, which preserves built-artifact mode for lifecycle-selected prepared registries. Reuse of the active gateway generation and the generation-inherited delta preference compose with that owner's parameter instead of duplicating the forwarding.
1 parent 797d251 commit c6d6706

5 files changed

Lines changed: 197 additions & 14 deletions

‎src/agents/prepared-model-runtime.inbound-registry.ts‎

Lines changed: 58 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
11
import { hashRuntimeConfigValue } from "../config/runtime-snapshot.js";
2+
import {
3+
listRuntimePluginIdsFromRegistry,
4+
registryMatchesManifestPluginIds,
5+
} from "../plugins/active-runtime-registry.js";
6+
import { getCurrentPluginMetadataSnapshot } from "../plugins/current-plugin-metadata-snapshot.js";
27
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.types.js";
38
import type { PluginRegistry } from "../plugins/registry-types.js";
9+
import {
10+
getActivePluginRegistry,
11+
getActivePluginRegistryWorkspaceDir,
12+
getActivePluginRuntimeSubagentMode,
13+
} from "../plugins/runtime.js";
414
import type { PreparedModelRuntimeInput } from "./prepared-model-runtime.types.js";
515
import { loadAgentRuntimePluginRegistryHandle } from "./runtime-plugins.js";
616

@@ -45,14 +55,41 @@ export function createPreparedInboundRegistryLoader(): PreparedInboundRegistryLo
4555
if (existing) {
4656
return existing;
4757
}
48-
const registry = loadAgentRuntimePluginRegistryHandle({
58+
const activeRegistry = getActivePluginRegistry();
59+
const activeWorkspaceDir = getActivePluginRegistryWorkspaceDir();
60+
// Reuse is generation-bound: the requesting snapshot must BE the process-current
61+
// published generation, or a leaked/older active registry could satisfy the
62+
// manifest match (bundled records compare by id+origin only) and serve another
63+
// generation's plugins. Identity, not equivalence, is the authority check here.
64+
const currentGenerationSnapshot = getCurrentPluginMetadataSnapshot({
4965
config: input.config,
50-
env: input.env ?? process.env,
51-
...(input.workspaceDir ? { workspaceDir: input.workspaceDir } : {}),
52-
...(input.allowGatewaySubagentBinding ? { allowGatewaySubagentBinding: true } : {}),
53-
metadataSnapshot,
54-
preferBuiltPluginArtifacts: true,
66+
workspaceDir: metadataSnapshot.workspaceDir,
67+
allowWorkspaceScopedSnapshot: true,
5568
});
69+
const reusableGatewayRegistry =
70+
input.allowGatewaySubagentBinding === true &&
71+
input.env === undefined &&
72+
getActivePluginRuntimeSubagentMode() === "gateway-bindable" &&
73+
activeRegistry &&
74+
currentGenerationSnapshot === metadataSnapshot &&
75+
(activeWorkspaceDir === undefined || activeWorkspaceDir === metadataSnapshot.workspaceDir) &&
76+
registryMatchesManifestPluginIds(
77+
activeRegistry,
78+
metadataSnapshot.manifestRegistry.plugins,
79+
listRuntimePluginIdsFromRegistry(activeRegistry),
80+
)
81+
? activeRegistry
82+
: undefined;
83+
const registry =
84+
reusableGatewayRegistry ??
85+
loadAgentRuntimePluginRegistryHandle({
86+
config: input.config,
87+
env: input.env ?? process.env,
88+
...(input.workspaceDir ? { workspaceDir: input.workspaceDir } : {}),
89+
...(input.allowGatewaySubagentBinding ? { allowGatewaySubagentBinding: true } : {}),
90+
metadataSnapshot,
91+
preferBuiltPluginArtifacts: true,
92+
});
5693
registries.set(key, registry);
5794
return registry;
5895
};
@@ -76,16 +113,29 @@ export function prepareWorkspacePluginRegistries(
76113
const inboundPluginRegistry = input.readOnly
77114
? undefined
78115
: loadInboundRegistry?.(input, metadataSnapshot);
116+
// Extending the reused Gateway generation inherits its artifact preference: the
117+
// Gateway loader realizes built artifacts, so the delta load must not re-import
118+
// the same plugins through source transforms. Isolated loads keep source truth.
119+
const extendsActiveGatewayGeneration =
120+
inboundPluginRegistry !== undefined && inboundPluginRegistry === getActivePluginRegistry();
79121
const runtimePluginRegistry =
80122
input.runtimePluginSelections || !inboundPluginRegistry
81123
? loadAgentRuntimePluginRegistryHandle({
82-
...(input.loadRuntimePlugins ? { basePluginIds: [] } : {}),
124+
...(input.loadRuntimePlugins
125+
? { basePluginIds: [] }
126+
: inboundPluginRegistry
127+
? { basePluginIds: listRuntimePluginIdsFromRegistry(inboundPluginRegistry) }
128+
: {}),
83129
config: input.config,
84130
env: input.env ?? process.env,
85131
...(input.workspaceDir ? { workspaceDir: input.workspaceDir } : {}),
86132
...(input.allowGatewaySubagentBinding ? { allowGatewaySubagentBinding: true } : {}),
87133
metadataSnapshot,
88-
...(preferBuiltPluginArtifacts ? { preferBuiltPluginArtifacts: true } : {}),
134+
// Lifecycle-selected callers and delta loads extending the active Gateway
135+
// generation both stay on built artifacts; isolated loads keep source truth.
136+
...(preferBuiltPluginArtifacts || extendsActiveGatewayGeneration
137+
? { preferBuiltPluginArtifacts: true }
138+
: {}),
89139
selections: input.runtimePluginSelections,
90140
})
91141
: inboundPluginRegistry;

‎src/agents/prepared-model-runtime.plugin-context.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ describe("prepared model runtime plugin metadata ownership", () => {
7070
workspaceDir,
7171
});
7272
const resolveMetadata = vi
73-
.spyOn(pluginMetadata, "loadPluginMetadataSnapshot")
73+
.spyOn(pluginMetadata, "resolvePluginMetadataSnapshot")
7474
.mockReturnValue(directSnapshot);
7575
const registry = createEmptyPluginRegistry();
7676

@@ -94,6 +94,7 @@ describe("prepared model runtime plugin metadata ownership", () => {
9494
config,
9595
env: process.env,
9696
workspaceDir,
97+
allowWorkspaceScopedCurrent: true,
9798
});
9899
} finally {
99100
resolveMetadata.mockRestore();
@@ -109,7 +110,7 @@ describe("prepared model runtime plugin metadata ownership", () => {
109110
workspaceDir,
110111
});
111112
const resolveMetadata = vi
112-
.spyOn(pluginMetadata, "loadPluginMetadataSnapshot")
113+
.spyOn(pluginMetadata, "resolvePluginMetadataSnapshot")
113114
.mockReturnValue(directSnapshot);
114115

115116
try {
@@ -129,6 +130,7 @@ describe("prepared model runtime plugin metadata ownership", () => {
129130
config,
130131
env: process.env,
131132
workspaceDir,
133+
allowWorkspaceScopedCurrent: true,
132134
pluginIdScope: expect.objectContaining({ key: expect.any(String) }),
133135
});
134136
} finally {

‎src/agents/prepared-model-runtime.plugin-context.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { PluginDiscoveryResult } from "../plugins/discovery.js";
22
import { extractPluginInstallRecordsFromInstalledPluginIndex } from "../plugins/installed-plugin-index-install-records.js";
3-
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
3+
import { resolvePluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
44
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.types.js";
55
import type { PluginRegistry } from "../plugins/registry-types.js";
66
import {
@@ -74,10 +74,15 @@ function resolveColdMetadataSnapshot(
7474
input: PreparedModelRuntimeInput,
7575
env: NodeJS.ProcessEnv,
7676
): PluginMetadataSnapshot {
77-
const resolvedMetadataSnapshot = loadPluginMetadataSnapshot({
77+
// Resolve (slot-probing) instead of load: in the gateway the published current
78+
// generation satisfies this read, which keeps snapshot identity stable for the
79+
// generation-bound registry reuse in the inbound loader.
80+
const resolvedMetadataSnapshot = resolvePluginMetadataSnapshot({
7881
config: input.config,
7982
env,
80-
...(input.workspaceDir ? { workspaceDir: input.workspaceDir } : {}),
83+
...(input.workspaceDir
84+
? { workspaceDir: input.workspaceDir, allowWorkspaceScopedCurrent: true }
85+
: {}),
8186
...(input.loadRuntimePlugins && input.runtimePluginSelections && input.workspaceDir
8287
? {
8388
pluginIdScope: createAgentRuntimeMetadataPluginIdScope({

‎src/agents/prepared-model-runtime.startup-static.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,10 @@ describe("prepared model runtime Gateway catalog mode", () => {
407407
);
408408
expect(mocks.buildPreparedModelCatalogSnapshot).not.toHaveBeenCalled();
409409
expect(mocks.loadStaticCatalog).not.toHaveBeenCalled();
410-
expect(mocks.resolvePluginMetadataSnapshot).toHaveBeenCalledOnce();
410+
// Two slot-probing resolutions share the published generation: the prepared
411+
// cold plugin context and the model-id normalization lane. Neither builds a
412+
// catalog; the laziness guards above are the eager-work protections.
413+
expect(mocks.resolvePluginMetadataSnapshot).toHaveBeenCalledTimes(2);
411414
expect(configuredRuntimeModelCount).toBe(1);
412415
expect(generatedCatalogReadCount).toBe(0);
413416
const snapshot = getPreparedModelRuntimeSnapshot({

‎src/agents/runtime-plugins.test.ts‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
33

44
const hoisted = vi.hoisted(() => ({
55
loadPluginMetadataSnapshot: vi.fn(),
6+
getCurrentPluginMetadataSnapshot: vi.fn(),
67
getActivePluginRegistry: vi.fn(),
8+
getActivePluginRegistryWorkspaceDir: vi.fn(),
9+
getActivePluginRuntimeSubagentMode: vi.fn(),
710
loadPluginRegistryHandle: vi.fn(),
811
adoptRuntimeContextEngineRegistrations: vi.fn((target: unknown) => target),
912
adoptRuntimeWidgetPresenterRegistrations: vi.fn((target: unknown) => target),
@@ -19,6 +22,8 @@ vi.mock("../context-engine/registry.js", () => ({
1922

2023
vi.mock("../plugins/runtime.js", () => ({
2124
getActivePluginRegistry: hoisted.getActivePluginRegistry,
25+
getActivePluginRegistryWorkspaceDir: hoisted.getActivePluginRegistryWorkspaceDir,
26+
getActivePluginRuntimeSubagentMode: hoisted.getActivePluginRuntimeSubagentMode,
2227
}));
2328

2429
vi.mock("../plugins/widget-presenters.js", () => ({
@@ -29,6 +34,10 @@ vi.mock("../plugins/plugin-metadata-snapshot.js", () => ({
2934
loadPluginMetadataSnapshot: hoisted.loadPluginMetadataSnapshot,
3035
}));
3136

37+
vi.mock("../plugins/current-plugin-metadata-snapshot.js", () => ({
38+
getCurrentPluginMetadataSnapshot: hoisted.getCurrentPluginMetadataSnapshot,
39+
}));
40+
3241
vi.mock("../plugins/loader.js", () => ({
3342
loadPluginRegistryHandle: hoisted.loadPluginRegistryHandle,
3443
}));
@@ -42,6 +51,10 @@ import {
4251
getPluginRuntimeGatewayRequestScope,
4352
withPluginRuntimeRegistryScope,
4453
} from "../plugins/runtime/gateway-request-scope.js";
54+
import {
55+
createPreparedInboundRegistryLoader,
56+
prepareWorkspacePluginRegistries,
57+
} from "./prepared-model-runtime.inbound-registry.js";
4558
import {
4659
loadAgentRuntimePluginRegistryHandle,
4760
withAgentPluginRegistry,
@@ -68,7 +81,10 @@ describe("agent runtime plugin registries", () => {
6881
...createMetadataSnapshot(params.workspaceDir),
6982
pluginIds: undefined,
7083
}));
84+
hoisted.getCurrentPluginMetadataSnapshot.mockReset().mockReturnValue(undefined);
7185
hoisted.getActivePluginRegistry.mockReset().mockReturnValue(undefined);
86+
hoisted.getActivePluginRegistryWorkspaceDir.mockReset().mockReturnValue(undefined);
87+
hoisted.getActivePluginRuntimeSubagentMode.mockReset().mockReturnValue("default");
7288
hoisted.loadPluginRegistryHandle.mockReset().mockReturnValue({ handle: true });
7389
hoisted.adoptRuntimeContextEngineRegistrations
7490
.mockReset()
@@ -106,6 +122,113 @@ describe("agent runtime plugin registries", () => {
106122
);
107123
});
108124

125+
it("reuses the Gateway inbound registry and loads only its selected provider delta", () => {
126+
const config = {} as never;
127+
const gatewayPlugin = {
128+
id: "gateway-owned",
129+
origin: "bundled",
130+
rootDir: "/dist/extensions/gateway-owned",
131+
source: "/dist/extensions/gateway-owned/index.js",
132+
status: "loaded",
133+
};
134+
const activeRegistry = { plugins: [gatewayPlugin] };
135+
const selectedRegistry = { plugins: [gatewayPlugin, { id: "selected-provider" }] };
136+
const metadataSnapshot = {
137+
...createMetadataSnapshot("/tmp/default-workspace", undefined),
138+
manifestRegistry: {
139+
diagnostics: [],
140+
plugins: [
141+
{
142+
id: "gateway-owned",
143+
origin: "bundled",
144+
rootDir: "/extensions/gateway-owned",
145+
source: "/extensions/gateway-owned/index.ts",
146+
},
147+
],
148+
},
149+
};
150+
hoisted.getActivePluginRegistry.mockReturnValue(activeRegistry);
151+
hoisted.getActivePluginRuntimeSubagentMode.mockReturnValue("gateway-bindable");
152+
hoisted.getCurrentPluginMetadataSnapshot.mockImplementation(() => metadataSnapshot);
153+
hoisted.loadPluginRegistryHandle.mockReturnValue(selectedRegistry);
154+
hoisted.resolveAgentRuntimePluginLoadPlan.mockImplementation(({ basePluginIds }) => ({
155+
config,
156+
pluginIds: [...(basePluginIds ?? []), "selected-provider"],
157+
}));
158+
159+
const prepared = prepareWorkspacePluginRegistries(
160+
{
161+
agentDir: "/tmp/agent",
162+
allowGatewaySubagentBinding: true,
163+
config,
164+
runtimePluginSelections: [{ provider: "selected", modelId: "model" }],
165+
workspaceDir: "/tmp/default-workspace",
166+
},
167+
metadataSnapshot as never,
168+
createPreparedInboundRegistryLoader(),
169+
);
170+
171+
expect(prepared.inboundPluginRegistry).toBe(activeRegistry);
172+
expect(prepared.runtimePluginRegistry).toBe(selectedRegistry);
173+
expect(hoisted.loadPluginRegistryHandle).toHaveBeenCalledOnce();
174+
expect(hoisted.loadPluginRegistryHandle).toHaveBeenCalledWith(
175+
expect.objectContaining({
176+
onlyPluginIds: ["gateway-owned", "selected-provider"],
177+
}),
178+
);
179+
});
180+
181+
it("refuses Gateway registry reuse for a non-current metadata generation", () => {
182+
const config = {} as never;
183+
const gatewayPlugin = {
184+
id: "gateway-owned",
185+
origin: "bundled",
186+
rootDir: "/dist/extensions/gateway-owned",
187+
source: "/dist/extensions/gateway-owned/index.js",
188+
status: "loaded",
189+
};
190+
const activeRegistry = { plugins: [gatewayPlugin] };
191+
const metadataSnapshot = {
192+
...createMetadataSnapshot("/tmp/default-workspace", undefined),
193+
manifestRegistry: {
194+
diagnostics: [],
195+
plugins: [
196+
{
197+
id: "gateway-owned",
198+
origin: "bundled",
199+
rootDir: "/extensions/gateway-owned",
200+
source: "/extensions/gateway-owned/index.ts",
201+
},
202+
],
203+
},
204+
};
205+
hoisted.getActivePluginRegistry.mockReturnValue(activeRegistry);
206+
hoisted.getActivePluginRuntimeSubagentMode.mockReturnValue("gateway-bindable");
207+
// A different (older/leaked) generation is current: identity must fail closed.
208+
hoisted.getCurrentPluginMetadataSnapshot.mockReturnValue(
209+
createMetadataSnapshot("/tmp/default-workspace", undefined),
210+
);
211+
hoisted.loadPluginRegistryHandle.mockReturnValue({ plugins: [] });
212+
hoisted.resolveAgentRuntimePluginLoadPlan.mockImplementation(({ basePluginIds }) => ({
213+
config,
214+
pluginIds: basePluginIds,
215+
}));
216+
217+
const loadInboundRegistry = createPreparedInboundRegistryLoader();
218+
const inbound = loadInboundRegistry(
219+
{
220+
agentDir: "/tmp/agent",
221+
allowGatewaySubagentBinding: true,
222+
config,
223+
workspaceDir: "/tmp/default-workspace",
224+
},
225+
metadataSnapshot as never,
226+
);
227+
228+
expect(inbound).not.toBe(activeRegistry);
229+
expect(hoisted.loadPluginRegistryHandle).toHaveBeenCalled();
230+
});
231+
109232
it("keeps direct no-current loads on the requested workspace", () => {
110233
const config = {} as never;
111234
const env = { OPENCLAW_STATE_DIR: "/tmp/openclaw-state" };

0 commit comments

Comments
 (0)