Skip to content

Commit fce3810

Browse files
d-csTrigger.dev RepoOps
authored andcommitted
fix(run-store): keep a quarantined snapshot unit's staged entries
Mono-RevId: 8bbaff82d01c5829f67705c674588e44ff38b634
1 parent a823591 commit fce3810

4 files changed

Lines changed: 166 additions & 5 deletions

File tree

‎internal-packages/run-store/src/redisSnapshotStore.prepare.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -545,3 +545,52 @@ describe("key durability", () => {
545545
}
546546
);
547547
});
548+
549+
describe("cycle records in a prepared unit", () => {
550+
const record = (id: string): CompletedWaitpointRecord => ({
551+
id,
552+
friendlyId: `waitpoint_${id}`,
553+
type: "RUN",
554+
completedAt: "2026-01-01T00:00:00.000Z",
555+
outputType: "application/json",
556+
outputIsError: true,
557+
output: {
558+
inline: JSON.stringify({ message: `failed ${id} "quoted"`, stack: "at x\n".repeat(50) }),
559+
},
560+
});
561+
const records = [record("w_a"), record("w_b")];
562+
const refs = [{ id: "w_a", index: 0 }, { id: "w_b" }];
563+
const newCycle = (r = records) => ({
564+
kind: "new" as const,
565+
completedWaitpoints: refs,
566+
records: r,
567+
});
568+
569+
// Catches: a quarantine record that keeps only `unit`, which loses the records once `unit` stops
570+
// holding them.
571+
redisTest("quarantine keeps the staged records", async ({ redisOptions }) => {
572+
const store = new RedisSnapshotStore({ redisOptions, completedTtlMs: 60_000 });
573+
const raw = createRedisClient(redisOptions);
574+
try {
575+
const runId = "run_records_quarantine";
576+
await bornRun(store, runId);
577+
const u = unit(runId, [staged(runId, "s1", { expectedCur: "s0", cycle: newCycle() })], {
578+
residency: "redis-primary",
579+
});
580+
await store.prepare(u);
581+
const stagedJson = await raw.hget(preparedUnitKey(runId), "staged");
582+
const read = JSON.parse((await store.readPreparedUnitRaw(runId))!) as PreparedPgUnit;
583+
expect(read.entries[0]!.cycle?.records).toEqual(records);
584+
585+
expect((await store.quarantinePreparedUnit(read, "redis-primary-null")).moved).toBe(true);
586+
const quarantined = await store.readQuarantinedUnit(runId);
587+
expect(quarantined?.staged).toBe(stagedJson);
588+
expect(JSON.parse(quarantined!.staged!)[0].records).toBe(JSON.stringify(records));
589+
expect(quarantined?.unit).toEqual(read);
590+
expect(await store.hasPreparedUnit(runId)).toBe(false);
591+
} finally {
592+
await raw.quit();
593+
await store.quit();
594+
}
595+
});
596+
});

‎internal-packages/run-store/src/redisSnapshotStore.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ export type QuarantinedRecord = {
5454
quarantinedAt: string;
5555
/** The raw, unparseable value, preserved verbatim when the unit was structurally invalid. */
5656
raw?: string;
57+
/** The prepared unit's staged entries JSON, the copy of its cycle records that finalize applies. */
58+
staged?: string;
5759
};
5860

