Skip to content

Commit b96c4b5

Browse files
1stvampTrigger.dev RepoOps
authored andcommitted
feat(run-engine): name the previous attempt's runner when dequeuing a retry
Mono-RevId: 84962fc88fa51bb3054d36ac072302c71d89234c
1 parent e77a8b2 commit b96c4b5

10 files changed

Lines changed: 511 additions & 18 deletions

File tree

‎apps/supervisor/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,7 @@ class ManagedSupervisor {
846846
snapshotId: message.snapshot.id,
847847
snapshotFriendlyId: message.snapshot.friendlyId,
848848
placementTags: message.placementTags,
849+
previousRunnerId: message.previousRunnerId,
849850
traceContext: message.run.traceContext,
850851
annotations: message.run.annotations,
851852
hasPrivateLink: message.organization.hasPrivateLink,

‎apps/supervisor/src/util.ts‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
1+
import {
2+
runnerIdForAttempt as getRunnerId,
3+
runnerIdForRestore as getRestoreRunnerId,
4+
} from "@trigger.dev/core/v3/isomorphic";
15
import { isMacOS, isWindows } from "std-env";
26

7+
export { getRestoreRunnerId, getRunnerId };
8+
39
export function normalizeDockerHostUrl(url: string) {
410
const $url = new URL(url);
511

@@ -26,16 +32,6 @@ export function extractTraceparent(traceContext?: Record<string, unknown>): stri
2632
return undefined;
2733
}
2834

29-
export function getRunnerId(runId: string, attemptNumber?: number) {
30-
const parts = ["runner", runId.replace("run_", "")];
31-
32-
if (attemptNumber && attemptNumber > 1) {
33-
parts.push(`attempt-${attemptNumber}`);
34-
}
35-
36-
return parts.join("-");
37-
}
38-
3935
/**
4036
* The attempt a cold start's runner was created for, read back from its id (`getRunnerId`).
4137
* Undefined for any other id, e.g. a restore runner's, which carries a checkpoint instead.
@@ -50,10 +46,3 @@ export function attemptOfRunnerId(runnerId: string, runFriendlyId: string): numb
5046
: null;
5147
return match ? Number(match[1]) : undefined;
5248
}
53-
54-
/** Derive a unique runnerId for a restore cycle using the checkpoint suffix */
55-
export function getRestoreRunnerId(runFriendlyId: string, checkpointId: string) {
56-
const runIdShort = runFriendlyId.replace("run_", "");
57-
const checkpointSuffix = checkpointId.slice(-8);
58-
return `runner-${runIdShort}-${checkpointSuffix}`;
59-
}

‎apps/supervisor/src/workloadManager/runCrd.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,27 @@ describe("runnerBodyFor", () => {
302302
);
303303
});
304304

