Skip to content

Commit 6270380

Browse files
d-csTrigger.dev RepoOps
authored andcommitted
fix(run-store): record a redis-primary birth on the run row
Mono-RevId: 220a778c7872d7327d8607413b9bae966971f866
1 parent fce3810 commit 6270380

6 files changed

Lines changed: 263 additions & 13 deletions

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,9 @@ describe("RedisSnapshotStore read retry", () => {
166166
redisTest("a write is never retried on a command timeout", async ({ redisOptions }) => {
167167
await withStore(redisOptions, async (store, client) => {
168168
const timeout = commandTimeout();
169-
const spy = vi.spyOn(client, "finalizeSnapshotUnit").mockRejectedValueOnce(timeout);
169+
const spy = vi
170+
.spyOn(client, "finalizeSnapshotUnitStampingBirthFlag")
171+
.mockRejectedValueOnce(timeout);
170172
await expect(store.finalize("run_1", "tok_1")).rejects.toBe(timeout);
171173
expect(attempts(spy, client)).toBe(1);
172174
});

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

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,8 @@ export type PreparedEntry = {
280280
/** Fork guard: the head snapshot id this entry expects, or "" for none. */
281281
expectedCur?: string;
282282
cycle?: AppendCyclePayload;
283+
/** Birth only: the TaskRun row records this redis-primary birth (see hasRedisPrimaryBirth). */
284+
redisPrimaryBirthRecorded?: boolean;
283285
};
284286

285287
/**
@@ -336,6 +338,8 @@ type StagedApply = {
336338
orderCount: string;
337339
distinctJson: string;
338340
birthMode: string;
341+
/** "1" stamps the seq `bf` field: the run's TaskRun row records its redis-primary birth. */
342+
birthFlag: string;
339343
};
340344

341345
export type SnapshotStoreMetrics = {
@@ -917,6 +921,7 @@ export class RedisSnapshotStore {
917921
orderCount,
918922
distinctJson,
919923
birthMode: pe.kind === "birth" ? residency : "",
924+
birthFlag: pe.kind === "birth" && pe.redisPrimaryBirthRecorded ? "1" : "",
920925
};
921926
}
922927

@@ -998,7 +1003,7 @@ export class RedisSnapshotStore {
9981003
async finalize(runId: string, transitionToken: string): Promise<FinalizeResult> {
9991004
return this.#timed("finalize", async () => {
10001005
const k = snapshotKeys(runId);
1001-
const reply = (await this.redis.finalizeSnapshotUnit(
1006+
const reply = (await this.redis.finalizeSnapshotUnitStampingBirthFlag(
10021007
k.e,
10031008
k.idx,
10041009
k.cur,
@@ -1378,7 +1383,7 @@ export class RedisSnapshotStore {
13781383
// Writes one entry with no guards; callers validate first. Include it after the eKey, idxKey,
13791384
// curKey, seqKey, resKey and wpKey locals. Returns { seq, cycleSeq, ttl, mismatch }.
13801385
const APPLY_FUNCTION = `
1381-
local function applyEntry(kind, id, raw, isValid, isTerminal, ttlMs, cycleMode, cycleSeqIn, orderJson, records, orderCount, distinctJson, birthMode)
1386+
local function applyEntry(kind, id, raw, isValid, isTerminal, ttlMs, cycleMode, cycleSeqIn, orderJson, records, orderCount, distinctJson, birthMode, birthFlag)
13821387
local seq = redis.call('HINCRBY', seqKey, 'e', 1)
13831388
13841389
-- Birth only: stamp the state version and residency.
@@ -1387,6 +1392,10 @@ export class RedisSnapshotStore {
13871392
if birthMode ~= '' then
13881393
redis.call('SET', resKey, birthMode)
13891394
end
1395+
-- bf: the run's TaskRun row records its redis-primary birth. Older scripts ignore it.
1396+
if birthFlag == '1' then
1397+
redis.call('HSET', seqKey, 'bf', '1')
1398+
end
13901399
end
13911400
13921401
local cycleSeq = 0
@@ -1556,7 +1565,7 @@ export class RedisSnapshotStore {
15561565
redis.call('HSET', seqKey, 'g', '1')
15571566
end
15581567
1559-
local r = applyEntry(kind, id, raw, isValid, isTerminal, ttlMs, cycleMode, cycleSeqIn, orderJson, records, orderCount, distinctJson, birthMode)
1568+
local r = applyEntry(kind, id, raw, isValid, isTerminal, ttlMs, cycleMode, cycleSeqIn, orderJson, records, orderCount, distinctJson, birthMode, '')
15601569
return { '${WRITTEN}', tostring(r[1]), tostring(r[2]), r[3], tostring(r[4]) }
15611570
`,
15621571
});
@@ -1606,7 +1615,7 @@ export class RedisSnapshotStore {
16061615
});
16071616

16081617
// See finalize().
1609-
this.redis.defineCommand("finalizeSnapshotUnit", {
1618+
this.redis.defineCommand("finalizeSnapshotUnitStampingBirthFlag", {
16101619
numberOfKeys: 7,
16111620
lua: `
16121621
${PRELUDE}
@@ -1638,7 +1647,7 @@ export class RedisSnapshotStore {
16381647
end
16391648
for i = 1, #staged do
16401649
local e = staged[i]
1641-
applyEntry(e.kind, e.id, e.raw, e.valid, e.isTerminal, ttlMs, e.cycleMode, e.cycleSeqIn, e.orderJson, e.records, e.orderCount, e.distinctJson, e.birthMode)
1650+
applyEntry(e.kind, e.id, e.raw, e.valid, e.isTerminal, ttlMs, e.cycleMode, e.cycleSeqIn, e.orderJson, e.records, e.orderCount, e.distinctJson, e.birthMode, e.birthFlag)
16421651
end
16431652
16441653
local head = redis.call('GET', curKey) or ''
@@ -2062,7 +2071,7 @@ declare module "@internal/redis" {
20622071
runId: string,
20632072
callback?: Callback<string[]>
20642073
): Result<string[], Context>;
2065-
finalizeSnapshotUnit(
2074+
finalizeSnapshotUnitStampingBirthFlag(
20662075
eKey: string,
20672076
idxKey: string,
20682077
curKey: string,

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
// carries only the version, residency, and organizationId (the run id is always available on the message
66
// itself, so it is never duplicated on the wire).
77

8+
import type { Prisma } from "@trigger.dev/database";
9+
810
/** A run's fixed storage residency. */
911
export type SnapshotResidency = "postgres" | "mirrored" | "redis-primary";
1012

@@ -45,6 +47,29 @@ export function metadataWithSnapshotResidency(
4547
return { ...metadata, snapshotStore: { version: 1, residency } };
4648
}
4749

50+
/**
51+
* Set on a run's TaskRun annotations, in the INSERT that creates the run, when it is born
52+
* redis-primary. Once the run's MemoryDB state and residency marker age out, this is the durable
53+
* proof the run was redis-primary. Code that predates it ignores the key.
54+
*/
55+
export function annotationsWithRedisPrimaryBirth(annotations: unknown): Prisma.InputJsonObject {
56+
const base =
57+
typeof annotations === "object" && annotations !== null && !Array.isArray(annotations)
58+
? (annotations as Prisma.InputJsonObject)
59+
: {};
60+
return { ...base, redisPrimaryBirth: true };
61+
}
62+
63+
/** True when the run's annotations record a redis-primary birth. */
64+
export function hasRedisPrimaryBirth(annotations: unknown): boolean {
65+
return (
66+
typeof annotations === "object" &&
67+
annotations !== null &&
68+
!Array.isArray(annotations) &&
69+
(annotations as Record<string, unknown>).redisPrimaryBirth === true
70+
);
71+
}
72+
4873
/** Operation-local server context derived from a stored snapshot. Never sent to a runner. */
4974
export function snapshotRouteFromSnapshot(snapshot: {
5075
organizationId: string;
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
// A redis-primary birth records itself in two places, written by the same pod in one unit: the
2+
// TaskRun row's annotations (in the INSERT that creates the run) and the run's MemoryDB `seq` hash
3+
// (`bf`). A mirrored birth records neither. Real Postgres + real Redis, no mocks.
4+
import { describe, expect } from "vitest";
5+
import { containerTest } from "@internal/testcontainers";
6+
import { createRedisClient } from "@internal/redis";
7+
import type { PrismaClient } from "@trigger.dev/database";
8+
import { generateInternalId } from "@trigger.dev/core/v3/isomorphic";
9+
import { PostgresRunStore } from "./PostgresRunStore.js";
10+
import { RedisSnapshotStore } from "./redisSnapshotStore.js";
11+
import { TaskRunExecutionSnapshotStore } from "./taskRunExecutionSnapshotStore.js";
12+
import { hasRedisPrimaryBirth } from "./snapshotResidency.js";
13+
import { snapshotKeys } from "./snapshotKeys.js";
14+
import {
15+
buildCreateRunData,
16+
seedSnapshotEnvironment,
17+
type SnapshotFixtureEnv,
18+
} from "./testFixtures/snapshotIdFixture.js";
19+
20+
const ROUTE = "logical:1";
21+
const TRIGGER_ANNOTATIONS = {
22+
triggerSource: "api",
23+
triggerAction: "trigger",
24+
rootTriggerSource: "api",
25+
};
26+
27+
function birthSnapshot(env: SnapshotFixtureEnv, id: string) {
28+
return {
29+
id,
30+
createdAt: new Date(),
31+
engine: "V2" as const,
32+
executionStatus: "RUN_CREATED" as const,
33+
description: "Run was created",
34+
runStatus: "PENDING" as const,
35+
environmentId: env.id,
36+
environmentType: env.type,
37+
projectId: env.projectId,
38+
organizationId: env.organizationId,
39+
};
40+
}
41+
42+
function writer(
43+
prisma: PrismaClient,
44+
store: RedisSnapshotStore,
45+
redisPrimaryBirthReady: boolean
46+
): TaskRunExecutionSnapshotStore {
47+
return new TaskRunExecutionSnapshotStore(
48+
new PostgresRunStore({ prisma, readOnlyPrisma: prisma }),
49+
{
50+
store,
51+
mode: "redis-only",
52+
resolveDial: () => "redis-only",
53+
logicalRunStoreRoute: ROUTE,
54+
redisPrimaryBirthReady: () => redisPrimaryBirthReady,
55+
}
56+
);
57+
}
58+
59+
async function annotationsOf(prisma: PrismaClient, runId: string): Promise<unknown> {
60+
return (await prisma.taskRun.findUniqueOrThrow({ where: { id: runId } })).annotations;
61+
}
62+
63+
describe("TaskRunExecutionSnapshotStore redis-primary birth flag", () => {
64+
containerTest(
65+
"a redis-primary createRun flags the TaskRun annotations and the seq hash",
66+
async ({ prisma, redisOptions }) => {
67+
const store = new RedisSnapshotStore({ redisOptions, completedTtlMs: 60_000 });
68+
const raw = createRedisClient(redisOptions);
69+
try {
70+
const env = await seedSnapshotEnvironment(prisma);
71+
const runId = generateInternalId();
72+
await writer(prisma, store, true).createRun({
73+
data: { ...buildCreateRunData(runId, env), annotations: TRIGGER_ANNOTATIONS },
74+
snapshot: birthSnapshot(env, generateInternalId()),
75+
});
76+
77+
expect(await store.readBirthResidency(runId)).toBe("redis-primary");
78+
// The trigger's own annotations survive next to the flag.
79+
expect(await annotationsOf(prisma, runId)).toEqual({
80+
...TRIGGER_ANNOTATIONS,
81+
redisPrimaryBirth: true,
82+
});
83+
expect(await raw.hget(snapshotKeys(runId).seq, "bf")).toBe("1");
84+
} finally {
85+
await raw.quit();
86+
await store.quit();
87+
}
88+
}
89+
);
90+
91+
containerTest(
92+
"a mirrored createRun flags neither the TaskRun nor the seq hash",
93+
async ({ prisma, redisOptions }) => {
94+
const store = new RedisSnapshotStore({ redisOptions, completedTtlMs: 60_000 });
95+
const raw = createRedisClient(redisOptions);
96+
try {
97+
const env = await seedSnapshotEnvironment(prisma);
98+
const runId = generateInternalId();
99+
// Not ready: the redis-only dial degrades the birth to mirrored.
100+
await writer(prisma, store, false).createRun({
101+
data: { ...buildCreateRunData(runId, env), annotations: TRIGGER_ANNOTATIONS },
102+
snapshot: birthSnapshot(env, generateInternalId()),
103+
});
104+
105+
expect(await store.readBirthResidency(runId)).toBe("mirrored");
106+
expect(await annotationsOf(prisma, runId)).toEqual(TRIGGER_ANNOTATIONS);
107+
expect(await raw.hget(snapshotKeys(runId).seq, "bf")).toBeNull();
108+
} finally {
109+
await raw.quit();
110+
await store.quit();
111+
}
112+
}
113+
);
114+
115+
containerTest(
116+
"a redis-primary createCancelledRun flags the TaskRun annotations and the seq hash",
117+
async ({ prisma, redisOptions }) => {
118+
const store = new RedisSnapshotStore({ redisOptions, completedTtlMs: 60_000 });
119+
const raw = createRedisClient(redisOptions);
120+
try {
121+
const env = await seedSnapshotEnvironment(prisma);
122+
const runId = generateInternalId();
123+
const cancelledAt = new Date();
124+
await writer(prisma, store, true).createCancelledRun({
125+
data: {
126+
...buildCreateRunData(runId, env),
127+
status: "CANCELED",
128+
error: { type: "STRING_ERROR", raw: "cancelled before materialisation" },
129+
completedAt: cancelledAt,
130+
updatedAt: cancelledAt,
131+
attemptNumber: 0,
132+
},
133+
snapshot: {
134+
...birthSnapshot(env, generateInternalId()),
135+
executionStatus: "FINISHED",
136+
description: "Run cancelled before materialisation",
137+
runStatus: "CANCELED",
138+
},
139+
});
140+
141+
expect(await store.readBirthResidency(runId)).toBe("redis-primary");
142+
expect(hasRedisPrimaryBirth(await annotationsOf(prisma, runId))).toBe(true);
143+
expect(await raw.hget(snapshotKeys(runId).seq, "bf")).toBe("1");
144+
} finally {
145+
await raw.quit();
146+
await store.quit();
147+
}
148+
}
149+
);
150+
});

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
// the plain, retriable SnapshotReadUnavailableError. Real Postgres + real Redis, no mocks.
66
import { describe, expect } from "vitest";
77
import { containerTest } from "@internal/testcontainers";
8+
import { createRedisClient } from "@internal/redis";
89
import { generateInternalId } from "@trigger.dev/core/v3/isomorphic";
910
import { PostgresRunStore } from "./PostgresRunStore.js";
1011
import { RedisSnapshotStore, type PreparedPgUnit } from "./redisSnapshotStore.js";
@@ -15,6 +16,7 @@ import {
1516
} from "./taskRunExecutionSnapshotStore.js";
1617
import type { SnapshotResidencyResolver } from "./snapshotResidencyResolver.js";
1718
import type { SnapshotRouteWire } from "./snapshotResidency.js";
19+
import { residencyKey } from "./snapshotKeys.js";
1820
import {
1921
buildCreateRunData,
2022
seedSnapshotEnvironment,
@@ -287,6 +289,35 @@ describe("TaskRunExecutionSnapshotStore expired redis-primary state", () => {
287289
}
288290
);
289291

292+
containerTest(
293+
"route-carried reads of a run with no state and no marker throw SnapshotStateExpiredError",
294+
async ({ prisma, redisOptions }) => {
295+
const delegate = new PostgresRunStore({ prisma, readOnlyPrisma: prisma });
296+
const store = new RedisSnapshotStore({ redisOptions, completedTtlMs: 60_000 });
297+
const raw = createRedisClient(redisOptions);
298+
try {
299+
const env = await seedSnapshotEnvironment(prisma);
300+
const writer = new TaskRunExecutionSnapshotStore(delegate, {
301+
store,
302+
mode: "redis-only",
303+
logicalRunStoreRoute: ROUTE,
304+
});
305+
const { runId, finishedId } = await finishedAndExpired(writer, store, env);
306+
await raw.del(residencyKey(runId));
307+
const reads = routeReads(writer, runId, finishedId, redisPrimaryRoute(env), prisma);
308+
309+
// The carried route proves the run is redis-primary, so a run with no state, marker or
310+
// pending unit has lost its state for good: never the retriable miss.
311+
expectExpired(await rejection(reads.latest()), runId);
312+
expectExpired(await rejection(reads.byId()), runId);
313+
expectExpired(await rejection(reads.window()), runId);
314+
} finally {
315+
await raw.quit();
316+
await store.quit();
317+
}
318+
}
319+
);
320+
290321
containerTest(
291322
"route-carried reads of a run whose state is present still succeed",
292323
async ({ prisma, redisOptions }) => {

0 commit comments

Comments
 (0)