Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

perf(eve): start a new session's first model step sooner (#5240)

Andrew Barbabb4afff5f61b
diff --git a/.changeset/inline-session-boot.md b/.changeset/inline-session-boot.md
new file mode 100644
index 000000000..78cee2012
--- /dev/null
+++ b/.changeset/inline-session-boot.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+New sessions start their first model step sooner, and later turns no longer wait for their cancellation hooks to register before their first step. Thanks @Lukavyi for reporting the startup latency in #876.
diff --git a/packages/eve/src/execution/session-inbox/inbox.test.ts b/packages/eve/src/execution/session-inbox/inbox.test.ts
index e0a63f311..76a3a69c2 100644
--- a/packages/eve/src/execution/session-inbox/inbox.test.ts
+++ b/packages/eve/src/execution/session-inbox/inbox.test.ts
@@ -606,6 +606,27 @@ describe("createSessionInbox", () => {
await inbox.dispose();
});
+ it("creates a hook at once and confirms it only after confirmAfter settles, even on failure", async () => {
+ const stable = createMockHook({
+ reads: [Promise.resolve(resolved(send("early")))],
+ token: "stable",
+ });
+ installHooks(stable);
+ const inbox = createSessionInbox("session-1");
+ const sessionCreation = Promise.withResolvers<never>();
+
+ const claim = inbox.claimSessionHook("stable", { confirmAfter: sessionCreation.promise });
+ expect(createHookMock).toHaveBeenCalledOnce();
+ await Promise.resolve();
+ expect(stable.getConflict).not.toHaveBeenCalled();
+ sessionCreation.reject(new Error("session creation failed"));
+
+ await expect(claim).resolves.toBeUndefined();
+ expect(stable.getConflict).toHaveBeenCalledOnce();
+ await expect(readResult(inbox)).resolves.toEqual(resolved(send("early")));
+ await inbox.dispose();
+ });
+
it("rejects empty tokens", async () => {
installHooks(createMockHook({ token: "stable" }), createMockHook({ token: "auth" }));
const inbox = createSessionInbox("session-1");
@@ -673,6 +694,7 @@ function authCallback(connectionName: string): SessionInboxPayload {
interface MockHook {
readonly dispose: ReturnType<typeof vi.fn>;
+ readonly getConflict: ReturnType<typeof vi.fn>;
readonly hook: unknown;
readonly return: ReturnType<typeof vi.fn>;
readonly token: string;
@@ -686,6 +708,7 @@ function createMockHook(input: {
}): MockHook {
const reads = [...(input.reads ?? [])];
const dispose = vi.fn();
+ const getConflict = vi.fn(async () => input.registration ?? input.conflict ?? null);
const iteratorReturn = vi.fn(async () => ({ done: true, value: undefined }) as const);
const hook = Object.assign(new Promise<SessionInboxPayload>(() => {}), {
[Symbol.asyncIterator]() {
@@ -701,10 +724,10 @@ function createMockHook(input: {
};
},
dispose,
- getConflict: vi.fn(async () => input.registration ?? input.conflict ?? null),
+ getConflict,
token: input.token,
});
- return { dispose, hook, return: iteratorReturn, token: input.token };
+ return { dispose, getConflict, hook, return: iteratorReturn, token: input.token };
}
function installHooks(...hooks: readonly MockHook[]): void {
diff --git a/packages/eve/src/execution/session-inbox/inbox.ts b/packages/eve/src/execution/session-inbox/inbox.ts
index f9df180a3..53e2e9aa1 100644
--- a/packages/eve/src/execution/session-inbox/inbox.ts
+++ b/packages/eve/src/execution/session-inbox/inbox.ts
@@ -107,6 +107,13 @@ export interface SessionHookClaimOptions {
* token this inbox already holds is claimed again on a fresh hook.
*/
readonly force?: boolean;
+ /**
+ * Creates the hook at once but confirms its registration only after this
+ * settles. While a registration is awaited, Workflow queues every step
+ * started beside it instead of running it inline, so a claim made next to a
+ * step confirms after that step; the hook still commits alongside it.
+ */
+ readonly confirmAfter?: Promise<unknown>;
}
export interface SessionHookBatchClaimOptions extends SessionHookClaimOptions {
@@ -348,7 +355,8 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {
}
stopped = false;
try {
- source.registered = claimHookOwnership(source.hook);
+ const confirm = () => claimHookOwnership(source.hook);
+ source.registered = options.confirmAfter?.then(confirm, confirm) ?? confirm();
await source.registered;
// A takeover this run has reclaimed from no longer counts toward the next one.
takenOver = false;
diff --git a/packages/eve/src/execution/session/entry.integration.test.ts b/packages/eve/src/execution/session/entry.integration.test.ts
index dc20b4b3a..5876eed11 100644
--- a/packages/eve/src/execution/session/entry.integration.test.ts
+++ b/packages/eve/src/execution/session/entry.integration.test.ts
@@ -100,53 +100,75 @@ describe("workflowEntry integration", () => {
}
});
});
- it("registers first-turn abort hooks before a prewarmed session receives a message", async () => {
- const runtime = await createTestRuntime({ agent: { name: "workflow-entry-turn-prewarm" } });
+ it.each([
+ { firstMessage: undefined, start: "a prewarmed session" },
+ { firstMessage: "Say hello.", start: "a session started with a message" },
+ ])(
+ "registers each turn's abort hooks before its message for $start",
+ async ({ firstMessage }) => {
+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-turn-prewarm" } });
- await runtime.run(async () => {
- const run = await start(workflowEntry, [
- {
- kind: "initial",
- ownerDeploymentId: "dpl_inline",
- input: {},
- serializedContext: buildSerializedContext({ channelKind: "http" }),
- sessionTimeoutMs: false,
- },
- ]);
- const stream = captureTurnEvents(run);
- try {
- await waitForHook(
- { runId: run.runId },
- { token: sessionInboxHookToken(sessionCommandHookToken(run.runId)) },
- );
- let abortTokensBeforeMessage: string[] = [];
- await vi.waitFor(async () => {
- abortTokensBeforeMessage = (
- await (await getWorld()).hooks.list({ runId: run.runId })
- ).data
- .map((hook) => hook.token)
- .filter((token) => token.startsWith("abrt_"));
- expect(abortTokensBeforeMessage).toHaveLength(2);
- });
-
- await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {
- kind: "send",
- payload: { message: "Say hello." },
- });
- await stream.nextTurn();
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ kind: "initial",
+ ownerDeploymentId: "dpl_inline",
+ input: firstMessage === undefined ? {} : { message: firstMessage },
+ serializedContext: buildSerializedContext({ channelKind: "http" }),
+ sessionTimeoutMs: false,
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+ const world = await getWorld();
+ const inboxToken = sessionInboxHookToken(sessionCommandHookToken(run.runId));
+ try {
+ await waitForHook({ runId: run.runId }, { token: inboxToken });
+ let turns = 0;
+ if (firstMessage !== undefined) {
+ await stream.nextTurn();
+ turns++;
+ }
+ for (const message of ["Say hello.", "Say hello again."].slice(turns)) {
+ await vi.waitFor(async () => {
+ const hooks = (await world.hooks.list({ runId: run.runId })).data;
+ expect(hooks.filter((hook) => hook.token.startsWith("abrt_"))).toHaveLength(
+ 2 * (turns + 1),
+ );
+ });
+ await resumeHook(inboxToken, { kind: "send", payload: { message } });
+ await stream.nextTurn();
+ turns++;
+ }
- const abortTokensAfterTurn = (
- await (await getWorld()).hooks.list({ runId: run.runId })
- ).data
- .map((hook) => hook.token)
- .filter((token) => token.startsWith("abrt_"));
- expect(abortTokensAfterTurn).toEqual(abortTokensBeforeMessage);
- } finally {
- stream.dispose();
- await run.cancel();
- }
- });
- });
+ const events = (
+ await world.events.list({
+ pagination: { limit: 1000 },
+ resolveData: "all",
+ runId: run.runId,
+ })
+ ).data;
+ let abortHooks = 0;
+ const abortHooksBeforeEachTurn: number[] = [];
+ for (const event of events) {
+ if (event.eventType === "hook_created" && event.eventData.token.startsWith("abrt_")) {
+ abortHooks++;
+ }
+ if (
+ event.eventType === "step_created" &&
+ event.eventData.stepName.endsWith("turnStep")
+ ) {
+ abortHooksBeforeEachTurn.push(abortHooks);
+ }
+ }
+ // Each turn uses the pair registered before its message; none starts its own.
+ expect(abortHooksBeforeEachTurn).toEqual([2, 4]);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ },
+ );
it("parks before initialization and initializes with the first message identity and title", async () => {
let initializedSessions = 0;
diff --git a/packages/eve/src/execution/session/entry.test.ts b/packages/eve/src/execution/session/entry.test.ts
index a039b77c3..c3cd59417 100644
--- a/packages/eve/src/execution/session/entry.test.ts
+++ b/packages/eve/src/execution/session/entry.test.ts
@@ -3,10 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { bootInitialOwner } from "#execution/session/entry.js";
import { createSessionStep } from "#execution/create-session-step.js";
import { createSessionInbox } from "#execution/session-inbox/inbox.js";
-import {
- cancelSessionTimeoutStep,
- startSessionTimeoutStep,
-} from "#execution/session/timeout-steps.js";
+import { startSessionTimeoutStep } from "#execution/session/timeout-steps.js";
import { resolveInitialTurnCallerStep } from "#subagents/parent-notification.js";
import { hasDelegatedSessionContext } from "#execution/delegated-session-context.js";
import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";
@@ -95,10 +92,8 @@ beforeEach(() => {
vi.clearAllMocks();
vi.mocked(createSessionStep).mockResolvedValue({ history: [], state: {} } as never);
vi.mocked(startSessionTimeoutStep).mockResolvedValue({ runId: "timeout-run-1" });
- vi.mocked(cancelSessionTimeoutStep).mockResolvedValue(undefined);
vi.mocked(createTurnControl).mockImplementation(() => ({
cancellation: new AbortController(),
- dispose: vi.fn(),
steering: new AbortController(),
}));
vi.mocked(resolveInitialTurnCallerStep).mockResolvedValue(undefined);
@@ -106,32 +101,31 @@ beforeEach(() => {
vi.mocked(settleContinuationConflictStep).mockResolvedValue(undefined);
});
-describe("bootInitialOwner timeout startup", () => {
- it("prepares controls and starts the timeout while session creation is pending", async () => {
+describe("bootInitialOwner", () => {
+ it("prepares turn controls and claims while session creation is pending, confirming after it", async () => {
const sessionCreation = deferred<never>();
- const timeoutStartup = deferred<{ runId: string }>();
const inbox = createInbox();
vi.mocked(createSessionStep).mockReturnValue(sessionCreation.promise);
- vi.mocked(startSessionTimeoutStep).mockReturnValue(timeoutStartup.promise);
vi.mocked(createSessionInbox).mockReturnValue(inbox as never);
const bootPromise = bootInitialOwner(initialInput(), "session-1");
- await vi.waitFor(() => expect(startSessionTimeoutStep).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(inbox.claimSessionHook).toHaveBeenCalledOnce());
+ expect(inbox.claimSessionHook).toHaveBeenCalledWith("eve:session:session-1:inbox", {
+ confirmAfter: sessionCreation.promise,
+ });
expect(createTurnControl).toHaveBeenCalledOnce();
- expect(inbox.claimSessionHook).toHaveBeenCalledWith("eve:session:session-1:inbox");
sessionCreation.resolve({ history: [], state: {} } as never);
const boot = await bootPromise;
expect(boot?.session.initialTurnControl).toBeDefined();
- expect(boot?.session.sessionTimeoutControl).toBeDefined();
- const loopStart = boot!.session.sessionTimeoutControl!.start();
+ // The session loop starts the timer, once ownership is confirmed.
+ expect(startSessionTimeoutStep).not.toHaveBeenCalled();
+ await boot!.session.sessionTimeoutControl!.start();
expect(startSessionTimeoutStep).toHaveBeenCalledOnce();
- timeoutStartup.resolve({ runId: "timeout-run-1" });
- await loopStart;
});
- it("waits for stable and alias ownership before starting the timeout", async () => {
+ it("waits for stable and alias ownership before returning", async () => {
const stableClaim = deferred<void>();
const aliasClaim = deferred<void>();
const inbox = createInbox();
@@ -139,6 +133,7 @@ describe("bootInitialOwner timeout startup", () => {
.mockImplementationOnce(async () => await stableClaim.promise)
.mockImplementationOnce(async () => await aliasClaim.promise);
vi.mocked(createSessionInbox).mockReturnValue(inbox as never);
+ let booted = false;
const bootPromise = bootInitialOwner(
initialInput({
@@ -148,22 +143,20 @@ describe("bootInitialOwner timeout startup", () => {
},
}),
"session-1",
- );
+ ).then((boot) => {
+ booted = true;
+ return boot;
+ });
await vi.waitFor(() => expect(inbox.claimSessionHook).toHaveBeenCalledTimes(2));
- expect(createTurnControl).not.toHaveBeenCalled();
- expect(startSessionTimeoutStep).not.toHaveBeenCalled();
stableClaim.resolve();
- await Promise.resolve();
- expect(createTurnControl).not.toHaveBeenCalled();
- expect(startSessionTimeoutStep).not.toHaveBeenCalled();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(booted).toBe(false);
aliasClaim.resolve();
await expect(bootPromise).resolves.toBeDefined();
- expect(createTurnControl).toHaveBeenCalledOnce();
- expect(startSessionTimeoutStep).toHaveBeenCalledOnce();
});
- it("settles an alias conflict without starting a timeout", async () => {
+ it("settles an alias conflict and releases the inbox", async () => {
const inbox = createInbox();
inbox.claimSessionHook
.mockResolvedValueOnce(undefined)
@@ -188,60 +181,32 @@ describe("bootInitialOwner timeout startup", () => {
command: continuationConflictCommand,
continuationToken: "channel:conversation-1",
});
- expect(createTurnControl).not.toHaveBeenCalled();
- expect(startSessionTimeoutStep).not.toHaveBeenCalled();
expect(inbox.dispose).toHaveBeenCalledOnce();
});
- it("cancels a started timeout when session creation fails", async () => {
- const sessionCreation = deferred<never>();
+ it.each([
+ {
+ fail: (failure: Error) => vi.mocked(createSessionStep).mockRejectedValue(failure),
+ source: "session creation",
+ },
+ {
+ fail: (failure: Error) => {
+ vi.mocked(hasDelegatedSessionContext).mockReturnValue(true);
+ vi.mocked(resolveInitialTurnCallerStep).mockRejectedValue(failure);
+ },
+ source: "delegated caller resolution",
+ },
+ ])("fails the session and releases the inbox when $source fails", async ({ fail }) => {
const inbox = createInbox();
- vi.mocked(createSessionStep).mockReturnValue(sessionCreation.promise);
vi.mocked(createSessionInbox).mockReturnValue(inbox as never);
- const failure = new Error("session creation failed");
+ const failure = new Error("boot failed");
+ fail(failure);
- const bootPromise = bootInitialOwner(initialInput(), "session-1");
- await vi.waitFor(() => expect(startSessionTimeoutStep).toHaveBeenCalledOnce());
- sessionCreation.reject(failure);
-
- await expect(bootPromise).rejects.toBe(failure);
- expect(cancelSessionTimeoutStep).toHaveBeenCalledWith({ runId: "timeout-run-1" });
- expect(vi.mocked(createTurnControl).mock.results[0]?.value.dispose).toHaveBeenCalledOnce();
+ await expect(bootInitialOwner(initialInput(), "session-1")).rejects.toBe(failure);
+ expect(mocks.failSession).toHaveBeenCalledOnce();
expect(inbox.dispose).toHaveBeenCalledOnce();
});
- it("cancels a started timeout when delegated caller resolution fails", async () => {
- const callerResolution = deferred<never>();
- const inbox = createInbox();
- vi.mocked(createSessionInbox).mockReturnValue(inbox as never);
- vi.mocked(hasDelegatedSessionContext).mockReturnValue(true);
- vi.mocked(resolveInitialTurnCallerStep).mockReturnValue(callerResolution.promise);
- const failure = new Error("caller resolution failed");
-
- const bootPromise = bootInitialOwner(initialInput(), "session-1");
- await vi.waitFor(() => expect(startSessionTimeoutStep).toHaveBeenCalledOnce());
- callerResolution.reject(failure);
-
- await expect(bootPromise).rejects.toBe(failure);
- expect(cancelSessionTimeoutStep).toHaveBeenCalledWith({ runId: "timeout-run-1" });
- expect(vi.mocked(createTurnControl).mock.results[0]?.value.dispose).toHaveBeenCalledOnce();
- expect(inbox.dispose).toHaveBeenCalledOnce();
- });
-
- it("carries timeout startup failures into the session loop", async () => {
- const inbox = createInbox();
- vi.mocked(createSessionInbox).mockReturnValue(inbox as never);
- const failure = new Error("timeout startup failed");
- vi.mocked(startSessionTimeoutStep).mockRejectedValue(failure);
-
- const boot = await bootInitialOwner(initialInput(), "session-1");
-
- await expect(boot?.session.sessionTimeoutControl?.start()).rejects.toBe(failure);
- expect(startSessionTimeoutStep).toHaveBeenCalledOnce();
- expect(cancelSessionTimeoutStep).not.toHaveBeenCalled();
- expect(inbox.dispose).not.toHaveBeenCalled();
- });
-
it("does not create a timeout when session timeouts are disabled", async () => {
const inbox = createInbox();
vi.mocked(createSessionInbox).mockReturnValue(inbox as never);
@@ -253,21 +218,4 @@ describe("bootInitialOwner timeout startup", () => {
expect(createTurnControl).toHaveBeenCalledOnce();
expect(startSessionTimeoutStep).not.toHaveBeenCalled();
});
-
- it("does not start a very short timeout until ownership is ready", async () => {
- const ownership = deferred<void>();
- const inbox = createInbox();
- inbox.claimSessionHook.mockImplementationOnce(async () => await ownership.promise);
- vi.mocked(createSessionInbox).mockReturnValue(inbox as never);
-
- const bootPromise = bootInitialOwner(initialInput({ sessionTimeoutMs: 1 }), "session-1");
- await vi.waitFor(() => expect(inbox.claimSessionHook).toHaveBeenCalledOnce());
- expect(createTurnControl).not.toHaveBeenCalled();
- expect(startSessionTimeoutStep).not.toHaveBeenCalled();
- ownership.resolve();
-
- await expect(bootPromise).resolves.toBeDefined();
- expect(createTurnControl).toHaveBeenCalledOnce();
- expect(startSessionTimeoutStep).toHaveBeenCalledOnce();
- });
});
diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.ts
index f2448f179..cf0adbc3c 100644
--- a/packages/eve/src/execution/session/entry.ts
+++ b/packages/eve/src/execution/session/entry.ts
@@ -99,7 +99,6 @@ interface OwnedInitialSession {
readonly kind: "owned";
readonly timeoutControl: SessionTimeoutControl | undefined;
readonly turnControl: TurnControl;
- dispose(): Promise<void>;
}
type InitialOwnerPreparation = OwnedInitialSession | { readonly kind: "alias-conflict" };
@@ -108,39 +107,36 @@ async function prepareInitialOwner(
inbox: SessionInboxHandle,
input: {
readonly continuationToken: string;
+ /** The claims confirm after it, so it runs inline while their hooks commit. */
+ readonly sessionCreation: Promise<unknown>;
readonly sessionId: string;
readonly sessionTimeoutMs: number | false;
},
): Promise<InitialOwnerPreparation> {
+ const owner: OwnedInitialSession = {
+ kind: "owned",
+ // The session loop starts the timer once the claims are confirmed; one
+ // started sooner could signal a command hook that is not registered yet.
+ timeoutControl: createSessionTimeoutControl({
+ sessionId: input.sessionId,
+ timeoutMs: input.sessionTimeoutMs,
+ }),
+ // Created before any await so its abort hooks commit with the session's
+ // hooks instead of beside the first turn's step.
+ turnControl: createTurnControl(),
+ };
+ const claim = { confirmAfter: input.sessionCreation };
const [stableClaim, aliasClaim] = await Promise.allSettled([
- inbox.claimSessionHook(sessionCommandHookToken(input.sessionId)),
+ inbox.claimSessionHook(sessionCommandHookToken(input.sessionId), claim),
input.continuationToken === ""
? Promise.resolve()
- : inbox.claimSessionHook(input.continuationToken),
+ : inbox.claimSessionHook(input.continuationToken, claim),
]);
if (stableClaim.status === "rejected") throw stableClaim.reason;
if (aliasClaim.status === "rejected") {
if (isHookConflictError(aliasClaim.reason)) return { kind: "alias-conflict" };
throw aliasClaim.reason;
}
-
- const turnControl = createTurnControl();
- const timeoutControl = createSessionTimeoutControl({
- sessionId: input.sessionId,
- timeoutMs: input.sessionTimeoutMs,
- });
- const owner: OwnedInitialSession = {
- kind: "owned",
- timeoutControl,
- turnControl,
- async dispose() {
- turnControl.dispose();
- await timeoutControl?.dispose();
- },
- };
- // The session loop joins this startup. Handling the promise here prevents a
- // rejection from becoming unhandled if another boot branch fails first.
- void timeoutControl?.start().catch(() => {});
return owner;
}
@@ -149,18 +145,6 @@ function unwrapSettled<T>(result: PromiseSettledResult<T>): T {
return result.value;
}
-async function disposeInitialBoot(
- inbox: SessionInboxHandle,
- owner: OwnedInitialSession | undefined,
-): Promise<void> {
- const [ownerDisposal, inboxDisposal] = await Promise.allSettled([
- owner?.dispose(),
- inbox.dispose(),
- ]);
- if (ownerDisposal.status === "rejected") throw ownerDisposal.reason;
- if (inboxDisposal.status === "rejected") throw inboxDisposal.reason;
-}
-
/** Returns `undefined` when a competing continuation owner already exists. */
export async function bootInitialOwner(
input: InitialWorkflowEntryInput,
@@ -175,7 +159,6 @@ export async function bootInitialOwner(
source: DurableCompiledArtifactsSource;
nodeId?: string;
};
- let owner: OwnedInitialSession | undefined;
try {
const sessionCreationPromise = createSessionStep({
agentSessionRuntimeOverrides: serializedContext["eve.agentSessionRuntimeOverrides"] as
@@ -195,6 +178,7 @@ export async function bootInitialOwner(
});
const ownerPreparationPromise = prepareInitialOwner(inbox, {
continuationToken,
+ sessionCreation: sessionCreationPromise,
sessionId,
sessionTimeoutMs,
});
@@ -206,9 +190,6 @@ export async function bootInitialOwner(
ownerPreparationPromise,
callerResolutionPromise,
]);
- if (ownerPreparation.status === "fulfilled" && ownerPreparation.value.kind === "owned") {
- owner = ownerPreparation.value;
- }
const created = unwrapSettled(sessionCreation);
const prepared = unwrapSettled(ownerPreparation);
if (prepared.kind === "alias-conflict") {
@@ -218,7 +199,7 @@ export async function bootInitialOwner(
continuationToken,
});
}
- await disposeInitialBoot(inbox, owner);
+ await inbox.dispose();
return undefined;
}
const caller = unwrapSettled(callerResolution);
@@ -246,7 +227,7 @@ export async function bootInitialOwner(
},
};
} catch (error) {
- await disposeInitialBoot(inbox, owner);
+ await inbox.dispose();
return await failSession({
error,
serializedContext,
diff --git a/packages/eve/src/execution/session/program.ts b/packages/eve/src/execution/session/program.ts
index 3aff59e51..90ea55509 100644
--- a/packages/eve/src/execution/session/program.ts
+++ b/packages/eve/src/execution/session/program.ts
@@ -399,6 +399,9 @@ async function runSessionLoop(
const transferred = await tryCompactionHandoff();
if (transferred !== undefined) return transferred;
+ // Registered while parked, so the next turn's first step is not held
+ // behind its abort hooks.
+ turnControl ??= createTurnControl();
const next = await nextParkedActivity();
switch (next.kind) {
@@ -431,7 +434,6 @@ async function runSessionLoop(
}
}
} finally {
- turnControl?.dispose();
await sessionTimeout?.dispose();
}
}
diff --git a/packages/eve/src/execution/session/turn-control.test.ts b/packages/eve/src/execution/session/turn-control.test.ts
index 11b5ac7a6..485d75481 100644
--- a/packages/eve/src/execution/session/turn-control.test.ts
+++ b/packages/eve/src/execution/session/turn-control.test.ts
@@ -22,14 +22,4 @@ describe("createTurnControl", () => {
expect(construct).toHaveBeenCalledTimes(2);
expect(control.cancellation).not.toBe(control.steering);
});
-
- it("retires both unused controls", () => {
- const control = createTurnControl();
-
- control.dispose();
- control.dispose();
-
- expect(control.cancellation.signal.aborted).toBe(true);
- expect(control.steering.signal.aborted).toBe(true);
- });
});
diff --git a/packages/eve/src/execution/session/turn-control.ts b/packages/eve/src/execution/session/turn-control.ts
index 654c6daac..2a98f0313 100644
--- a/packages/eve/src/execution/session/turn-control.ts
+++ b/packages/eve/src/execution/session/turn-control.ts
@@ -1,19 +1,13 @@
-/** Workflow-owned abort controls prepared before a turn begins. */
+/**
+ * Workflow-owned abort controls prepared before a turn begins. One that no
+ * turn uses is left open, as a finished turn's are: nothing listens to it,
+ * so aborting it would only add Workflow writes.
+ */
export interface TurnControl {
readonly cancellation: AbortController;
readonly steering: AbortController;
- dispose(): void;
}
export function createTurnControl(): TurnControl {
- const cancellation = new AbortController();
- const steering = new AbortController();
- return {
- cancellation,
- steering,
- dispose() {
- cancellation.abort();
- steering.abort();
- },
- };
+ return { cancellation: new AbortController(), steering: new AbortController() };
}
diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.ts
index 50ce70f3a..b51ddd05f 100644
--- a/packages/eve/src/execution/session/turn.ts
+++ b/packages/eve/src/execution/session/turn.ts
@@ -105,20 +105,14 @@ export class SessionExecution {
readonly control?: TurnControl;
} = {},
): Promise<TurnOutcome> {
- let turn: ActiveTurn;
- try {
- turn = new ActiveTurn(
- this.input,
- {
- caller: options.caller,
- principal: resolveTurnPrincipal(delivery, this.input.cursor.serializedContext),
- },
- options.control,
- );
- } catch (error) {
- options.control?.dispose();
- throw error;
- }
+ const turn = new ActiveTurn(
+ this.input,
+ {
+ caller: options.caller,
+ principal: resolveTurnPrincipal(delivery, this.input.cursor.serializedContext),
+ },
+ options.control,
+ );
try {
const outcome = await this.runTurnSteps(turn, delivery);
// Tasks run beside the turn, and a run can open a session after its call
diff --git a/packages/eve/src/internal/testing/entry-test-helpers.ts b/packages/eve/src/internal/testing/entry-test-helpers.ts
index a2eef6681..010bdbede 100644
--- a/packages/eve/src/internal/testing/entry-test-helpers.ts
+++ b/packages/eve/src/internal/testing/entry-test-helpers.ts
@@ -192,11 +192,7 @@ export async function withTimeout<T>(promise: Promise<T>, label: string): Promis
}
}
-export async function expectHookClaims(
- runId: string,
- tokens: string[],
- options: { readonly turnStarted?: boolean } = {},
-): Promise<void> {
+export async function expectHookClaims(runId: string, tokens: string[]): Promise<void> {
const events = await (
await getWorld()
).events.list({
@@ -207,8 +203,6 @@ export async function expectHookClaims(
const claims = events.data.flatMap((event) =>
event.eventType === "hook_created" ? [event.eventData.token] : [],
);
- const signals = claims.filter((token) => token.startsWith("abrt_"));
- expect(signals).toHaveLength(options.turnStarted === false ? 0 : 2);
expect(claims.filter((token) => !token.startsWith("abrt_")).sort()).toEqual(
tokens.map(sessionInboxHookToken).sort(),
);