305+
it("names the previous attempt's runner only when there was one", () => {
306+
expect(
307+
runnerBodyFor(createOptions({ previousRunnerId: "runner-previous" }), meta).spec
308+
.previousRunner
309+
).toBe("runner-previous");
310+
expect(runnerBodyFor(createOptions(), meta).spec).not.toHaveProperty("previousRunner");
311+
});
312+
313+
it("drops a previous runner that is not a runner name", () => {
314+
for (const previousRunnerId of [
315+
"runner_first",
316+
"Runner-abc",
317+
"runner-abc/../x",
318+
"x".repeat(300),
319+
]) {
320+
expect(runnerBodyFor(createOptions({ previousRunnerId }), meta).spec).not.toHaveProperty(
321+
"previousRunner"
322+
);
323+
}
324+
});
325+
305326
// It decides node-pool affinity and tolerations for every run this runner
306327
// later serves, not only the one that started it.
307328
it("carries the scheduled flag derived from the bootstrap run's source", () => {
@@ -525,6 +546,7 @@ describe("run-crd carries every shared create-option or excludes it on purpose",
525546
"nextAttemptNumber",
526547
"dequeuedAt",
527548
"placementTags",
549+
"previousRunnerId",
528550
"dequeueResponseMs",
529551
"pollingIntervalMs",
530552
"warmStartCheckMs",
@@ -582,6 +604,7 @@ describe("run-crd carries every shared create-option or excludes it on purpose",
582604
nextAttemptNumber: { nextAttemptNumber: 5 },
583605
dequeuedAt: { dequeuedAt: new Date("2026-01-01T00:00:00.000Z") },
584606
placementTags: { placementTags: [{ key: "pool", values: ["spot"] }] },
607+
previousRunnerId: { previousRunnerId: "runner-previous" },
585608
dequeueResponseMs: { dequeueResponseMs: 999 },
586609
pollingIntervalMs: { pollingIntervalMs: 999 },
587610
warmStartCheckMs: { warmStartCheckMs: 999 },

‎apps/supervisor/src/workloadManager/runCrd.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
type KubernetesObject,
88
type ObjectCache,
99
} from "@kubernetes/client-node";
10+
import { RUNNER_ID_PATTERN } from "@trigger.dev/core/v3/isomorphic";
1011
import { SimpleStructuredLogger } from "@trigger.dev/core/v3/utils/structuredLogger";
1112
import type {
1213
CheckpointType,
@@ -1610,6 +1611,9 @@ export function runnerBodyFor(
16101611
})),
16111612
}
16121613
: {}),
1614+
...(opts.previousRunnerId && RUNNER_ID_PATTERN.test(opts.previousRunnerId)
1615+
? { previousRunner: opts.previousRunnerId }
1616+
: {}),
16131617
// Carried, not derived: it decides affinity for every run this runner
16141618
// later serves.
16151619
...(isScheduledRun(opts) ? { isScheduledRun: true } : {}),

