perf(cron): carry the published plugin generation into hook/cron isolated runs (#130581)

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.
This commit is contained in:
Peter Steinberger authored and GitHub committed 2026-08-26 19:08:38 -07:00
1 parent 89d6ce457c
commit bdc0c924ce
4 files changed
+215 -6

No files matched your search

+3
View File
@@ -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,
@@ -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<typeof import("../../agents/prepared-model-runtime.js")>()),
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();
});
});
@@ -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,
);
});
});
+84 -6
View File
@@ -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<CronRunPluginGenerationLease | undefined> {
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<ReturnType<typeof runExecutionWithAdmission>>;
try {
execution = pluginGenerationLease
? await withPreparedModelRuntimePluginGenerationScope(
pluginGenerationLease.pluginGeneration,
runExecutionWithAdmission,
pluginGenerationLease.borrowSnapshot,
)
: await runExecutionWithAdmission();
} finally {
pluginGenerationLease?.release();
}
const finalized = await finalizeCronRun({
prepared: prepared.context,
execution,