Skip to content

Commit 27b8200

Browse files
ericallamTrigger.dev RepoOps
authored andcommitted
fix(cli): resume restored runs as soon as they continue
Mono-RevId: 0a35f4a9e1f0729502acf168c6d7815df8fdc799
1 parent 8025aff commit 27b8200

11 files changed

Lines changed: 739 additions & 11 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"trigger.dev": patch
3+
"@trigger.dev/core": patch
4+
---
5+
6+
Resume a deployed task as soon as its run is restored after a wait. A run that was suspended during a wait (`wait.for`, `triggerAndWait`, a waitpoint token or session input) could take up to 5 seconds longer than needed to continue, and the waits it finished after that, or a cancellation, could reach the task with the same delay.

‎apps/supervisor/src/workloadServer/index.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1148,7 +1148,12 @@ export class WorkloadServer extends EventEmitter<WorkloadServerEvents> {
11481148
return;
11491149
}
11501150
}
1151-
reply.json(continuation as WorkloadContinueRunExecutionResponseBody);
1151+
const { executionData } = continuation;
1152+
reply.json({
1153+
...continuation,
1154+
// Same form as `snapshots/since` returns, so the runner can use it instead.
1155+
executionData: executionData && legacifyCheckpointType(executionData),
1156+
} satisfies WorkloadContinueRunExecutionResponseBody);
11521157

11531158
await this.cancelCheckpointsAfterReply(params.runFriendlyId);
11541159
}