‎apps/supervisor/src/workloadManager/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ export interface WorkloadManagerCreateOptions {
3535
nextAttemptNumber?: number;
3636
dequeuedAt: Date;
3737
placementTags?: PlacementTag[];
38+
// The runner that executed the run's previous attempt.
39+
previousRunnerId?: string;
3840
// Timing context (populated by supervisor handler, included in wide event)
3941
dequeueResponseMs?: number;
4042
pollingIntervalMs?: number;

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

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,13 @@ import {
99
RetryOptions,
1010
RunAnnotations,
1111
} from "@trigger.dev/core/v3";
12-
import { getMaxDuration, SnapshotId } from "@trigger.dev/core/v3/isomorphic";
12+
import {
13+
getMaxDuration,
14+
RunId,
15+
runnerIdForAttempt,
16+
runnerIdForRestore,
17+
SnapshotId,
18+
} from "@trigger.dev/core/v3/isomorphic";
1319
import { placementTag } from "@trigger.dev/core/v3/serverOnly";
1420
import type {
1521
BackgroundWorker,
@@ -18,6 +24,7 @@ import type {
1824
RuntimeEnvironmentType,
1925
WorkerDeploymentStatus,
2026
} from "@trigger.dev/database";
27+
import { boundedIn } from "@trigger.dev/database";
2128
import { z } from "zod";
2229
import type { BillingCache } from "../billingCache.js";
2330
import type {
@@ -42,6 +49,7 @@ import type {
4249
} from "../types.js";
4350
import {
4451
getLatestExecutionSnapshotOrFinishedRun,
52+
type EnhancedExecutionSnapshot,
4553
type ExecutionSnapshotSystem,
4654
type PreviousSnapshot,
4755
} from "./executionSnapshotSystem.js";
@@ -855,6 +863,12 @@ export class DequeueSystem {
855863
? undefined
856864
: result.task.retryConfig;
857865

866+
const previousRunnerId = await this.#previousRunnerId(
867+
prisma,
868+
snapshot,
869+
result.run.attemptNumber
870+
);
871+
858872
// Pre-generate snapshot ID so we can construct the result without an extra read
859873
const { id: snapshotId, createdAt: snapshotCreatedAt } =
860874
this.executionSnapshotSystem.nextSnapshotIdentity(snapshot, runId);
@@ -1059,6 +1073,7 @@ export class DequeueSystem {
10591073
id: lockedTaskRun.projectId,
10601074
},
10611075
placementTags: [placementTag("paid", isPaying ? "true" : "false")],
1076+
...(previousRunnerId ? { previousRunnerId } : {}),
10621077
} satisfies DequeuedMessage;
10631078
},
10641079
{
@@ -1272,6 +1287,64 @@ export class DequeueSystem {
12721287
return "TEMPLATE_WAIT";
12731288
}
12741289

1290+
/**
1291+
* The runner that executed the run's previous attempt, for placing a retry. Only a new attempt
1292+
* after the first gets one: a resume or a continuation keeps its attempt. The name is derived
1293+
* from the dequeue that created that runner, never from a runner id the workload reported, which
1294+
* it can set to anything.
1295+
*/
1296+
async #previousRunnerId(
1297+
prisma: PrismaClientOrTransaction,
1298+
snapshot: EnhancedExecutionSnapshot,
1299+
attemptNumber: number | null
1300+
): Promise<string | undefined> {
1301+
if (!attemptNumber || snapshot.executionStatus !== "QUEUED" || snapshot.checkpointId) {
1302+
return undefined;
1303+
}
1304+
const route = snapshotRouteFromSnapshot(snapshot);
1305+
// shortcut: a Redis-only snapshot history has no indexed newest-first read, so those runs carry
1306+
// none; add one to the snapshot store if retries of those runs need placing.
1307+
if (route.residency === "redis-primary") return undefined;
1308+
const runId = snapshot.runId;
1309+
// shortcut: only the newest dequeues are considered; a run released this many times without
1310+
// starting carries none.
1311+
const dequeues = await this.$.runStore.findManyExecutionSnapshots(
1312+
{
1313+
where: { runId, isValid: true, executionStatus: "PENDING_EXECUTING" },
1314+
select: { id: true, attemptNumber: true, checkpointId: true },
1315+
orderBy: { createdAt: "desc" },
1316+
take: 20,
1317+
},
1318+
prisma,
1319+
route
1320+
);
1321+
if (dequeues.length === 0) return undefined;
1322+
// The runner of the newest dequeue that execution started from. A dequeue that was released or
1323+
// whose restore failed never ran, and a retry in place stays on the runner it started on.
1324+
const [started] = await this.$.runStore.findManyExecutionSnapshots(
1325+
{
1326+
where: {
1327+
runId,
1328+
isValid: true,
1329+
executionStatus: { in: ["EXECUTING", "EXECUTING_WITH_WAITPOINTS"] },
1330+
previousSnapshotId: { in: boundedIn(dequeues.map((dequeue) => dequeue.id)) },
1331+
},
1332+
select: { previousSnapshotId: true },
1333+
orderBy: { createdAt: "desc" },
1334+
take: 1,
1335+
},
1336+
prisma,
1337+
route
1338+
);
1339+
const dequeue = dequeues.find((candidate) => candidate.id === started?.previousSnapshotId);
1340+
if (!dequeue) return undefined;
1341+
const runFriendlyId = RunId.toFriendlyId(runId);
1342+
// The supervisor names a cold start's runner for the attempt the dequeue started.
1343+
return dequeue.checkpointId
1344+
? runnerIdForRestore(runFriendlyId, dequeue.checkpointId)
1345+
: runnerIdForAttempt(runFriendlyId, (dequeue.attemptNumber ?? 0) + 1);
1346+
}
1347+
12751348
async #acknowledgeExpiredFinishedRun(orgId: string, runId: string): Promise<void> {
12761349
this.$.logger.warn(
12771350
"dequeueFromWorkerQueue: snapshot state expired for a finished run, removing from queue",

0 commit comments

Comments
 (0)