Skip to content

Commit 0fea415

Browse files
committed
perf(cron): carry the published plugin generation into hook/cron isolated runs
Hook dispatch and the cron scheduler rebuilt process-stable plugin metadata on every isolated run: prepareCronRunContext reloaded a metadata snapshot per run inside loadAgentRuntimePluginRegistryHandle (installed-plugin-index safeHashFile ~2.2s, doctor contract artifact resolution ~1.8s, realpathSync walks), and the embedded orchestrator rebuilt-and-froze another snapshot plus a fresh prepared-runtime owner per run — ~5-6s aggregate synchronous work across a 13-run gmail hook burst even after #130167 removed the cold full-registry load. The channel path already carries dispatchRuntime.pluginGeneration (#125596) and the gateway agent RPC carries commandRuntimeContext.pluginGeneration. This completes the same carry at the isolated-run owner: prepareCronRunContext reuses the published model-catalog owner's metadataSnapshot for the run registry handle, and runCronIsolatedAgentTurn admits the published Gateway generation (static prepared-runtime lease + withPreparedModelRuntimePluginGenerationScope with a borrow accessor, mirroring runPreparedReply) so the embedded orchestrator reuses the generation instead of rebuilding it. Standalone hosts and startup/replacement races keep generation-free execution. Live proof on an isolated dev gateway: plugins.metadata.scan timeline spans stayed at the 22 startup scans across two full isolated cron runs (zero per-run rebuilds); regression tests fail pre-fix.
1 parent 93d879d commit 0fea415

4 files changed

Lines changed: 215 additions & 6 deletions

File tree