5961
/**
@@ -544,7 +546,7 @@ export class RedisSnapshotStore {
544546
raw?: string
545547
): Promise<{ moved: boolean }> {
546548
return this.#timed("quarantinePreparedUnit", async () => {
547-
const moved = (await this.redis.quarantinePreparedUnit(
549+
const moved = (await this.redis.quarantinePreparedUnitKeepingStaged(
548550
quarantineKey(unit.runId),
549551
preparedUnitKey(unit.runId),
550552
JSON.stringify(unit),
@@ -568,6 +570,7 @@ export class RedisSnapshotStore {
568570
reason: fields.reason ?? "",
569571
quarantinedAt: fields.quarantinedAt ?? "",
570572
...(fields.raw !== undefined ? { raw: fields.raw } : {}),
573+
...(fields.staged !== undefined ? { staged: fields.staged } : {}),
571574
};
572575
});
573576
}
@@ -1672,7 +1675,7 @@ export class RedisSnapshotStore {
16721675
});
16731676

16741677
// See quarantinePreparedUnit(). The stream entry is left for the recovery sweep to settle.
1675-
this.redis.defineCommand("quarantinePreparedUnit", {
1678+
this.redis.defineCommand("quarantinePreparedUnitKeepingStaged", {
16761679
numberOfKeys: 2,
16771680
lua: `
16781681
local quarantineKey = KEYS[1]
@@ -1691,6 +1694,11 @@ export class RedisSnapshotStore {
16911694
if ARGV[5] == '1' then
16921695
redis.call('HSET', quarantineKey, 'raw', ARGV[6])
16931696
end
1697+
-- Keep the staged entries too: they hold the cycle records finalize applies.
1698+
local staged = redis.call('HGET', prepKey, 'staged')
1699+
if staged then
1700+
redis.call('HSET', quarantineKey, 'staged', staged)
1701+
end
16941702
-- A corrupt unit with no token keeps its prep key for inspection.
16951703
if tok then
16961704
redis.call('DEL', prepKey)
@@ -2072,7 +2080,7 @@ declare module "@internal/redis" {
20722080
token: string,
20732081
callback?: Callback<string[]>
20742082
): Result<string[], Context>;
2075-
quarantinePreparedUnit(
2083+
quarantinePreparedUnitKeepingStaged(
20762084
quarantineKey: string,
20772085
prepKey: string,
20782086
unitJson: string,

‎internal-packages/run-store/src/taskRunExecutionSnapshotStore.lockWaitpointCycle.test.ts‎

Lines changed: 104 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,17 @@ import { containerTest } from "@internal/testcontainers";
66
import { createRedisClient } from "@internal/redis";
77
import { generateInternalId } from "@trigger.dev/core/v3/isomorphic";
88
import { PostgresRunStore } from "./PostgresRunStore.js";
9-
import { RedisSnapshotStore, type CompletedWaitpointRecord } from "./redisSnapshotStore.js";
9+
import {
10+
RedisSnapshotStore,
11+
type CompletedWaitpointRecord,
12+
type PreparedPgUnit,
13+
} from "./redisSnapshotStore.js";
1014
import {
1115
SnapshotWriteUnavailableError,
1216
TaskRunExecutionSnapshotStore,
1317
} from "./taskRunExecutionSnapshotStore.js";
1418
import { SnapshotResidencyResolver } from "./snapshotResidencyResolver.js";
15-
import { snapshotKeys } from "./snapshotKeys.js";
19+
import { preparedUnitKey, snapshotKeys } from "./snapshotKeys.js";
1620
import {
1721
buildCreateRunData,
1822
seedSnapshotEnvironment,
@@ -365,4 +369,102 @@ describe("redis-primary lockRunToWorker carries the completed-waitpoint cycle (F
365369
}
366370
}
367371
);
372+
373+
// Catches: a carry that passes hydrated waitpoints (as startRunAttempt does) putting every output
374+
// into the prepared unit's cycle refs, beside the records.
375+
containerTest(
376+
"a carry from hydrated waitpoints prepares only their ids and indexes, and keeps every record",
377+
async ({ prisma, redisOptions }) => {
378+
const store = new RedisSnapshotStore({ redisOptions, completedTtlMs: 60_000 });
379+
const raw = createRedisClient(redisOptions);
380+
const delegate = new PostgresRunStore({ prisma, readOnlyPrisma: prisma });
381+
let runId = "";
382+
const preparedUnits: string[] = [];
383+
const preparedStaged: string[] = [];
384+
const decorator = new TaskRunExecutionSnapshotStore(delegate, {
385+
store,
386+
mode: "redis-only",
387+
resolveDial: () => "redis-only",
388+
residencyResolver: new SnapshotResidencyResolver({ store }),
389+
logicalRunStoreRoute: ROUTE,
390+
hooks: {
391+
afterPrepare: async () => {
392+
preparedUnits.push((await store.readPreparedUnitRaw(runId)) ?? "");
393+
preparedStaged.push((await raw.hget(preparedUnitKey(runId), "staged")) ?? "");
394+
},
395+
},
396+
});
397+
try {
398+
const env = await seedSnapshotEnvironment(prisma);
399+
runId = generateInternalId();
400+
const birthId = generateInternalId();
401+
await decorator.createRun({
402+
data: buildCreateRunData(runId, env),
403+
snapshot: birthSnapshot(env, birthId),
404+
});
405+
const rec = (id: string): CompletedWaitpointRecord => ({
406+
id,
407+
friendlyId: `waitpoint_${id}`,
408+
type: "RUN",
409+
completedAt: "2026-01-01T00:00:00.000Z",
410+
outputType: "application/json",
411+
outputIsError: true,
412+
output: { inline: `record of ${id}` },
413+
});
414+
const base = {
415+
run: { id: runId, status: "EXECUTING" as const, attemptNumber: 1 },
416+
environmentId: env.id,
417+
environmentType: env.type,
418+
projectId: env.projectId,
419+
organizationId: env.organizationId,
420+
};
421+
const queuedId = generateInternalId();
422+
await decorator.createExecutionSnapshot({
423+
...base,
424+
id: queuedId,
425+
createdAt: new Date(),
426+
snapshot: { executionStatus: "QUEUED", description: "resumed" },
427+
previousSnapshotId: birthId,
428+
completedWaitpoints: [{ id: "A", index: 0 }, { id: "B" }],
429+
resolveCompletedWaitpointRecords: async () => [rec("A"), rec("B")],
430+
});
431+
const hydrated = ["A", "B"].map((id, i) => ({
432+
id,
433+
...(i === 0 ? { index: 0 } : {}),
434+
friendlyId: `waitpoint_${id}`,
435+
type: "RUN",
436+
output: `hydrated output of ${id}`,
437+
outputIsError: true,
438+
}));
439+
const executingId = generateInternalId();
440+
await decorator.createExecutionSnapshot({
441+
...base,
442+
id: executingId,
443+
createdAt: new Date(),
444+
snapshot: { executionStatus: "EXECUTING", description: "started" },
445+
previousSnapshotId: queuedId,
446+
completedWaitpoints: hydrated,
447+
});
448+
449+
const last = preparedUnits.length - 1;
450+
const carried = JSON.parse(preparedUnits[last]!) as PreparedPgUnit;
451+
expect(carried.entries[0]!.cycle).toEqual({
452+
kind: "carryForward",
453+
cycleSeq: 1,
454+
completedWaitpoints: [{ id: "A", index: 0 }, { id: "B" }],
455+
records: [rec("A"), rec("B")],
456+
});
457+
expect(JSON.parse(preparedStaged[last]!)[0].records).toBe(
458+
JSON.stringify([rec("A"), rec("B")])
459+
);
460+
for (const unitJson of preparedUnits) expect(unitJson).not.toContain("hydrated output");
461+
const read = await store.getSnapshotCompletedWaitpoints(runId, executingId);
462+
expect(read.order).toEqual(["A"]);
463+
expect(read.records).toEqual([rec("A"), rec("B")]);
464+
} finally {
465+
await raw.quit();
466+
await store.quit();
467+
}
468+
}
469+
);
368470
});

‎internal-packages/run-store/src/taskRunExecutionSnapshotStore.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2069,6 +2069,8 @@ export class TaskRunExecutionSnapshotStore extends DelegatingRunStore {
20692069
): Promise<AppendCyclePayload | undefined> {
20702070
if (residency !== "redis-primary") return undefined;
20712071
if (!completedWaitpoints || completedWaitpoints.length === 0) return undefined;
2072+
// Callers may pass hydrated waitpoints, outputs included; the cycle reads only id and index.
2073+
completedWaitpoints = completedWaitpoints.map(({ id, index }) => ({ id, index }));
20722074
// Fresh completions come with a records resolver from the unblock site: mint a new cycle.
20732075
const records = resolveRecords ? await resolveRecords() : undefined;
20742076
if (records && records.length > 0) {

0 commit comments

Comments
 (0)