‎internal-packages/run-engine/src/engine/index.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { tryCatch } from "@trigger.dev/core/utils";
1616
import {
1717
type CheckpointInput,
1818
type CompleteRunAttemptResult,
19+
type ContinueRunExecutionResult,
1920
type CreateCheckpointResult,
2021
type DequeuedMessage,
2122
type ExecutionResult,
@@ -3226,7 +3227,7 @@ export class RunEngine {
32263227
runnerId?: string;
32273228
environmentId?: string;
32283229
tx?: PrismaClientOrTransaction;
3229-
}): Promise<ExecutionResult> {
3230+
}): Promise<ContinueRunExecutionResult> {
32303231
return this.checkpointSystem.continueRunExecution({
32313232
runId,
32323233
snapshotId,

‎internal-packages/run-engine/src/engine/systems/checkpointSystem.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type {
22
CheckpointInput,
3+
ContinueRunExecutionResult,
34
CreateCheckpointResult,
4-
ExecutionResult,
55
} from "@trigger.dev/core/v3";
66
import { validateCheckpointLocation } from "@trigger.dev/core/v3";
77
import { encodeCheckpointMetadata } from "../checkpointMetadata.js";
@@ -12,6 +12,7 @@ import { isCheckpointable, isPendingExecuting } from "../statuses.js";
1212
import type { ExecutionSnapshotSystem } from "./executionSnapshotSystem.js";
1313
import {
1414
getLatestExecutionSnapshot,
15+
executionDataFromSnapshot,
1516
executionResultFromSnapshot,
1617
} from "./executionSnapshotSystem.js";
1718
import type { SystemResources } from "./systems.js";
@@ -366,7 +367,7 @@ export class CheckpointSystem {
366367
runnerId?: string;
367368
environmentId?: string;
368369
tx?: PrismaClientOrTransaction;
369-
}): Promise<ExecutionResult> {
370+
}): Promise<ContinueRunExecutionResult> {
370371
const prisma = tx ?? this.$.prisma;
371372

372373
return await this.$.runLock.lock("continueRunExecution", [runId], async () => {
@@ -400,7 +401,10 @@ export class CheckpointSystem {
400401
await this.executionSnapshotSystem.enqueueHeartbeatIfNeeded(snapshot);
401402
await sendNotificationToWorker({ runId, snapshot, eventBus: this.$.eventBus });
402403

403-
return executionResultFromSnapshot(snapshot);
404+
return {
405+
...executionResultFromSnapshot(snapshot),
406+
executionData: executionDataFromSnapshot(snapshot),
407+
} satisfies ContinueRunExecutionResult;
404408
}
405409

406410
throw new ServiceValidationError(
@@ -499,7 +503,14 @@ export class CheckpointSystem {
499503

500504
return {
501505
...executionResultFromSnapshot(newSnapshot),
502-
} satisfies ExecutionResult;
506+
// What `snapshots/since` would return for the new snapshot, read from the primary, so the
507+
// runner can resume without fetching it. It carries the waitpoints it was created with.
508+
executionData: executionDataFromSnapshot({
509+
...newSnapshot,
510+
checkpoint: null,
511+
completedWaitpoints: snapshot.completedWaitpoints,
512+
}),
513+
} satisfies ContinueRunExecutionResult;
503514
});
504515
}
505516
}

‎internal-packages/run-engine/src/engine/tests/continueRunExecutionRetry.test.ts‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,9 +134,56 @@ async function restoreFromCheckpoint(
134134
assertNonNullable(restored[0]);
135135
expect(restored[0].snapshot.executionStatus).toBe("PENDING_EXECUTING");
136136

137-
return { run, pendingSnapshotId: restored[0].snapshot.id };
137+
return { run, pendingSnapshotId: restored[0].snapshot.id, waitpointId: waitpoint.waitpoint.id };
138138
}
139139

140+
describe("RunEngine continueRunExecution", () => {
141+
// Catches: a continue response without the completed waitpoints, which leaves the restored
142+
// runner to fetch the snapshot it just created (from a read replica that may not have it yet).
143+
containerTest(
144+
"returns the snapshot it created as snapshots/since does, with the completed waitpoints",
145+
async ({ prisma, redisOptions }) => {
146+
const environment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
147+
const engine = createEngine(prisma, redisOptions);
148+
149+
try {
150+
const { run, pendingSnapshotId, waitpointId } = await restoreFromCheckpoint(
151+
engine,
152+
prisma,
153+
environment
154+
);
155+
156+
const continued = await engine.continueRunExecution({
157+
runId: run.id,
158+
snapshotId: pendingSnapshotId,
159+
runnerId: "runner_a",
160+
});
161+
162+
assertNonNullable(continued.executionData);
163+
expect(continued.executionData.snapshot.id).toBe(continued.snapshot.id);
164+
expect(continued.executionData.snapshot.executionStatus).toBe("EXECUTING");
165+
expect(continued.executionData.completedWaitpoints.map((w) => w.id)).toEqual([waitpointId]);
166+
167+
const since = await engine.getSnapshotsSince({
168+
runId: run.id,
169+
snapshotId: pendingSnapshotId,
170+
});
171+
expect(continued.executionData).toEqual(since?.at(-1));
172+
173+
// A retry of the same continue returns the same.
174+
const retry = await engine.continueRunExecution({
175+
runId: run.id,
176+
snapshotId: pendingSnapshotId,
177+
runnerId: "runner_a",
178+
});
179+
expect(retry.executionData).toEqual(continued.executionData);
180+
} finally {
181+
await engine.quit();
182+
}
183+
}
184+
);
185+
});
186+
140187
describe("RunEngine continueRunExecution retries", () => {
141188
containerTest(
142189
"a retry after the continue already succeeded gets the same result",

‎packages/cli-v3/src/entryPoints/managed/controller.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,12 @@ export class ManagedRunController {
479479
runId: this.runFriendlyId,
480480
message: "Socket connected to supervisor",
481481
});
482+
483+
// After a reconnect the supervisor has a new socket that isn't bound to the run, so it
484+
// would drop the run's notifications. Subscribing again is harmless on a first connect.
485+
if (this.runFriendlyId && this.snapshotFriendlyId) {
486+
this.subscribeToRunNotifications(this.runFriendlyId, this.snapshotFriendlyId);
487+
}
482488
});
483489

484490
socket.on("connect_error", (error) => {
@@ -564,6 +570,9 @@ export class ManagedRunController {
564570
// Create a new socket with the updated URL and headers
565571
this.socket = this.createSupervisorSocket();
566572

573+
// The execution listens for run notifications on its socket, so hand it the new one
574+
this.currentExecution?.updateSupervisorSocket(this.socket);
575+
567576
// Re-subscribe to notifications if we have an active execution
568577
if (this.runFriendlyId && this.snapshotFriendlyId) {
569578
this.subscribeToRunNotifications(this.runFriendlyId, this.snapshotFriendlyId);

‎packages/cli-v3/src/entryPoints/managed/execution.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ import { UsageJwtRefresher } from "./usageJwtRefresh.js";
3333

3434
const CREDENTIAL_RESUME_RETRY_DELAYS_MS = [0, 1_000, 3_000];
3535

36+
// Only for a platform whose continue response doesn't carry the new snapshot. Gaps before each
37+
// fetch of it: snapshots/since can be served from a read replica that hasn't got it yet. Replica
38+
// lag is usually well under 100ms, so the first fetch nearly always finds it; the second, 600ms
39+
// after continue, covers a slow replica. Then the poll or a notification takes over.
40+
const CONTINUED_SNAPSHOT_FETCH_DELAYS_MS = [100, 500];
41+
3642
class ExecutionAbortError extends Error {
3743
constructor(message: string) {
3844
super(message);
@@ -892,6 +898,8 @@ export class RunExecution {
892898
throw new Error("Cannot restore: missing run or snapshot manager");
893899
}
894900

901+
const continuedFromSnapshotId = this.snapshotManager.snapshotId;
902+
895903
// Short delay to give websocket time to reconnect
896904
await sleep(100);
897905

@@ -903,7 +911,7 @@ export class RunExecution {
903911
// No billing report here: the restored runner does not own the suspended snapshot yet.
904912
if (this.runToken?.isDue) await this.sendHeartbeat("restore", { reportUsageJwt: false });
905913

906-
const continuationResult = await this.httpClient.continueRunExecution(
914+
let continuationResult = await this.httpClient.continueRunExecution(
907915
this.runFriendlyId,
908916
this.snapshotManager.snapshotId
909917
);
@@ -923,13 +931,51 @@ export class RunExecution {
923931
if (!retryResult.success) {
924932
throw new Error(retryResult.error);
925933
}
934+
935+
continuationResult = retryResult;
926936
} else {
927937
throw new Error(continuationResult.error);
928938
}
929939
}
930940

931941
// Track restore count
932942
this.restoreCount++;
943+
944+
// Continuing created the EXECUTING snapshot that carries the completed waitpoints. Take it in
945+
// now instead of leaving it to the next poll, which can be seconds away, or to a notification
946+
// a restored runner may not be subscribed to yet. Not awaited: we are inside the snapshot
947+
// queue, which processes it once this change is done.
948+
const { executionData } = continuationResult.data;
949+
950+
if (executionData) {
951+
this.enqueueSnapshotChangesAndWait([executionData]).catch((error) => {
952+
this.sendDebugLog("restore: failed to process the continued snapshot", {
953+
error: error instanceof Error ? error.message : String(error),
954+
});
955+
});
956+
return;
957+
}
958+
959+
// An older platform doesn't return it, so fetch it.
960+
this.fetchContinuedSnapshot(continuedFromSnapshotId).catch(() => {});
961+
}
962+
963+
/**
964+
* Fetches snapshot changes until the snapshot manager moves past the snapshot the run was
965+
* continued from. snapshots/since can be served from a read replica that doesn't have the
966+
* snapshot continue created yet, and then returns an empty list. After the last try the poll or
967+
* a notification takes over, as for any other snapshot change.
968+
*/
969+
private async fetchContinuedSnapshot(continuedFromSnapshotId: string) {
970+
for (const delayMs of CONTINUED_SNAPSHOT_FETCH_DELAYS_MS) {
971+
await sleep(delayMs);
972+
973+
if (this.isShuttingDown || this.currentSnapshotFriendlyId !== continuedFromSnapshotId) {
974+
return;
975+
}
976+
977+
await this.fetchAndProcessSnapshotChanges("continue");
978+
}
933979
}
934980

935981
private async exitTaskRunProcessWithoutFailingRun({
@@ -945,6 +991,15 @@ export class RunExecution {
945991
this.shutdownExecution(`exitTaskRunProcessWithoutFailingRun: ${reason}`);
946992
}
947993

994+
/**
995+
* Called by the RunController when it replaces its socket after a restore under a different
996+
* supervisor, so run notifications are received on the new socket.
997+
*/
998+
public updateSupervisorSocket(supervisorSocket: SupervisorSocket) {
999+
this.supervisorSocket = supervisorSocket;
1000+
this.notifier?.updateSocket(supervisorSocket);
1001+
}
1002+
9481003
/**
9491004
* Processes env overrides from the metadata service. Generally called when we're resuming from a suspended state.
9501005
*/

0 commit comments

Comments
 (0)