Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

Avoid retrying incompatible session handoffs (#4032)

Karthik Kalyanf9c785ff8ffe
diff --git a/.changeset/handoff-incompatible-target.md b/.changeset/handoff-incompatible-target.md
new file mode 100644
index 000000000..2a49dac32
--- /dev/null
+++ b/.changeset/handoff-incompatible-target.md
@@ -0,0 +1,7 @@
+---
+"eve": patch
+---
+
+When a target deployment cannot read the session checkpoint version, validation returns incompatibility instead of throwing so Workflow no longer retries the step. The turn is processed on the current owner immediately.
+
+Owners running this eve build remember every deployment that reported incompatibility and skip handoff to those targets for later turns in the same run. Sessions whose owner workflow started on an older build still attempt handoff each turn, but each attempt no longer triggers validation retries on the target.
diff --git a/packages/eve/src/execution/session/entry-handoff.integration.test.ts b/packages/eve/src/execution/session/entry-handoff.integration.test.ts
index f5cd22c8b..29bc737c4 100644
--- a/packages/eve/src/execution/session/entry-handoff.integration.test.ts
+++ b/packages/eve/src/execution/session/entry-handoff.integration.test.ts
@@ -11,6 +11,7 @@ import {
} from "#internal/testing/session-test-helpers.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { workflowEntry } from "#execution/session/entry.js";
+import { SESSION_CHECKPOINT_VERSION } from "#execution/session/handoff.js";
import {
sessionCommandHookToken,
sessionInboxHookToken,
@@ -170,6 +171,180 @@ describe("workflowEntry integration", () => {
).toEqual([]);
});
+ it("stops attempting a deployment that cannot read the checkpoint version", async () => {
+ const output = captureConsoleOutput();
+ const runtime = await createTestRuntime({ agent: { name: "handoff-checkpoint-version" } });
+ await runtime.run(async () => {
+ const anchor = await start(workflowEntry, [
+ {
+ kind: "initial",
+ ownerDeploymentId: "dpl_a",
+ sessionTimeoutMs: false,
+ input: { message: "Alice opens a research session." },
+ serializedContext: buildSerializedContext({
+ acceptedDeploymentId: "dpl_a",
+ channelKind: "http",
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(anchor);
+ const world = await getWorld();
+ const workflowRuntime = createWorkflowRuntime({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ });
+ const rewritten = new Map<string, Promise<unknown>>();
+ const candidateIds = new Set<string>();
+ // Rewrites only the candidate checkpoint version. Owner and candidate both
+ // run this build, so the test covers successor validation and memoization
+ // on a current owner — not an owner workflow still on a pre-upgrade build.
+ const olderCheckpointInput = (runId: string, encoded: unknown): Promise<unknown> => {
+ let pending = rewritten.get(runId);
+ if (pending === undefined) {
+ pending = (async () => {
+ const args = (await hydrateWorkflowArguments(encoded, runId, undefined)) as [
+ HandoffWorkflowEntryInput,
+ ];
+ expect(args[0].kind).toBe("handoff");
+ candidateIds.add(runId);
+ Object.assign(args[0].checkpoint, { version: SESSION_CHECKPOINT_VERSION - 1 });
+
+ const operations: Promise<void>[] = [];
+ const result = await dehydrateWorkflowArguments(args, runId, undefined, operations);
+ await Promise.all(operations);
+ return result;
+ })();
+ rewritten.set(runId, pending);
+ }
+ return pending;
+ };
+ const createEvent = world.events.create.bind(world.events);
+ const created = vi.spyOn(world.events, "create").mockImplementation(async (...args) => {
+ const [runId] = args;
+ const event = args[1] as (typeof args)[1] | RunCreatedEventRequest;
+ if (event.eventType === "run_created" && event.eventData.deploymentId === "dpl_b") {
+ event.eventData.input = await olderCheckpointInput(runId, event.eventData.input);
+ }
+ return createEvent(...args);
+ });
+ const queue = world.queue.bind(world);
+ const queued = vi.spyOn(world, "queue").mockImplementation(async (...args) => {
+ const message = args[1] as {
+ runId?: string;
+ runInput?: { deploymentId?: string; input: unknown };
+ };
+ if (message.runId !== undefined && message.runInput?.deploymentId === "dpl_b") {
+ message.runInput.input = await olderCheckpointInput(
+ message.runId,
+ message.runInput.input,
+ );
+ }
+ return queue(...args);
+ });
+ const handoffMarkerClaims = async (): Promise<number> => {
+ const events = await world.events.list({
+ pagination: { limit: 1000 },
+ resolveData: "all",
+ runId: anchor.runId,
+ });
+ return events.data.filter(
+ (event) =>
+ event.eventType === "hook_created" &&
+ event.eventData.token.startsWith("eve:inbox:handoff:"),
+ ).length;
+ };
+ try {
+ await stream.nextTurn();
+ await waitForParkedTurnStep(anchor.runId);
+
+ await workflowRuntime.dispatchSession({
+ command: handoffFollowUp("dpl_b", "Bob requests the first research step.", "version-1"),
+ sessionId: anchor.runId,
+ });
+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");
+ await waitForParkedTurnStep(anchor.runId, 2);
+ expect(candidateIds.size).toBe(1);
+ const markersAfterAttempt = await handoffMarkerClaims();
+ expect(markersAfterAttempt).toBeGreaterThan(0);
+
+ await workflowRuntime.dispatchSession({
+ command: handoffFollowUp(
+ "dpl_b",
+ "Bob requests the second research step.",
+ "version-2",
+ ),
+ sessionId: anchor.runId,
+ });
+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");
+ await waitForParkedTurnStep(anchor.runId, 3);
+ // The remembered target is skipped before any candidate or marker exists.
+ expect(candidateIds.size).toBe(1);
+ expect(await handoffMarkerClaims()).toBe(markersAfterAttempt);
+
+ const [candidateId] = candidateIds;
+ const candidateEvents = await world.events.list({
+ pagination: { limit: 1000 },
+ resolveData: "none",
+ runId: candidateId!,
+ });
+ // An unreadable version is an answer, not a fault: validation runs once.
+ expect(
+ candidateEvents.data.filter(
+ (event) => event.eventType === "step_failed" || event.eventType === "step_retrying",
+ ),
+ ).toEqual([]);
+
+ expect(
+ (
+ await waitForCommandHookOwner(
+ sessionInboxHookToken(sessionCommandHookToken(anchor.runId)),
+ )
+ ).runId,
+ ).toBe(anchor.runId);
+ await vi.waitFor(
+ async () => {
+ // Recorded steps are not returned in turn order; the settled
+ // history is the one that accumulated every turn.
+ const settled = (await readTurnStepStates(anchor.runId))
+ .map((state) => state.sessionState.snapshot.session.history)
+ .reduce<readonly unknown[]>(
+ (longest, history) => (history.length > longest.length ? history : longest),
+ [],
+ ) as readonly { role: string; content: unknown }[];
+ const delivered = (message: string) =>
+ settled.filter(
+ (entry) =>
+ entry.role === "user" && JSON.stringify(entry.content).includes(message),
+ );
+ expect(delivered("Bob requests the first research step.")).toHaveLength(1);
+ expect(delivered("Bob requests the second research step.")).toHaveLength(1);
+ },
+ { timeout: 5000 },
+ );
+
+ // A different deployment is unproven, so it earns a fresh attempt.
+ await workflowRuntime.dispatchSession({
+ command: handoffFollowUp("dpl_c", "Bob requests a third research step.", "version-3"),
+ sessionId: anchor.runId,
+ });
+ await stream.nextTurn();
+ const successor = await waitForCommandHookOwner(
+ sessionInboxHookToken(sessionCommandHookToken(anchor.runId)),
+ );
+ expect(successor.runId).not.toBe(anchor.runId);
+ } finally {
+ created.mockRestore();
+ queued.mockRestore();
+ stream.dispose();
+ await anchor.cancel();
+ }
+ });
+ expect(output.lines).toContainEqual(
+ expect.stringContaining(workflowSdkNotice.unpinnedDelivery),
+ );
+ // No validation retry: the SDK never reports an exhausted step.
+ expect(output.unexpected(workflowSdkNotice.unpinnedDelivery)).toEqual([]);
+ });
+
it("retains a message accepted just before durable hook disposal", async () => {
const runtime = await createTestRuntime({ agent: { name: "workflow-entry-handoff" } });
diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.ts
index 1fbae3088..1a580d50b 100644
--- a/packages/eve/src/execution/session/entry.ts
+++ b/packages/eve/src/execution/session/entry.ts
@@ -165,7 +165,15 @@ async function bootHandoffOwner(
const serializedContext = stampSessionIdentity(checkpoint.serializedContext, sessionId);
const inbox = createSessionInbox(sessionId);
try {
- await validateSessionCheckpointStep({ checkpoint });
+ const validation = await validateSessionCheckpointStep({ checkpoint });
+ if (validation.kind === "incompatible") {
+ const payloads = await inbox.release();
+ await signalSessionOwnerActivationStep({
+ activation: { kind: "incompatible", payloads, reason: validation.reason },
+ token: input.activationToken,
+ });
+ return undefined;
+ }
await inbox.claimSessionHooks(
sessionHookTokens({ serializedContext, sessionState: checkpoint.sessionState }),
);
diff --git a/packages/eve/src/execution/session/handoff-steps.test.ts b/packages/eve/src/execution/session/handoff-steps.test.ts
index 13ea14545..582996a6b 100644
--- a/packages/eve/src/execution/session/handoff-steps.test.ts
+++ b/packages/eve/src/execution/session/handoff-steps.test.ts
@@ -27,7 +27,7 @@ describe("validateSessionCheckpointStep", () => {
readDurableSessionMock.mockReturnValue({});
const checkpoint = createCheckpoint();
- await validateSessionCheckpointStep({ checkpoint });
+ await expect(validateSessionCheckpointStep({ checkpoint })).resolves.toEqual({ kind: "valid" });
expect(require).toHaveBeenCalledWith(BundleKey);
expect(readDurableSessionMock).toHaveBeenCalledWith(checkpoint.sessionState);
@@ -56,15 +56,16 @@ describe("validateSessionCheckpointStep", () => {
});
it.each([5, 6, 7, 8, 9, 11])(
- "rejects checkpoint version %s before reading nested state",
+ "reports checkpoint version %s as incompatible before reading nested state",
async (version) => {
const checkpoint = createCheckpoint();
// Simulate an incompatible checkpoint received over the wire.
Object.assign(checkpoint, { version });
- await expect(validateSessionCheckpointStep({ checkpoint })).rejects.toThrow(
- `Unsupported session checkpoint version ${version}`,
- );
+ await expect(validateSessionCheckpointStep({ checkpoint })).resolves.toEqual({
+ kind: "incompatible",
+ reason: "checkpoint-version",
+ });
expect(deserializeContextMock).not.toHaveBeenCalled();
expect(readDurableSessionMock).not.toHaveBeenCalled();
},
diff --git a/packages/eve/src/execution/session/handoff-steps.ts b/packages/eve/src/execution/session/handoff-steps.ts
index 724e8cff8..297b0763a 100644
--- a/packages/eve/src/execution/session/handoff-steps.ts
+++ b/packages/eve/src/execution/session/handoff-steps.ts
@@ -47,16 +47,23 @@ export async function isSessionIdleForHandoffStep(input: {
return isSessionStateIdleForHandoff(input.sessionState);
}
-/** Validates a checkpoint and resolves the target deployment's compiled bundle. */
+export type SessionCheckpointValidation =
+ | { readonly kind: "valid" }
+ | { readonly kind: "incompatible"; readonly reason: "checkpoint-version" };
+
+/**
+ * Validates a checkpoint and resolves the target deployment's compiled bundle.
+ *
+ * A version mismatch is a settled answer about this deployment, not a fault, so
+ * it returns rather than throws: retrying the step can never change it.
+ */
export async function validateSessionCheckpointStep(input: {
readonly checkpoint: SessionCheckpoint;
-}): Promise<void> {
+}): Promise<SessionCheckpointValidation> {
"use step";
const { checkpoint } = input;
if (checkpoint.version !== SESSION_CHECKPOINT_VERSION) {
- throw new Error(
- `Unsupported session checkpoint version ${JSON.stringify(checkpoint.version)}; this deployment reads version ${SESSION_CHECKPOINT_VERSION}. Keep the session on its original deployment or start a new session here.`,
- );
+ return { kind: "incompatible", reason: "checkpoint-version" };
}
const timeout = checkpoint.sessionTimeoutMs;
if (
@@ -87,6 +94,7 @@ export async function validateSessionCheckpointStep(input: {
if (!isSessionStateIdleForHandoff(checkpoint.sessionState)) {
throw new Error("Session checkpoint contains pending work and cannot be handed off.");
}
+ return { kind: "valid" };
}
export async function signalSessionOwnerActivationStep(input: {
diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.ts
index 7e2bc7813..78431433e 100644
--- a/packages/eve/src/execution/session/handoff.test.ts
+++ b/packages/eve/src/execution/session/handoff.test.ts
@@ -133,6 +133,60 @@ describe("SessionHandoff", () => {
expect(inbox.restore).toHaveBeenCalledWith(payloads);
});
+ it("remembers every incompatible target for the rest of the owner run", async () => {
+ const inbox = createInbox();
+ const payloads: SessionInboxPayload[] = [
+ { kind: "send", payload: { message: "Alice sends a follow-up." } },
+ ];
+ installActivationSequence(
+ { kind: "incompatible", payloads, reason: "checkpoint-version" },
+ { kind: "incompatible", payloads, reason: "checkpoint-version" },
+ );
+ startSessionOwnerStepMock.mockResolvedValue(undefined);
+ const handoff = createHandoff(inbox);
+
+ await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({
+ kind: "retained",
+ reason: "checkpoint-incompatible",
+ });
+ expect(inbox.restore).toHaveBeenCalledWith(payloads);
+
+ await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({
+ kind: "retained",
+ reason: "known-incompatible",
+ });
+ expect(startSessionOwnerStepMock).toHaveBeenCalledTimes(1);
+ expect(inbox.release).toHaveBeenCalledTimes(1);
+
+ await expect(handoff.tryTransfer(selection("deployment-c"), state())).resolves.toEqual({
+ kind: "retained",
+ reason: "checkpoint-incompatible",
+ });
+ expect(startSessionOwnerStepMock).toHaveBeenCalledTimes(2);
+
+ await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({
+ kind: "retained",
+ reason: "known-incompatible",
+ });
+ expect(startSessionOwnerStepMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("attempts handoff on every turn when the owner only sees a generic activation failure", async () => {
+ installActivation({ error: new Error("unsupported checkpoint"), kind: "failed", payloads: [] });
+ startSessionOwnerStepMock.mockResolvedValue(undefined);
+ const handoff = createHandoff(createInbox());
+
+ await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({
+ kind: "retained",
+ reason: "activation-failed",
+ });
+ await expect(handoff.tryTransfer(selection("deployment-b"), state())).resolves.toEqual({
+ kind: "retained",
+ reason: "activation-failed",
+ });
+ expect(startSessionOwnerStepMock).toHaveBeenCalledTimes(2);
+ });
+
it("abandons transfer when input was accepted during release", async () => {
installActivation({ kind: "active" });
const accepted: SessionInboxPayload[] = [{ kind: "send", payload: { message: "late" } }];
@@ -152,9 +206,16 @@ function createdHooks() {
}
function installActivation(activation: SessionOwnerActivation): void {
+ installActivationSequence(activation);
+}
+
+function installActivationSequence(...activations: SessionOwnerActivation[]): void {
created.length = 0;
+ let index = 0;
createHookMock.mockImplementation((options: { token: string }) => {
- const resolved = options.token.endsWith(":anchor") ? { output: "done" } : activation;
+ const resolved = options.token.endsWith(":anchor")
+ ? { output: "done" }
+ : (activations[Math.min(index++, activations.length - 1)] ?? activations.at(-1)!);
const hook = Object.assign(Promise.resolve(resolved), {
dispose: vi.fn(),
getConflict: vi.fn(async () => null),
diff --git a/packages/eve/src/execution/session/handoff.ts b/packages/eve/src/execution/session/handoff.ts
index eb916820f..2508d4d7f 100644
--- a/packages/eve/src/execution/session/handoff.ts
+++ b/packages/eve/src/execution/session/handoff.ts
@@ -34,6 +34,14 @@ export interface SessionCheckpoint {
export type SessionOwnerActivation =
| { readonly kind: "active" }
+ | {
+ // Owners running older eve builds read every non-`active` result as a
+ // failure, so this variant carries `payloads` in the same shape.
+ readonly kind: "incompatible";
+ readonly reason: "checkpoint-version";
+ /** Commands accepted by partial successor claims before it rejected the checkpoint. */
+ readonly payloads: readonly SessionInboxPayload[];
+ }
| {
readonly kind: "failed";
readonly error: unknown;
@@ -51,7 +59,9 @@ type SessionTransferOutcome =
| "not-idle"
| "busy"
| "accepted-during-release"
- | "activation-failed";
+ | "activation-failed"
+ | "checkpoint-incompatible"
+ | "known-incompatible";
};
interface SessionHandoffInput {
@@ -70,10 +80,18 @@ export function sessionAnchorToken(sessionId: string): string {
* The sole boundary for moving an idle session to another exact deployment.
* Constructed once per owner; `tryTransfer()` is attempted per eligible selection.
* When the upstream atomic hook-handoff primitive lands, only this class changes.
+ *
+ * Skipping known-incompatible targets requires this owner run to execute the
+ * `incompatible` activation branch below. Owners still on an older eve build
+ * treat that signal as a generic failure and attempt handoff on every turn;
+ * they still benefit from successors returning incompatibility without step
+ * retries.
*/
export class SessionHandoff {
private readonly input: SessionHandoffInput;
private anchor: Hook<WorkflowEntryResult> | undefined;
+ /** Deployments that rejected this session's checkpoint during this owner run. */
+ private readonly incompatibleTargetDeploymentIds = new Set<string>();
constructor(input: SessionHandoffInput) {
this.input = input;
@@ -92,6 +110,8 @@ export class SessionHandoff {
const targetDeploymentId = readAcceptedDeploymentId(selection.delivery);
if (targetDeploymentId === undefined) return { kind: "retained", reason: "missing-deployment" };
if (targetDeploymentId === deploymentId) return { kind: "retained", reason: "same-deployment" };
+ if (this.incompatibleTargetDeploymentIds.has(targetDeploymentId))
+ return { kind: "retained", reason: "known-incompatible" };
if (!selection.handoffEligible) return { kind: "retained", reason: "busy" };
if (!(await isSessionIdleForHandoffStep(state)))
return { kind: "retained", reason: "not-idle" };
@@ -125,6 +145,11 @@ export class SessionHandoff {
targetDeploymentId,
);
if (activation.kind === "active") return { kind: "transferred" };
+ if (activation.kind === "incompatible") {
+ this.incompatibleTargetDeploymentIds.add(targetDeploymentId);
+ await this.recover(tokens, activation.payloads);
+ return { kind: "retained", reason: "checkpoint-incompatible" };
+ }
acceptedByFailedCandidate = activation.payloads;
} catch {
// The current owner remains authoritative until activation.