Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): cancel orphaned workflow runs in local workflow world (#3816)

prhac004ac890616
diff --git a/.changeset/quiet-local-workflow-cleanup.md b/.changeset/quiet-local-workflow-cleanup.md
new file mode 100644
index 000000000..3be0bec8a
--- /dev/null
+++ b/.changeset/quiet-local-workflow-cleanup.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`eve dev` now cancels unfinished local Workflow runs whose development snapshots are gone, instead of repeatedly reporting them as startup errors. Runs with retained snapshots still recover across restarts, and cancelled runs record why they can no longer resume.
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index afb793df6..626c2f492 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -232,6 +232,8 @@ Local dev records the last ready URL per resolved app root in `.eve/dev-server-s
Local dev keeps immutable runtime generations under `.eve/dev-runtime/snapshots/` so in-flight turns hold a consistent code revision while new turns pick up rebuilds. Each generation contains the compiled authored module graph and runtime resources rather than a recursive copy of the app or workspace. The terminal REPL keeps its logical session across successful rebuilds, so the next turn continues the conversation on the latest generation; `/new` terminally retires that session before clearing the transcript, and the next prompt starts a fresh session with a new session-scoped sandbox on first sandbox use. After a generation is superseded, `eve dev` retains it for at least 30 minutes and also retains the five most recently superseded generations, regardless of the configured Workflow World. The active generation is never pruned. Old runtime snapshots and local sandbox templates are pruned in the background. For manual cleanup, stop `eve dev` before deleting `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`. A turn that remains unfinished beyond the automatic retention window can no longer resume after its generation is pruned.
+With the built-in local Workflow World, `eve dev` cancels unfinished runs whose runtime snapshots are missing, at startup and after snapshot pruning. This includes waiting conversations and session timeout workflows. Cancellation records the reason in the run history without a terminal warning; normal run-data retention still applies. Stopping `eve dev` does not cancel runs whose snapshots remain available: the next start recovers them. This cleanup does not apply to a custom Workflow World.
+
Local development records traces under `.eve/traces/` by default and bounds that store by age, size, and a keep-newest floor. Configure it with `EVE_TRACES*` in `.env.local`, or disable the destination with `agent/instrumentation/local.ts`; see [`eve traces`](#retention) for the rules and defaults.
`eve acp` reserves stdin and stdout for newline-delimited JSON-RPC and sends diagnostics to stderr. Without a URL, it supervises an isolated local development server. With a URL, it bridges ACP to that server's existing eve HTTP API. See [Agent Client Protocol (ACP)](../protocols/acp) for client configuration and capability limits.
diff --git a/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts b/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts
index e9d3bdef5..034a67078 100644
--- a/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts
+++ b/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts
@@ -318,9 +318,7 @@ export function readActiveDevelopmentRuntimeArtifactsSnapshot(
};
}
-/**
- * Reads a revision token for the latest dev runtime artifact snapshot.
- */
+/** Reads a revision token for the latest dev runtime artifact snapshot. */
export function readDevelopmentRuntimeArtifactsRevision(
appRoot: string,
): DevelopmentRuntimeArtifactsRevision {
diff --git a/packages/eve/src/internal/nitro/development-generation.test.ts b/packages/eve/src/internal/nitro/development-generation.test.ts
index e4b8e726e..05b383f90 100644
--- a/packages/eve/src/internal/nitro/development-generation.test.ts
+++ b/packages/eve/src/internal/nitro/development-generation.test.ts
@@ -5,7 +5,7 @@ import type { CompileAgentResult } from "#compiler/compile-agent.js";
const mocks = vi.hoisted(() => ({
activateTransaction: vi.fn(),
- prune: vi.fn(async () => undefined),
+ prune: vi.fn(async (): Promise<void> => undefined),
prepare: vi.fn(),
stage: vi.fn(),
materialize: vi.fn(),
@@ -123,6 +123,66 @@ describe("development generation activation", () => {
expect(mocks.prune).toHaveBeenCalledWith({ appRoot: "/tmp/app-commit" });
});
+ it("reconciles only after pruning and preserves requests made during failed reconciliation", async () => {
+ mocks.activateTransaction.mockResolvedValue({ commit: vi.fn(), rollback: vi.fn() });
+ const pruning = Promise.withResolvers<void>();
+ const reconciliation = Promise.withResolvers<void>();
+ mocks.prune.mockReturnValueOnce(pruning.promise);
+ const onRuntimePruned = vi
+ .fn()
+ .mockReturnValueOnce(reconciliation.promise)
+ .mockResolvedValue(undefined);
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const input = {
+ appRoot: "/tmp/app-reconcile",
+ generation: createGeneration("one"),
+ onRuntimePruned,
+ };
+ try {
+ await activateDevelopmentGeneration(input);
+ expect(onRuntimePruned).not.toHaveBeenCalled();
+ pruning.resolve();
+ await vi.waitFor(() => expect(onRuntimePruned).toHaveBeenCalledOnce());
+ await activateDevelopmentGeneration({ ...input, generation: createGeneration("two") });
+ reconciliation.reject(new Error("storage unavailable"));
+ await vi.waitFor(() => expect(onRuntimePruned).toHaveBeenCalledTimes(2));
+ expect(mocks.prune).toHaveBeenCalledTimes(2);
+ expect(warning).toHaveBeenCalledExactlyOnceWith(
+ "[eve:dev] failed to reconcile expired Workflow runs: Error: storage unavailable",
+ );
+ } finally {
+ pruning.resolve();
+ reconciliation.resolve();
+ warning.mockRestore();
+ }
+ });
+
+ it("does not reconcile failed pruning and retries a pending prune request", async () => {
+ mocks.activateTransaction.mockResolvedValue({ commit: vi.fn(), rollback: vi.fn() });
+ const pruning = Promise.withResolvers<void>();
+ mocks.prune.mockReturnValueOnce(pruning.promise);
+ const onRuntimePruned = vi.fn(async () => undefined);
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const input = {
+ appRoot: "/tmp/app-prune-failure",
+ generation: createGeneration("one"),
+ onRuntimePruned,
+ };
+ try {
+ await activateDevelopmentGeneration(input);
+ await activateDevelopmentGeneration(input);
+ pruning.reject(new Error("filesystem unavailable"));
+ await vi.waitFor(() => expect(onRuntimePruned).toHaveBeenCalledOnce());
+ expect(mocks.prune).toHaveBeenCalledTimes(2);
+ expect(warning).toHaveBeenCalledExactlyOnceWith(
+ "[eve:dev] failed to prune runtime generations: Error: filesystem unavailable",
+ );
+ } finally {
+ pruning.resolve();
+ warning.mockRestore();
+ }
+ });
+
it("does not request pruning when an activation rolls back", async () => {
const commit = vi.fn();
const rollback = vi.fn(async () => undefined);
diff --git a/packages/eve/src/internal/nitro/development-generation.ts b/packages/eve/src/internal/nitro/development-generation.ts
index 406f78ba0..f1b279df6 100644
--- a/packages/eve/src/internal/nitro/development-generation.ts
+++ b/packages/eve/src/internal/nitro/development-generation.ts
@@ -22,6 +22,7 @@ export interface DevelopmentGeneration extends DevelopmentRuntimeArtifactsSnapsh
interface DevelopmentGenerationPruneState {
requested: boolean;
running: Promise<void> | undefined;
+ onRuntimePruned?: () => Promise<void>;
}
const developmentGenerationPruneStates = new Map<string, DevelopmentGenerationPruneState>();
@@ -85,6 +86,7 @@ export async function stageDevelopmentGeneration(
export async function activateDevelopmentGeneration(input: {
readonly appRoot: string;
readonly generation: DevelopmentGeneration;
+ readonly onRuntimePruned?: () => Promise<void>;
}): Promise<void> {
const activation = await activateDevelopmentGenerationTransaction(input);
activation.commit();
@@ -93,6 +95,7 @@ export async function activateDevelopmentGeneration(input: {
export async function activateDevelopmentGenerationTransaction(input: {
readonly appRoot: string;
readonly generation: DevelopmentGeneration;
+ readonly onRuntimePruned?: () => Promise<void>;
}): Promise<DevelopmentRuntimeArtifactsActivation> {
const activation = await activateDevelopmentRuntimeArtifactsSnapshotTransaction({
appRoot: input.appRoot,
@@ -106,7 +109,7 @@ export async function activateDevelopmentGenerationTransaction(input: {
}
settled = true;
activation.commit();
- requestDevelopmentGenerationPrune(input.appRoot);
+ requestDevelopmentGenerationPrune(input.appRoot, input.onRuntimePruned);
},
async rollback() {
if (settled) {
@@ -124,13 +127,17 @@ export async function discardDevelopmentGeneration(
await rm(generation.snapshotRoot, { force: true, recursive: true });
}
-function requestDevelopmentGenerationPrune(appRoot: string): void {
- const state = developmentGenerationPruneStates.get(appRoot) ?? {
+function requestDevelopmentGenerationPrune(
+ appRoot: string,
+ onRuntimePruned: (() => Promise<void>) | undefined,
+): void {
+ const state: DevelopmentGenerationPruneState = developmentGenerationPruneStates.get(appRoot) ?? {
requested: false,
running: undefined,
};
developmentGenerationPruneStates.set(appRoot, state);
state.requested = true;
+ state.onRuntimePruned = onRuntimePruned;
if (state.running === undefined) {
startDevelopmentGenerationPruning(appRoot, state);
}
@@ -143,7 +150,13 @@ function startDevelopmentGenerationPruning(
state.running = (async () => {
while (state.requested) {
state.requested = false;
+ const onRuntimePruned = state.onRuntimePruned;
await pruneDevelopmentRuntimeArtifactsSnapshots({ appRoot });
+ try {
+ await onRuntimePruned?.();
+ } catch (error) {
+ console.warn(`[eve:dev] failed to reconcile expired Workflow runs: ${String(error)}`);
+ }
}
})()
.catch((error) => {
diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts
index af9cc77b8..a4c5b406c 100644
--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts
+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts
@@ -124,12 +124,13 @@ const createRunner: DevelopmentRunnerFactory = () => {
};
};
-async function createCoordinatorWithServer() {
+async function createCoordinatorWithServer(onRuntimePruned?: () => Promise<void>) {
const devServer = new DrainedNitroDevServer({ error: () => undefined }, createRunner);
mocks.computeDevelopmentHostFingerprint.mockResolvedValueOnce("host-1");
const coordinator = await createDevelopmentAuthoredRebuildCoordinator({
devServer,
initialHost: createHost("initial", "run-1"),
+ onRuntimePruned,
});
return { coordinator, devServer };
}
@@ -139,6 +140,27 @@ beforeEach(() => {
});
describe("transactional authored rebuild coordinator", () => {
+ it.each(["host-1", "host-2"])(
+ "forwards reconciliation on activation with host fingerprint %s",
+ async (fingerprint) => {
+ const onRuntimePruned = vi.fn(async () => undefined);
+ const { coordinator, devServer } = await createCoordinatorWithServer(onRuntimePruned);
+ const candidate = createHost("candidate", "run-2");
+ mocks.prepareDevelopmentApplicationHost.mockResolvedValueOnce(candidate);
+ mocks.computeDevelopmentHostFingerprint.mockResolvedValueOnce(fingerprint);
+ try {
+ await coordinator.rebuild({ changedPaths: [] });
+ expect(mocks.activateDevelopmentGeneration).toHaveBeenCalledWith({
+ appRoot: candidate.appRoot,
+ generation: candidate.generation,
+ onRuntimePruned,
+ });
+ } finally {
+ await devServer.close();
+ }
+ },
+ );
+
it("passes changed paths into extension preparation and retains its committed watch plan", async () => {
const { coordinator, devServer } = await createCoordinatorWithServer();
const candidate = createHost("candidate", "run-1");
diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts
index ec80d6570..b864a4308 100644
--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts
+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts
@@ -57,6 +57,7 @@ export async function createDevelopmentAuthoredRebuildCoordinator(input: {
readonly developmentExtensions?: DevelopmentExtensionSelection;
readonly devServer: DrainedNitroDevServer;
readonly initialHost: PreparedDevelopmentApplicationHost;
+ readonly onRuntimePruned?: () => Promise<void>;
}): Promise<DevelopmentAuthoredRebuildCoordinator> {
return new TransactionalDevelopmentAuthoredRebuildCoordinator({
currentHostFingerprint: await computeDevelopmentHostFingerprint(input.initialHost),
@@ -64,6 +65,7 @@ export async function createDevelopmentAuthoredRebuildCoordinator(input: {
currentRuntimeFingerprint: input.initialHost.generation.fingerprint,
devServer: input.devServer,
initialHost: input.initialHost,
+ onRuntimePruned: input.onRuntimePruned,
});
}
@@ -84,6 +86,7 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentA
readonly #developmentExtensions: DevelopmentExtensionSelection | undefined;
readonly #devServer: DrainedNitroDevServer;
readonly #usesParentWorkflowWorld: boolean;
+ readonly #onRuntimePruned: (() => Promise<void>) | undefined;
constructor(input: {
readonly currentHostFingerprint: string;
@@ -91,8 +94,10 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentA
readonly developmentExtensions: DevelopmentExtensionSelection | undefined;
readonly devServer: DrainedNitroDevServer;
readonly initialHost: PreparedDevelopmentApplicationHost;
+ readonly onRuntimePruned?: () => Promise<void>;
}) {
this.#currentHost = input.initialHost;
+ this.#onRuntimePruned = input.onRuntimePruned;
this.#currentHostFingerprint = input.currentHostFingerprint;
this.#developmentExtensions = input.developmentExtensions;
this.#currentRuntimeFingerprint = input.currentRuntimeFingerprint;
@@ -153,6 +158,7 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentA
await activateDevelopmentGeneration({
appRoot: committedHost.appRoot,
generation: committedHost.generation,
+ onRuntimePruned: this.#onRuntimePruned,
});
this.#commitState(committedHost, nextHostFingerprint, nextRuntimeFingerprint);
nextHost = undefined;
@@ -223,6 +229,7 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentA
await activateDevelopmentGeneration({
appRoot: committedHost.appRoot,
generation: committedHost.generation,
+ onRuntimePruned: this.#onRuntimePruned,
});
} catch (error) {
await discardDevelopmentGeneration(committedHost.generation).catch(() => undefined);
diff --git a/packages/eve/src/internal/nitro/host/start-development-server.test.ts b/packages/eve/src/internal/nitro/host/start-development-server.test.ts
index e283db5ab..b924a54c4 100644
--- a/packages/eve/src/internal/nitro/host/start-development-server.test.ts
+++ b/packages/eve/src/internal/nitro/host/start-development-server.test.ts
@@ -21,6 +21,7 @@ const mocks = vi.hoisted(() => {
suspend: vi.fn(async () => undefined),
};
const mocksWorldInstance = {
+ reconcileExpiredRuns: vi.fn(async () => undefined),
close: vi.fn(async () => undefined),
handleRequest: vi.fn(async () => undefined),
start: vi.fn(async () => undefined),
diff --git a/packages/eve/src/internal/nitro/host/start-development-server.ts b/packages/eve/src/internal/nitro/host/start-development-server.ts
index 24a0e4235..d34abc5bd 100644
--- a/packages/eve/src/internal/nitro/host/start-development-server.ts
+++ b/packages/eve/src/internal/nitro/host/start-development-server.ts
@@ -437,6 +437,11 @@ async function startNitroDevelopmentServer(
preparedHost,
transportSecret: workflowTransportSecret,
});
+ const localWorkflowWorld = workflowWorld;
+ const onRuntimePruned =
+ localWorkflowWorld === undefined
+ ? undefined
+ : () => localWorkflowWorld.reconcileExpiredRuns();
// Parent-owned control routes must answer before the World starts: queue
// redelivery begins at start(), and a delivery's World calls would
// otherwise fall through to the worker and 404.
@@ -492,6 +497,7 @@ async function startNitroDevelopmentServer(
await activateDevelopmentGeneration({
appRoot: preparedHost.appRoot,
generation: preparedHost.generation,
+ onRuntimePruned,
});
initialGenerationPublished = true;
},
@@ -503,6 +509,7 @@ async function startNitroDevelopmentServer(
developmentExtensions,
devServer: activeDevServer,
initialHost: preparedHost,
+ onRuntimePruned,
});
authoredSourceWatcher = await devBootPhase(
diff --git a/packages/eve/src/internal/workflow/cancel-expired-development-run.test.ts b/packages/eve/src/internal/workflow/cancel-expired-development-run.test.ts
new file mode 100644
index 000000000..e945fdf74
--- /dev/null
+++ b/packages/eve/src/internal/workflow/cancel-expired-development-run.test.ts
@@ -0,0 +1,87 @@
+import {
+ EntityConflictError,
+ RunExpiredError,
+ WorkflowRunNotFoundError,
+} from "#compiled/@workflow/errors/index.js";
+import type { World } from "#compiled/@workflow/world/index.js";
+import { describe, expect, it, vi } from "vitest";
+
+import { cancelExpiredDevelopmentRun } from "#internal/workflow/cancel-expired-development-run.js";
+import { createDevelopmentWorkflowWorld } from "#internal/workflow/development-world-client.js";
+
+const { cancelRun } = vi.hoisted(() => ({ cancelRun: vi.fn() }));
+vi.mock("#internal/workflow/runtime.js", () => ({ cancelRun }));
+
+function worldWithStatus(...statuses: string[]): World {
+ const get = vi.fn();
+ for (const status of statuses) get.mockResolvedValueOnce({ status });
+ const world = createDevelopmentWorkflowWorld();
+ world.runs.get = get;
+ return world;
+}
+
+describe("cancelExpiredDevelopmentRun", () => {
+ it.each(["pending", "running"])("cancels a %s run with a diagnostic reason", async (status) => {
+ cancelRun.mockReset().mockResolvedValue(undefined);
+ const world = worldWithStatus(status);
+ await cancelExpiredDevelopmentRun(world, "run");
+ expect(cancelRun).toHaveBeenCalledWith(world, "run", {
+ cancelReason: "Development runtime snapshot is no longer available",
+ });
+ });
+
+ it.each(["completed", "failed", "cancelled"])("preserves a %s run", async (status) => {
+ cancelRun.mockReset();
+ await cancelExpiredDevelopmentRun(worldWithStatus(status), "run");
+ expect(cancelRun).not.toHaveBeenCalled();
+ });
+
+ it("accepts a concurrent terminal transition", async () => {
+ cancelRun.mockReset().mockRejectedValue(new Error("terminal state conflict"));
+ await expect(
+ cancelExpiredDevelopmentRun(worldWithStatus("running", "completed"), "run"),
+ ).resolves.toBeUndefined();
+ });
+
+ it.each([
+ new WorkflowRunNotFoundError("run"),
+ new RunExpiredError("run expired"),
+ new EntityConflictError("run already completed"),
+ ])("accepts an inactive target at every cancellation boundary: %s", async (cause) => {
+ const error = new Error("world request failed", { cause });
+ for (const boundary of ["initial read", "cancel", "re-read"]) {
+ cancelRun.mockReset().mockResolvedValue(undefined);
+ const world = worldWithStatus("running");
+ if (boundary === "initial read") {
+ vi.mocked(world.runs.get).mockReset().mockRejectedValue(error);
+ } else if (boundary === "cancel") {
+ cancelRun.mockRejectedValue(error);
+ } else {
+ cancelRun.mockRejectedValue(new Error("cancellation failed"));
+ vi.mocked(world.runs.get).mockRejectedValueOnce(error);
+ }
+ await expect(cancelExpiredDevelopmentRun(world, "run")).resolves.toBeUndefined();
+ if (boundary === "initial read") expect(cancelRun).not.toHaveBeenCalled();
+ }
+ });
+
+ it.each(["initial read", "re-read"])(
+ "propagates storage failures from the %s",
+ async (boundary) => {
+ const error = new Error("storage unavailable");
+ const world = worldWithStatus("running");
+ cancelRun.mockReset().mockRejectedValue(new Error("cancellation failed"));
+ if (boundary === "initial read") vi.mocked(world.runs.get).mockReset();
+ vi.mocked(world.runs.get).mockRejectedValueOnce(error);
+ await expect(cancelExpiredDevelopmentRun(world, "run")).rejects.toBe(error);
+ },
+ );
+
+ it("does not hide a cancellation failure for a still-active run", async () => {
+ const error = new Error("storage unavailable");
+ cancelRun.mockReset().mockRejectedValue(error);
+ await expect(
+ cancelExpiredDevelopmentRun(worldWithStatus("running", "running"), "run"),
+ ).rejects.toBe(error);
+ });
+});
diff --git a/packages/eve/src/internal/workflow/cancel-expired-development-run.ts b/packages/eve/src/internal/workflow/cancel-expired-development-run.ts
new file mode 100644
index 000000000..21081d575
--- /dev/null
+++ b/packages/eve/src/internal/workflow/cancel-expired-development-run.ts
@@ -0,0 +1,22 @@
+import type { World } from "#compiled/@workflow/world/index.js";
+import { cancelRun } from "#internal/workflow/runtime.js";
+import { isInactiveDevelopmentRunError } from "#internal/workflow/is-inactive-development-run-error.js";
+
+export async function cancelExpiredDevelopmentRun(world: World, runId: string): Promise<void> {
+ try {
+ const run = await world.runs.get(runId, { resolveData: "none" });
+ if (run.status !== "pending" && run.status !== "running") return;
+ try {
+ await cancelRun(world, runId, {
+ cancelReason: "Development runtime snapshot is no longer available",
+ });
+ } catch (error) {
+ if (isInactiveDevelopmentRunError(error)) return;
+ // A delivery can finish between the scan and cancellation.
+ const current = await world.runs.get(runId, { resolveData: "none" });
+ if (current.status === "pending" || current.status === "running") throw error;
+ }
+ } catch (error) {
+ if (!isInactiveDevelopmentRunError(error)) throw error;
+ }
+}
diff --git a/packages/eve/src/internal/workflow/development-world-client.ts b/packages/eve/src/internal/workflow/development-world-client.ts
index a30ca9aff..57b21519a 100644
--- a/packages/eve/src/internal/workflow/development-world-client.ts
+++ b/packages/eve/src/internal/workflow/development-world-client.ts
@@ -19,7 +19,8 @@ import {
getDevelopmentWorkflowGeneration,
withDevelopmentWorkflowGeneration,
} from "#internal/workflow/development-generation-context.js";
-import { LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH } from "#internal/workflow/local-world-data-directory.js";
+import { cancelExpiredDevelopmentRun } from "#internal/workflow/cancel-expired-development-run.js";
+import { isMissingDevelopmentRunError } from "#internal/workflow/is-inactive-development-run-error.js";
import {
DEVELOPMENT_WORKER_APP_ROOT_ENV,
DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,
@@ -45,8 +46,7 @@ const WORKFLOW_LOCAL_BASE_URL_ENV = "WORKFLOW_LOCAL_BASE_URL";
export class MissingDevelopmentGenerationError extends Error {
constructor(generationId: string, cause?: unknown) {
super(
- `Workflow run references missing development generation "${generationId}". ` +
- `Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard the app's active local Workflow runs.`,
+ `Workflow run references missing development generation "${generationId}". Start a new local session.`,
cause === undefined ? undefined : { cause },
);
this.name = "MissingDevelopmentGenerationError";
@@ -190,6 +190,7 @@ function createQueueHandler(
try {
const appRoot = readRequiredEnvironment(DEVELOPMENT_WORKER_APP_ROOT_ENV);
const generationId = await resolveDeliveryGenerationId(message);
+ if (generationId === undefined) return Response.json({ ok: true });
const runtimeAppRoot = await readGenerationRuntimeAppRoot(appRoot, generationId);
const result = await withDevelopmentWorkflowGeneration(
{
@@ -214,10 +215,14 @@ function createQueueHandler(
);
} catch (error) {
if (error instanceof MissingDevelopmentGenerationError) {
- // Retrying cannot bring the generation back; acknowledge the
- // delivery so the queue stops redelivering, and leave the loud
- // error for the user to act on.
- console.error(`[eve:dev] ${error.message}`);
+ const runId = resolveDeliveryRunId(message);
+ if (runId !== undefined) {
+ try {
+ await cancelExpiredDevelopmentRun(createDevelopmentWorkflowWorld(), runId);
+ } catch (cleanupError) {
+ return Response.json(String(cleanupError), { status: 500 });
+ }
+ }
return Response.json({ ok: true });
}
return Response.json(String(error), { status: 500 });
@@ -234,7 +239,7 @@ function createQueueHandler(
* the parent's queue and authenticated with the transport secret; nothing
* an untrusted caller controls participates.
*/
-async function resolveDeliveryGenerationId(message: unknown): Promise<string> {
+async function resolveDeliveryGenerationId(message: unknown): Promise<string | undefined> {
// Capability probes may name a run before start() persists its record.
if (!isRecord(message) || message.__healthCheck === true) {
return await call<string>("resolveLatestDeploymentId");
@@ -245,20 +250,29 @@ async function resolveDeliveryGenerationId(message: unknown): Promise<string> {
? runInput.deploymentId
: await call<string>("resolveLatestDeploymentId");
}
- const runId =
- typeof message.runId === "string"
- ? message.runId
- : typeof message.workflowRunId === "string"
- ? message.workflowRunId
- : undefined;
+ const runId = resolveDeliveryRunId(message);
if (runId === undefined) {
return await call<string>("resolveLatestDeploymentId");
}
- const run = await call<{ readonly deploymentId: string }>("runs.get", [
- runId,
- { resolveData: "none" },
- ]);
- return run.deploymentId;
+ try {
+ const run = await call<{ readonly deploymentId: string }>("runs.get", [
+ runId,
+ { resolveData: "none" },
+ ]);
+ return run.deploymentId;
+ } catch (error) {
+ if (!isMissingDevelopmentRunError(error)) throw error;
+ return undefined;
+ }
+}
+
+function resolveDeliveryRunId(message: unknown): string | undefined {
+ if (!isRecord(message) || message.__healthCheck === true) return undefined;
+ return typeof message.runId === "string"
+ ? message.runId
+ : typeof message.workflowRunId === "string"
+ ? message.workflowRunId
+ : undefined;
}
async function readGenerationRuntimeAppRoot(
diff --git a/packages/eve/src/internal/workflow/development-world-server.integration.test.ts b/packages/eve/src/internal/workflow/development-world-server.integration.test.ts
index 32d61086c..b207e5111 100644
--- a/packages/eve/src/internal/workflow/development-world-server.integration.test.ts
+++ b/packages/eve/src/internal/workflow/development-world-server.integration.test.ts
@@ -3,23 +3,23 @@ import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { EntityConflictError, RunExpiredError } from "#compiled/@workflow/errors/index.js";
import { workflowEntryReference } from "#execution/workflow-runtime.js";
+import { pruneDevelopmentRuntimeArtifactsSnapshots } from "#internal/nitro/dev-runtime-artifacts.js";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
import { getDevelopmentWorkflowGeneration } from "#internal/workflow/development-generation-context.js";
import { deriveEveWorkflowQueuePrefix } from "#internal/workflow/queue-namespace.js";
import {
decodeDevelopmentWorldValue,
encodeDevelopmentWorldValue,
+ serializeDevelopmentWorldError,
} from "#internal/workflow/development-world-codec.js";
import { createDevelopmentWorkflowWorld } from "#internal/workflow/development-world-client.js";
import {
createParentDevelopmentWorkflowWorld,
type ParentDevelopmentWorkflowWorld,
} from "#internal/workflow/development-world-server.js";
-import {
- LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH,
- resolveLocalWorkflowWorldDataDirectory,
-} from "#internal/workflow/local-world-data-directory.js";
+import { resolveLocalWorkflowWorldDataDirectory } from "#internal/workflow/local-world-data-directory.js";
import {
DEVELOPMENT_WORKER_APP_ROOT_ENV,
DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,
@@ -172,12 +172,12 @@ describe("parent development Workflow World", () => {
}
});
- it("quarantines runs referencing missing generations without refusing to boot", async () => {
+ it("quietly cancels orphaned runs at startup and preserves their cancellation reason", async () => {
const appRoot = await createScratchDirectory("eve-parent-workflow-missing-generation-");
await seedGeneration(appRoot, "generation-a");
const first = createWorld({ activeGenerationId: () => "generation-a", appRoot });
await first.start();
- await callWorld(first, "events.create", [
+ const created = await callWorld(first, "events.create", [
null,
{
eventData: {
@@ -199,20 +199,149 @@ describe("parent development Workflow World", () => {
const restarted = createWorld({ activeGenerationId: () => "generation-b", appRoot });
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
try {
- // One poisoned run must not take the app's other active runs down:
- // boot proceeds, the poisoned run's deliveries are quarantined, and
- // the failure is reported explicitly.
await expect(restarted.start()).resolves.toBeUndefined();
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("generation-a"));
- expect(errorSpy).toHaveBeenCalledWith(
- expect.stringContaining(LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH),
- );
+ expect(errorSpy).not.toHaveBeenCalled();
+ const runId = readCreatedRunId(created);
+ await expect(callWorld(restarted, "runs.get", [runId])).resolves.toMatchObject({
+ status: "cancelled",
+ });
+ const events = await callWorld(restarted, "events.list", [{ runId }]);
+ expect(events).toMatchObject({
+ data: expect.arrayContaining([
+ expect.objectContaining({
+ eventType: "run_cancelled",
+ eventData: { cancelReason: "Development runtime snapshot is no longer available" },
+ }),
+ ]),
+ });
} finally {
errorSpy.mockRestore();
await restarted.close();
}
});
+ it("recovers retained runs across restarts without recovering cancelled orphans", async () => {
+ const appRoot = await createScratchDirectory("eve-parent-workflow-recovery-");
+ await seedGeneration(appRoot, "retained");
+ const first = createWorld({ activeGenerationId: () => "retained", appRoot });
+ await first.start();
+ const runIds: string[] = [];
+ try {
+ for (const deploymentId of ["retained", "missing"]) {
+ runIds.push(
+ readCreatedRunId(
+ await callWorld(first, "events.create", [
+ null,
+ {
+ eventType: "run_created",
+ specVersion: 6,
+ eventData: {
+ deploymentId,
+ executionContext: {},
+ input: new Uint8Array(),
+ workflowName: workflowEntryReference.workflowId,
+ },
+ },
+ ]),
+ ),
+ );
+ }
+ } finally {
+ await first.close();
+ }
+ const deliveries: string[] = [];
+ process.env.WORKFLOW_LOCAL_BASE_URL = "http://eve-dev.local";
+ globalThis.fetch = (async (_input: unknown, init?: RequestInit) => {
+ const message = JSON.parse(new TextDecoder().decode(init?.body as Uint8Array)) as {
+ runId: string;
+ };
+ deliveries.push(message.runId);
+ return Response.json({ ok: true });
+ }) as typeof fetch;
+ const restarted = createWorld({ activeGenerationId: () => "retained", appRoot });
+ try {
+ await restarted.start();
+ await expect.poll(() => deliveries).toEqual([runIds[0]]);
+ await expect(callWorld(restarted, "runs.get", [runIds[1]])).resolves.toMatchObject({
+ status: "cancelled",
+ });
+ } finally {
+ await restarted.close();
+ }
+ });
+
+ it("reconciles explicitly after pruning, preserves retained runs, and skips cleanup after close", async () => {
+ const appRoot = await createScratchDirectory("eve-parent-workflow-pruning-");
+ await seedGeneration(appRoot, "old");
+ await seedGeneration(appRoot, "retained");
+ const world = createWorld({ activeGenerationId: () => "retained", appRoot });
+ await world.start();
+ const createRun = async (deploymentId: string) =>
+ readCreatedRunId(
+ await callWorld(world, "events.create", [
+ null,
+ {
+ eventData: {
+ deploymentId,
+ executionContext: {},
+ input: new Uint8Array(),
+ workflowName: workflowEntryReference.workflowId,
+ },
+ eventType: "run_created",
+ specVersion: 6,
+ },
+ ]),
+ );
+ try {
+ const old = await createRun("old");
+ const running = await createRun("old");
+ await callWorld(world, "events.create", [
+ running,
+ { eventType: "run_started", specVersion: 6 },
+ ]);
+ const terminal = await createRun("old");
+ await callWorld(world, "events.create", [
+ terminal,
+ { eventType: "run_completed", specVersion: 6, eventData: { output: new Uint8Array() } },
+ ]);
+ const retained = await createRun("retained");
+ await writeFile(join(appRoot, ".eve", "dev-runtime", "snapshots", "old", "activated"), "");
+ await writeFile(
+ join(appRoot, ".eve", "dev-runtime", "snapshots", "old", "retired.json"),
+ JSON.stringify({ retiredAt: 0 }),
+ );
+ await pruneDevelopmentRuntimeArtifactsSnapshots({
+ appRoot,
+ gracePeriodMs: 60_000,
+ retainCount: 0,
+ });
+ await expect(callWorld(world, "runs.get", [old])).resolves.toMatchObject({
+ status: "pending",
+ });
+ await world.reconcileExpiredRuns();
+ for (const runId of [old, running]) {
+ await expect(callWorld(world, "runs.get", [runId])).resolves.toMatchObject({
+ status: "cancelled",
+ });
+ }
+ await expect(callWorld(world, "runs.get", [terminal])).resolves.toMatchObject({
+ status: "completed",
+ });
+ await expect(callWorld(world, "runs.get", [retained])).resolves.toMatchObject({
+ status: "pending",
+ });
+ await world.close();
+ await rm(join(appRoot, ".eve", "dev-runtime", "snapshots", "retained"), { recursive: true });
+ await pruneDevelopmentRuntimeArtifactsSnapshots({ appRoot });
+ await world.reconcileExpiredRuns();
+ await expect(callWorld(world, "runs.get", [retained])).resolves.toMatchObject({
+ status: "pending",
+ });
+ } finally {
+ await world.close();
+ }
+ });
+
it("routes a pre-start health check to the active generation before its run exists", async () => {
const appRoot = await createScratchDirectory("eve-parent-workflow-health-check-");
await seedGeneration(appRoot, "generation-b");
@@ -286,13 +415,76 @@ describe("parent development Workflow World", () => {
// never runs.
expect(response.status).toBe(200);
expect(handled).not.toHaveBeenCalled();
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("generation-a"));
+ expect(errorSpy).not.toHaveBeenCalled();
+ await expect(callWorld(world, "runs.get", [runId])).resolves.toMatchObject({
+ status: "cancelled",
+ });
} finally {
errorSpy.mockRestore();
await world.close();
}
});
+ it("acknowledges stale deliveries whose run no longer exists", async () => {
+ const appRoot = await createScratchDirectory("eve-parent-workflow-missing-run-");
+ await seedGeneration(appRoot, "generation-a");
+ const world = createWorld({ activeGenerationId: () => "generation-a", appRoot });
+ connectWorkerToWorld(world, appRoot);
+ try {
+ await world.start();
+ const handled = vi.fn(async () => undefined);
+ const handler = createDevelopmentWorkflowWorld().createQueueHandler(QUEUE_PREFIX, handled);
+ for (const payload of [
+ { runId: RUN_ID },
+ { workflowRunId: RUN_ID },
+ { runId: RUN_ID, runInput: { deploymentId: "missing" } },
+ ]) {
+ const response = await handler(
+ new Request("http://localhost/.well-known/workflow/v1/flow", {
+ body: JSON.stringify(payload),
+ headers: deliveryHeaders({}),
+ method: "POST",
+ }),
+ );
+ expect(response.status, await response.text()).toBe(200);
+ }
+ expect(handled).not.toHaveBeenCalled();
+ } finally {
+ await world.close();
+ }
+ });
+
+ it.each([
+ { error: new RunExpiredError("run expired"), status: 200 },
+ { error: new EntityConflictError("storage conflict"), status: 500 },
+ { error: new Error("storage unavailable"), status: 500 },
+ ])("returns $status when delivery run lookup fails with $error", async ({ error, status }) => {
+ const appRoot = await createScratchDirectory("eve-parent-workflow-run-lookup-");
+ const world = createWorld({ activeGenerationId: () => "generation-a", appRoot });
+ connectWorkerToWorld(world, appRoot);
+ globalThis.fetch = vi.fn(
+ async () =>
+ new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(error)), {
+ status: 500,
+ }),
+ );
+ try {
+ const handled = vi.fn(async () => undefined);
+ const handler = createDevelopmentWorkflowWorld().createQueueHandler(QUEUE_PREFIX, handled);
+ const response = await handler(
+ new Request("http://localhost/.well-known/workflow/v1/flow", {
+ body: JSON.stringify({ runId: RUN_ID }),
+ headers: deliveryHeaders({}),
+ method: "POST",
+ }),
+ );
+ expect(response.status).toBe(status);
+ expect(handled).not.toHaveBeenCalled();
+ } finally {
+ await world.close();
+ }
+ });
+
it("retries a delivery when generation metadata is temporarily unreadable", async () => {
const appRoot = await createScratchDirectory("eve-parent-workflow-retry-delivery-");
await seedGeneration(appRoot, "generation-a");
diff --git a/packages/eve/src/internal/workflow/development-world-server.ts b/packages/eve/src/internal/workflow/development-world-server.ts
index ff607af13..098618638 100644
--- a/packages/eve/src/internal/workflow/development-world-server.ts
+++ b/packages/eve/src/internal/workflow/development-world-server.ts
@@ -1,6 +1,7 @@
import { existsSync } from "node:fs";
import { basename, join } from "node:path";
+import { cancelExpiredDevelopmentRun } from "#internal/workflow/cancel-expired-development-run.js";
import type { ValidQueueName, World } from "#compiled/@workflow/world/index.js";
import { createWorld } from "#compiled/@workflow/world-local/index.js";
import { deriveEveWorkflowQueuePrefix } from "#internal/workflow/queue-namespace.js";
@@ -44,6 +45,7 @@ export interface ParentDevelopmentWorkflowWorld {
close(): Promise<void>;
handleRequest(request: Request): Promise<Response | undefined>;
start(): Promise<void>;
+ reconcileExpiredRuns(): Promise<void>;
}
export function createParentDevelopmentWorkflowWorld(input: {
@@ -63,6 +65,7 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
readonly #world: World;
#closed = false;
#started = false;
+ #reconciliation: Promise<void> = Promise.resolve();
constructor(input: {
readonly agentName: string;
@@ -88,30 +91,19 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
if (this.#started) {
return;
}
- const referencedGenerationIds = await this.#collectActiveTurnGenerationIds();
- const missingGenerationIds = new Set<string>();
- for (const generationId of referencedGenerationIds) {
- if (!this.#generationExists(generationId)) {
- missingGenerationIds.add(generationId);
- }
- }
- if (missingGenerationIds.size > 0) {
- // One poisoned run must not take the rest of the app's active runs
- // down with it: quarantine its deliveries and keep booting.
- console.error(
- `[eve:dev] ${String(missingGenerationIds.size)} active local Workflow run(s) reference development generations that no longer exist ` +
- `(${[...missingGenerationIds].join(", ")}). Their deliveries are quarantined; ` +
- `remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard the app's active local Workflow runs.`,
- );
- }
await this.#world.start?.();
this.#started = true;
- await reenqueueActiveDevelopmentRuns({
- enqueue: this.#queue.bind(this),
- prefix: deriveEveWorkflowQueuePrefix(this.#agentName),
- quarantinedGenerationIds: missingGenerationIds,
- world: this.#world,
- });
+ try {
+ await this.#reconcileExpiredRuns();
+ await reenqueueActiveDevelopmentRuns({
+ enqueue: this.#queue.bind(this),
+ prefix: deriveEveWorkflowQueuePrefix(this.#agentName),
+ world: this.#world,
+ });
+ } catch (error) {
+ this.#started = false;
+ throw error;
+ }
}
async close(): Promise<void> {
@@ -120,6 +112,8 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
}
this.#closed = true;
this.#started = false;
+ // Reconciliation failures belong to their caller, not a later shutdown.
+ await this.#reconciliation.catch(() => undefined);
await this.#world.close?.();
}
@@ -134,8 +128,27 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
return undefined;
}
- async #collectActiveTurnGenerationIds(): Promise<ReadonlySet<string>> {
- const generationIds = new Set<string>();
+ async reconcileExpiredRuns(): Promise<void> {
+ if (!this.#started || this.#closed) return;
+ await this.#reconcileExpiredRuns();
+ }
+
+ #reconcileExpiredRuns(): Promise<void> {
+ this.#reconciliation = this.#reconciliation
+ .catch(() => undefined)
+ .then(async () => {
+ if (this.#closed) return;
+ const runIds = await this.#collectExpiredRunIds();
+ for (const runId of runIds) {
+ await cancelExpiredDevelopmentRun(this.#world, runId);
+ }
+ });
+ return this.#reconciliation;
+ }
+
+ async #collectExpiredRunIds(): Promise<readonly string[]> {
+ // Finish pagination before cancellation changes the status-filtered result set.
+ const runIds: string[] = [];
for (const status of ["pending", "running"] as const) {
let cursor: string | undefined;
do {
@@ -153,11 +166,13 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
{ cause: error },
);
}
- for (const run of page.data) generationIds.add(run.deploymentId);
+ for (const run of page.data) {
+ if (!this.#generationExists(run.deploymentId)) runIds.push(run.runId);
+ }
cursor = page.hasMore ? (page.cursor ?? undefined) : undefined;
} while (cursor !== undefined);
}
- return generationIds;
+ return runIds;
}
async #handleCall(request: Request): Promise<Response> {
@@ -286,7 +301,6 @@ function isObject(value: unknown): value is Record<string, unknown> {
async function reenqueueActiveDevelopmentRuns(input: {
readonly enqueue: World["queue"];
readonly prefix: string;
- readonly quarantinedGenerationIds: ReadonlySet<string>;
readonly world: World;
}): Promise<void> {
for (const status of ["pending", "running"] as const) {
@@ -307,9 +321,6 @@ async function reenqueueActiveDevelopmentRuns(input: {
);
}
for (const run of page.data) {
- if (input.quarantinedGenerationIds.has(run.deploymentId)) {
- continue;
- }
await input.enqueue(`${input.prefix}${run.workflowName}` as ValidQueueName, {
runId: run.runId,
});
diff --git a/packages/eve/src/internal/workflow/is-inactive-development-run-error.ts b/packages/eve/src/internal/workflow/is-inactive-development-run-error.ts
new file mode 100644
index 000000000..70781db2c
--- /dev/null
+++ b/packages/eve/src/internal/workflow/is-inactive-development-run-error.ts
@@ -0,0 +1,19 @@
+import {
+ EntityConflictError,
+ RunExpiredError,
+ WorkflowRunNotFoundError,
+} from "#compiled/@workflow/errors/index.js";
+import { walkCauseChain } from "#shared/errors.js";
+
+export function isMissingDevelopmentRunError(error: unknown): boolean {
+ return [...walkCauseChain(error)].some(
+ (cause) => WorkflowRunNotFoundError.is(cause) || RunExpiredError.is(cause),
+ );
+}
+
+export function isInactiveDevelopmentRunError(error: unknown): boolean {
+ return (
+ isMissingDevelopmentRunError(error) ||
+ [...walkCauseChain(error)].some((cause) => EntityConflictError.is(cause))
+ );
+}