‎src/cron/isolated-agent/run-prepare.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,9 @@ export async function prepareCronRunContext(params: {
642642
config: cfgWithAgentDefaults,
643643
workspaceDir,
644644
allowGatewaySubagentBinding: true,
645+
// The published owner already selected this run's metadata generation.
646+
// Reloading it here re-hashes every installed plugin on each hook/cron run.
647+
...(modelOwner.metadataSnapshot ? { metadataSnapshot: modelOwner.metadataSnapshot } : {}),
645648
selections: runtimePluginCandidates.map((candidate) => {
646649
const runtime = resolveSessionRuntimeOverrideForProvider({
647650
provider: candidate.provider,
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// Proves isolated cron/hook runs carry the published Gateway plugin generation
2+
// into embedded execution instead of rebuilding metadata per run (#125596 family).
3+
import { describe, expect, it, vi } from "vitest";
4+
import { getPreparedModelRuntimePluginGeneration } from "../../agents/prepared-model-runtime-generation-scope.js";
5+
import { makeIsolatedAgentParamsFixture } from "./job-fixtures.js";
6+
import { setupRunCronIsolatedAgentTurnSuite } from "./run.suite-helpers.js";
7+
import {
8+
loadRunCronIsolatedAgentTurn,
9+
mockRunCronFallbackPassthrough,
10+
runEmbeddedAgentMock,
11+
} from "./run.test-harness.js";
12+
13+
const preparedRuntimeMocks = vi.hoisted(() => ({
14+
acquireRuntime: vi.fn(),
15+
loadDispatchRuntime: vi.fn(),
16+
}));
17+
18+
vi.mock("../../agents/prepared-model-runtime.js", async (importOriginal) => ({
19+
...(await importOriginal<typeof import("../../agents/prepared-model-runtime.js")>()),
20+
acquireAgentRunPreparedModelRuntime: preparedRuntimeMocks.acquireRuntime,
21+
loadPublishedGatewayReplyDispatchRuntime: preparedRuntimeMocks.loadDispatchRuntime,
22+
}));
23+
24+
const { PreparedModelRuntimeOwnerNotPublishedError } = await vi.importActual<
25+
typeof import("../../agents/prepared-model-runtime.errors.js")
26+
>("../../agents/prepared-model-runtime.errors.js");
27+
28+
const runCronIsolatedAgentTurn = await loadRunCronIsolatedAgentTurn();
29+
30+
describe("runCronIsolatedAgentTurn plugin generation carry", () => {
31+
setupRunCronIsolatedAgentTurnSuite();
32+
33+
it("admits the published generation and keeps it active through embedded execution", async () => {
34+
const metadataSnapshot = { plugins: [], index: { plugins: [] } };
35+
const pluginGeneration = {
36+
configuredCatalogEntries: [],
37+
inlineProviderModels: [],
38+
pluginMetadataSnapshot: metadataSnapshot,
39+
} as never;
40+
const config = {};
41+
preparedRuntimeMocks.loadDispatchRuntime.mockResolvedValue({
42+
agentId: "default",
43+
agentDir: "/tmp/dispatch-agent-dir",
44+
workspaceDir: "/tmp/dispatch-workspace",
45+
config,
46+
pluginGeneration,
47+
});
48+
const release = vi.fn();
49+
preparedRuntimeMocks.acquireRuntime.mockResolvedValue({
50+
snapshot: { config, metadataSnapshot },
51+
release,
52+
});
53+
mockRunCronFallbackPassthrough();
54+
let embeddedRunGeneration: unknown = "not-captured";
55+
runEmbeddedAgentMock.mockImplementation(async () => {
56+
embeddedRunGeneration = getPreparedModelRuntimePluginGeneration();
57+
return { payloads: [{ text: "test output" }], meta: { agentMeta: {} } };
58+
});
59+
60+
await expect(runCronIsolatedAgentTurn(makeIsolatedAgentParamsFixture())).resolves.toMatchObject(
61+
{ status: "ok" },
62+
);
63+
expect(preparedRuntimeMocks.loadDispatchRuntime).toHaveBeenCalledWith({ agentId: "default" });
64+
expect(preparedRuntimeMocks.acquireRuntime).toHaveBeenCalledWith(
65+
{
66+
config,
67+
agentId: "default",
68+
agentDir: "/tmp/dispatch-agent-dir",
69+
allowGatewaySubagentBinding: true,
70+
workspaceDir: "/tmp/workspace",
71+
},
72+
{ catalogMode: "static", pluginGeneration },
73+
);
74+
expect(embeddedRunGeneration).toBe(pluginGeneration);
75+
expect(release).toHaveBeenCalledOnce();
76+
expect(getPreparedModelRuntimePluginGeneration()).toBeUndefined();
77+
});
78+
79+
it("runs without a generation when no Gateway publication exists", async () => {
80+
preparedRuntimeMocks.loadDispatchRuntime.mockResolvedValue(undefined);
81+
mockRunCronFallbackPassthrough();
82+
let embeddedRunGeneration: unknown = "not-captured";
83+
runEmbeddedAgentMock.mockImplementation(async () => {
84+
embeddedRunGeneration = getPreparedModelRuntimePluginGeneration();
85+
return { payloads: [{ text: "test output" }], meta: { agentMeta: {} } };
86+
});
87+
88+
await expect(runCronIsolatedAgentTurn(makeIsolatedAgentParamsFixture())).resolves.toMatchObject(
89+
{ status: "ok" },
90+
);
91+
expect(preparedRuntimeMocks.acquireRuntime).not.toHaveBeenCalled();
92+
expect(embeddedRunGeneration).toBeUndefined();
93+
});
94+
95+
it("falls back to generation-free execution when the owner is not published", async () => {
96+
preparedRuntimeMocks.loadDispatchRuntime.mockRejectedValue(
97+
new PreparedModelRuntimeOwnerNotPublishedError("owner not published"),
98+
);
99+
100+
await expect(runCronIsolatedAgentTurn(makeIsolatedAgentParamsFixture())).resolves.toMatchObject(
101+
{ status: "ok" },
102+
);
103+
expect(preparedRuntimeMocks.acquireRuntime).not.toHaveBeenCalled();
104+
});
105+
});

‎src/cron/isolated-agent/run.runtime-plugins.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,27 @@ describe("runCronIsolatedAgentTurn runtime plugin owner", () => {
4848
],
4949
});
5050
});
51+
52+
it("reuses the published owner metadata snapshot for the run registry load", async () => {
53+
const metadataSnapshot = { plugins: [], index: { plugins: [] } };
54+
loadModelCatalogOwnerMock.mockImplementation(
55+
async (params: { agentId?: string; config: object }) => ({
56+
agentId: params.agentId ?? "default",
57+
agentDir: "/tmp/agent-dir",
58+
workspaceDir: "/tmp/workspace",
59+
config: params.config,
60+
metadataSnapshot,
61+
modelCatalog: { entries: [], routeVariants: [] },
62+
}),
63+
);
64+
65+
await expect(runCronIsolatedAgentTurn(makeIsolatedAgentParamsFixture())).resolves.toMatchObject(
66+
{ status: "ok" },
67+
);
68+
expect(loadAgentRuntimePluginRegistryHandleMock).toHaveBeenCalledOnce();
69+
// Exact snapshot identity: a rebuilt copy would still re-hash every installed plugin.
70+
expect(loadAgentRuntimePluginRegistryHandleMock.mock.calls[0]?.[0].metadataSnapshot).toBe(
71+
metadataSnapshot,
72+
);
73+
});
5174
});

‎src/cron/isolated-agent/run.ts‎

Lines changed: 84 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
11
import { retireSessionMcpRuntime } from "../../agents/agent-bundle-mcp-tools.js";
2+
import { withPreparedModelRuntimePluginGenerationScope } from "../../agents/prepared-model-runtime-generation-scope.js";
3+
import {
4+
PreparedModelRuntimeOwnerNotPublishedError,
5+
acquireAgentRunPreparedModelRuntime,
6+
loadPublishedGatewayReplyDispatchRuntime,
7+
} from "../../agents/prepared-model-runtime.js";
8+
import type {
9+
PreparedModelRuntimePluginGeneration,
10+
PreparedModelRuntimeSnapshot,
11+
} from "../../agents/prepared-model-runtime.types.js";
212
import { createAgentRunRestartAbortError } from "../../agents/run-termination.js";
313
import { cleanupBrowserSessionsForLifecycleEnd } from "../../browser-lifecycle-cleanup.js";
414
import type { CliDeps } from "../../cli/outbound-send-deps.js";
@@ -41,6 +51,60 @@ import { cleanupCronRunSessionAfterRun } from "./session-cleanup.js";
4151

4252
const cronExecutorRuntimeLoader = createLazyImportLoader(() => import("./run-executor.runtime.js"));
4353

54+
type CronRunPluginGenerationLease = {
55+
pluginGeneration: PreparedModelRuntimePluginGeneration;
56+
borrowSnapshot: () => PreparedModelRuntimeSnapshot | undefined;
57+
release: () => void;
58+
};
59+
60+
/**
61+
* Gateway-hosted isolated runs reuse the published plugin generation instead of
62+
* rebuilding metadata snapshots per run (#125596 carried this for the channel
63+
* path; hook/cron turns share the invariant). Standalone hosts (no Gateway
64+
* lifecycle) and startup/replacement races return undefined so the embedded
65+
* orchestrator admits on whatever generation is current at execution time.
66+
*/
67+
async function acquireCronRunPluginGeneration(context: {
68+
agentId: string;
69+
workspaceDir: string;
70+
}): Promise<CronRunPluginGenerationLease | undefined> {
71+
try {
72+
const dispatchRuntime = await loadPublishedGatewayReplyDispatchRuntime({
73+
agentId: context.agentId,
74+
});
75+
if (!dispatchRuntime) {
76+
return undefined;
77+
}
78+
// Holding this static lease across the run anchors the admitted generation:
79+
// a config/plugin reload mid-run lets nested embedded admissions borrow the
80+
// leased snapshot instead of failing on the superseded configured owner.
81+
const lease = await acquireAgentRunPreparedModelRuntime(
82+
{
83+
config: dispatchRuntime.config,
84+
agentId: dispatchRuntime.agentId,
85+
agentDir: dispatchRuntime.agentDir,
86+
allowGatewaySubagentBinding: true,
87+
workspaceDir: context.workspaceDir,
88+
},
89+
{ catalogMode: "static", pluginGeneration: dispatchRuntime.pluginGeneration },
90+
);
91+
let leaseActive = true;
92+
return {
93+
pluginGeneration: dispatchRuntime.pluginGeneration,
94+
borrowSnapshot: () => (leaseActive ? lease.snapshot : undefined),
95+
release: () => {
96+
leaseActive = false;
97+
lease.release();
98+
},
99+
};
100+
} catch (error) {
101+
if (error instanceof PreparedModelRuntimeOwnerNotPublishedError) {
102+
return undefined;
103+
}
104+
throw error;
105+
}
106+
}
107+
44108
function isCronNestedLaneTaskTimeoutError(err: unknown): boolean {
45109
return isCommandLaneTaskTimeoutError(err, CommandLane.CronNested);
46110
}
@@ -259,13 +323,27 @@ export async function runCronIsolatedAgentTurn(params: {
259323
pluginRegistry: prepared.context.pluginRegistry,
260324
executionIdentity: params.executionIdentity,
261325
};
262-
const execution = await prepared.context.sessionWorkAdmission.run(() =>
263-
withAgentRunLifecycleGeneration(runLifecycleGeneration, () =>
264-
withPluginRuntimeRegistryScope(prepared.context.pluginRegistry, () =>
265-
executeCronRun(executionParams),
326+
const runExecutionWithAdmission = () =>
327+
prepared.context.sessionWorkAdmission.run(() =>
328+
withAgentRunLifecycleGeneration(runLifecycleGeneration, () =>
329+
withPluginRuntimeRegistryScope(prepared.context.pluginRegistry, () =>
330+
executeCronRun(executionParams),
331+
),
266332
),
267-
),
268-
);
333+
);
334+
const pluginGenerationLease = await acquireCronRunPluginGeneration(prepared.context);
335+
let execution: Awaited<ReturnType<typeof runExecutionWithAdmission>>;
336+
try {
337+
execution = pluginGenerationLease
338+
? await withPreparedModelRuntimePluginGenerationScope(
339+
pluginGenerationLease.pluginGeneration,
340+
runExecutionWithAdmission,
341+
pluginGenerationLease.borrowSnapshot,
342+
)
343+
: await runExecutionWithAdmission();
344+
} finally {
345+
pluginGenerationLease?.release();
346+
}
269347
const finalized = await finalizeCronRun({
270348
prepared: prepared.context,
271349
execution,

0 commit comments

Comments
 (0)