From bdc0c924ce04e547ce68dec409cedfee0bb334db Mon Sep 17 00:00:00 2001 From: Peter Steinberger Date: Wed, 26 Aug 2026 19:08:38 -0700 Subject: [PATCH] perf(cron): carry the published plugin generation into hook/cron isolated runs (#130581) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/cron/isolated-agent/run-prepare.ts | 3 + .../run.plugin-generation.test.ts | 105 ++++++++++++++++++ .../run.runtime-plugins.test.ts | 23 ++++ src/cron/isolated-agent/run.ts | 90 ++++++++++++++- 4 files changed, 215 insertions(+), 6 deletions(-) create mode 100644 src/cron/isolated-agent/run.plugin-generation.test.ts diff --git a/src/cron/isolated-agent/run-prepare.ts b/src/cron/isolated-agent/run-prepare.ts index 6a5018f45a1..cbfc17226c8 100644 --- a/src/cron/isolated-agent/run-prepare.ts +++ b/src/cron/isolated-agent/run-prepare.ts @@ -642,6 +642,9 @@ export async function prepareCronRunContext(params: { config: cfgWithAgentDefaults, workspaceDir, allowGatewaySubagentBinding: true, + // The published owner already selected this run's metadata generation. + // Reloading it here re-hashes every installed plugin on each hook/cron run. + ...(modelOwner.metadataSnapshot ? { metadataSnapshot: modelOwner.metadataSnapshot } : {}), selections: runtimePluginCandidates.map((candidate) => { const runtime = resolveSessionRuntimeOverrideForProvider({ provider: candidate.provider, diff --git a/src/cron/isolated-agent/run.plugin-generation.test.ts b/src/cron/isolated-agent/run.plugin-generation.test.ts new file mode 100644 index 00000000000..748f89db4fb --- /dev/null +++ b/src/cron/isolated-agent/run.plugin-generation.test.ts @@ -0,0 +1,105 @@ +// Proves isolated cron/hook runs carry the published Gateway plugin generation +// into embedded execution instead of rebuilding metadata per run (#125596 family). +import { describe, expect, it, vi } from "vitest"; +import { getPreparedModelRuntimePluginGeneration } from "../../agents/prepared-model-runtime-generation-scope.js"; +import { makeIsolatedAgentParamsFixture } from "./job-fixtures.js"; +import { setupRunCronIsolatedAgentTurnSuite } from "./run.suite-helpers.js"; +import { + loadRunCronIsolatedAgentTurn, + mockRunCronFallbackPassthrough, + runEmbeddedAgentMock, +} from "./run.test-harness.js"; + +const preparedRuntimeMocks = vi.hoisted(() => ({ + acquireRuntime: vi.fn(), + loadDispatchRuntime: vi.fn(), +})); + +vi.mock("../../agents/prepared-model-runtime.js", async (importOriginal) => ({ + ...(await importOriginal()), + acquireAgentRunPreparedModelRuntime: preparedRuntimeMocks.acquireRuntime, + loadPublishedGatewayReplyDispatchRuntime: preparedRuntimeMocks.loadDispatchRuntime, +})); + +const { PreparedModelRuntimeOwnerNotPublishedError } = await vi.importActual< + typeof import("../../agents/prepared-model-runtime.errors.js") +>("../../agents/prepared-model-runtime.errors.js"); + +const runCronIsolatedAgentTurn = await loadRunCronIsolatedAgentTurn(); + +describe("runCronIsolatedAgentTurn plugin generation carry", () => { + setupRunCronIsolatedAgentTurnSuite(); + + it("admits the published generation and keeps it active through embedded execution", async () => { + const metadataSnapshot = { plugins: [], index: { plugins: [] } }; + const pluginGeneration = { + configuredCatalogEntries: [], + inlineProviderModels: [], + pluginMetadataSnapshot: metadataSnapshot, + } as never; + const config = {}; + preparedRuntimeMocks.loadDispatchRuntime.mockResolvedValue({ + agentId: "default", + agentDir: "/tmp/dispatch-agent-dir", + workspaceDir: "/tmp/dispatch-workspace", + config, + pluginGeneration, + }); + const release = vi.fn(); + preparedRuntimeMocks.acquireRuntime.mockResolvedValue({ + snapshot: { config, metadataSnapshot }, + release, + }); + mockRunCronFallbackPassthrough(); + let embeddedRunGeneration: unknown = "not-captured"; + runEmbeddedAgentMock.mockImplementation(async () => { + embeddedRunGeneration = getPreparedModelRuntimePluginGeneration(); + return { payloads: [{ text: "test output" }], meta: { agentMeta: {} } }; + }); + + await expect(runCronIsolatedAgentTurn(makeIsolatedAgentParamsFixture())).resolves.toMatchObject( + { status: "ok" }, + ); + expect(preparedRuntimeMocks.loadDispatchRuntime).toHaveBeenCalledWith({ agentId: "default" }); + expect(preparedRuntimeMocks.acquireRuntime).toHaveBeenCalledWith( + { + config, + agentId: "default", + agentDir: "/tmp/dispatch-agent-dir", + allowGatewaySubagentBinding: true, + workspaceDir: "/tmp/workspace", + }, + { catalogMode: "static", pluginGeneration }, + ); + expect(embeddedRunGeneration).toBe(pluginGeneration); + expect(release).toHaveBeenCalledOnce(); + expect(getPreparedModelRuntimePluginGeneration()).toBeUndefined(); + }); + + it("runs without a generation when no Gateway publication exists", async () => { + preparedRuntimeMocks.loadDispatchRuntime.mockResolvedValue(undefined); + mockRunCronFallbackPassthrough(); + let embeddedRunGeneration: unknown = "not-captured"; + runEmbeddedAgentMock.mockImplementation(async () => { + embeddedRunGeneration = getPreparedModelRuntimePluginGeneration(); + return { payloads: [{ text: "test output" }], meta: { agentMeta: {} } }; + }); + + await expect(runCronIsolatedAgentTurn(makeIsolatedAgentParamsFixture())).resolves.toMatchObject( + { status: "ok" }, + ); + expect(preparedRuntimeMocks.acquireRuntime).not.toHaveBeenCalled(); + expect(embeddedRunGeneration).toBeUndefined(); + }); + + it("falls back to generation-free execution when the owner is not published", async () => { + preparedRuntimeMocks.loadDispatchRuntime.mockRejectedValue( + new PreparedModelRuntimeOwnerNotPublishedError("owner not published"), + ); + + await expect(runCronIsolatedAgentTurn(makeIsolatedAgentParamsFixture())).resolves.toMatchObject( + { status: "ok" }, + ); + expect(preparedRuntimeMocks.acquireRuntime).not.toHaveBeenCalled(); + }); +}); diff --git a/src/cron/isolated-agent/run.runtime-plugins.test.ts b/src/cron/isolated-agent/run.runtime-plugins.test.ts index 462fc2cd93a..ea38e33ef69 100644 --- a/src/cron/isolated-agent/run.runtime-plugins.test.ts +++ b/src/cron/isolated-agent/run.runtime-plugins.test.ts @@ -48,4 +48,27 @@ describe("runCronIsolatedAgentTurn runtime plugin owner", () => { ], }); }); + + it("reuses the published owner metadata snapshot for the run registry load", async () => { + const metadataSnapshot = { plugins: [], index: { plugins: [] } }; + loadModelCatalogOwnerMock.mockImplementation( + async (params: { agentId?: string; config: object }) => ({ + agentId: params.agentId ?? "default", + agentDir: "/tmp/agent-dir", + workspaceDir: "/tmp/workspace", + config: params.config, + metadataSnapshot, + modelCatalog: { entries: [], routeVariants: [] }, + }), + ); + + await expect(runCronIsolatedAgentTurn(makeIsolatedAgentParamsFixture())).resolves.toMatchObject( + { status: "ok" }, + ); + expect(loadAgentRuntimePluginRegistryHandleMock).toHaveBeenCalledOnce(); + // Exact snapshot identity: a rebuilt copy would still re-hash every installed plugin. + expect(loadAgentRuntimePluginRegistryHandleMock.mock.calls[0]?.[0].metadataSnapshot).toBe( + metadataSnapshot, + ); + }); }); diff --git a/src/cron/isolated-agent/run.ts b/src/cron/isolated-agent/run.ts index d4c6926a73b..b897201b077 100644 --- a/src/cron/isolated-agent/run.ts +++ b/src/cron/isolated-agent/run.ts @@ -1,4 +1,14 @@ import { retireSessionMcpRuntime } from "../../agents/agent-bundle-mcp-tools.js"; +import { withPreparedModelRuntimePluginGenerationScope } from "../../agents/prepared-model-runtime-generation-scope.js"; +import { + PreparedModelRuntimeOwnerNotPublishedError, + acquireAgentRunPreparedModelRuntime, + loadPublishedGatewayReplyDispatchRuntime, +} from "../../agents/prepared-model-runtime.js"; +import type { + PreparedModelRuntimePluginGeneration, + PreparedModelRuntimeSnapshot, +} from "../../agents/prepared-model-runtime.types.js"; import { createAgentRunRestartAbortError } from "../../agents/run-termination.js"; import { cleanupBrowserSessionsForLifecycleEnd } from "../../browser-lifecycle-cleanup.js"; import type { CliDeps } from "../../cli/outbound-send-deps.js"; @@ -41,6 +51,60 @@ import { cleanupCronRunSessionAfterRun } from "./session-cleanup.js"; const cronExecutorRuntimeLoader = createLazyImportLoader(() => import("./run-executor.runtime.js")); +type CronRunPluginGenerationLease = { + pluginGeneration: PreparedModelRuntimePluginGeneration; + borrowSnapshot: () => PreparedModelRuntimeSnapshot | undefined; + release: () => void; +}; + +/** + * Gateway-hosted isolated runs reuse the published plugin generation instead of + * rebuilding metadata snapshots per run (#125596 carried this for the channel + * path; hook/cron turns share the invariant). Standalone hosts (no Gateway + * lifecycle) and startup/replacement races return undefined so the embedded + * orchestrator admits on whatever generation is current at execution time. + */ +async function acquireCronRunPluginGeneration(context: { + agentId: string; + workspaceDir: string; +}): Promise { + try { + const dispatchRuntime = await loadPublishedGatewayReplyDispatchRuntime({ + agentId: context.agentId, + }); + if (!dispatchRuntime) { + return undefined; + } + // Holding this static lease across the run anchors the admitted generation: + // a config/plugin reload mid-run lets nested embedded admissions borrow the + // leased snapshot instead of failing on the superseded configured owner. + const lease = await acquireAgentRunPreparedModelRuntime( + { + config: dispatchRuntime.config, + agentId: dispatchRuntime.agentId, + agentDir: dispatchRuntime.agentDir, + allowGatewaySubagentBinding: true, + workspaceDir: context.workspaceDir, + }, + { catalogMode: "static", pluginGeneration: dispatchRuntime.pluginGeneration }, + ); + let leaseActive = true; + return { + pluginGeneration: dispatchRuntime.pluginGeneration, + borrowSnapshot: () => (leaseActive ? lease.snapshot : undefined), + release: () => { + leaseActive = false; + lease.release(); + }, + }; + } catch (error) { + if (error instanceof PreparedModelRuntimeOwnerNotPublishedError) { + return undefined; + } + throw error; + } +} + function isCronNestedLaneTaskTimeoutError(err: unknown): boolean { return isCommandLaneTaskTimeoutError(err, CommandLane.CronNested); } @@ -259,13 +323,27 @@ export async function runCronIsolatedAgentTurn(params: { pluginRegistry: prepared.context.pluginRegistry, executionIdentity: params.executionIdentity, }; - const execution = await prepared.context.sessionWorkAdmission.run(() => - withAgentRunLifecycleGeneration(runLifecycleGeneration, () => - withPluginRuntimeRegistryScope(prepared.context.pluginRegistry, () => - executeCronRun(executionParams), + const runExecutionWithAdmission = () => + prepared.context.sessionWorkAdmission.run(() => + withAgentRunLifecycleGeneration(runLifecycleGeneration, () => + withPluginRuntimeRegistryScope(prepared.context.pluginRegistry, () => + executeCronRun(executionParams), + ), ), - ), - ); + ); + const pluginGenerationLease = await acquireCronRunPluginGeneration(prepared.context); + let execution: Awaited>; + try { + execution = pluginGenerationLease + ? await withPreparedModelRuntimePluginGenerationScope( + pluginGenerationLease.pluginGeneration, + runExecutionWithAdmission, + pluginGenerationLease.borrowSnapshot, + ) + : await runExecutionWithAdmission(); + } finally { + pluginGenerationLease?.release(); + } const finalized = await finalizeCronRun({ prepared: prepared.context, execution,