Skip to content

Commit 07946c7

Browse files
d-csTrigger.dev RepoOps
authored andcommitted
fix(webapp,run-engine): answer 404 and log separately when the snapshots-since snapshot does not exist
Mono-RevId: 29077916597e0e85a49c237b36cef35ba7eb2e7e
1 parent a80bc3c commit 07946c7

11 files changed

Lines changed: 239 additions & 48 deletions
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { startTestServer, type TestServer } from "@internal/testcontainers/webapp";
2+
import { ApiClient } from "@trigger.dev/core/v3";
3+
import { SupervisorHttpClient } from "@trigger.dev/core/v3/runEngineWorker";
4+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
5+
import { MANAGED_WORKER_SECRET, seedEngineFixtures } from "../../test/bench/lib/engineFixtures";
6+
7+
const RUNNER_ID = "runner-snapshots-since-e2e";
8+
9+
let server: TestServer;
10+
11+
beforeAll(async () => {
12+
// The engine worker moves runs from the master queue to the worker queue.
13+
server = await startTestServer({ overrideEnv: { RUN_ENGINE_WORKER_ENABLED: "1" } });
14+
}, 180_000);
15+
16+
afterAll(async () => {
17+
await server?.stop();
18+
}, 120_000);
19+
20+
describe("snapshots since", () => {
21+
it("answers a since snapshot the run does not have with a 404", async () => {
22+
const fixtures = await seedEngineFixtures(server.prisma, { taskCount: 1 });
23+
const api = new ApiClient(server.webapp.baseUrl, fixtures.environmentApiKey);
24+
const supervisor = new SupervisorHttpClient({
25+
apiUrl: server.webapp.baseUrl,
26+
workerToken: fixtures.workerGroupToken,
27+
instanceName: "snapshots-since",
28+
managedWorkerSecret: MANAGED_WORKER_SECRET,
29+
});
30+
const { id: runId } = await api.triggerTask(fixtures.taskIdentifiers[0]!, { payload: {} });
31+
const dequeued = await vi.waitFor(
32+
async () => {
33+
const result = await supervisor.dequeue({});
34+
if (!result.success) throw new Error(result.error);
35+
if (!result.data[0]) throw new Error("Nothing dequeued yet");
36+
return result.data[0];
37+
},
38+
{ timeout: 10_000, interval: 100 }
39+
);
40+
41+
const known = await supervisor.getSnapshotsSince(
42+
runId,
43+
dequeued.snapshot.friendlyId,
44+
RUNNER_ID,
45+
fixtures.environmentId
46+
);
47+
expect(known.success).toBe(true);
48+
49+
// Catches: an unknown since snapshot answered with a 500, which reads as a server failure.
50+
const unknown = await supervisor.getSnapshotsSince(
51+
runId,
52+
"snapshot_doesnotexist00000",
53+
RUNNER_ID,
54+
fixtures.environmentId
55+
);
56+
expect(unknown).toMatchObject({
57+
success: false,
58+
statusCode: 404,
59+
error: "Snapshot not found",
60+
});
61+
}, 60_000);
62+
});

‎apps/webapp/app/routes/engine.v1.worker-actions.runs.$runFriendlyId.snapshots.since.$snapshotId.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { TypedResponse } from "@remix-run/server-runtime";
22
import { json } from "@remix-run/server-runtime";
3+
import { ExecutionSnapshotNotFoundError } from "@internal/run-engine";
34
import { SnapshotReadUnavailableError } from "@internal/run-store";
45
import type { WorkerApiRunSnapshotsSinceResponseBody } from "@trigger.dev/core/v3/workers";
56
import { z } from "zod";
@@ -29,6 +30,9 @@ export const loader = createLoaderWorkerApiRoute(
2930
});
3031
} catch (error) {
3132
// Returned, not thrown: the route builder logs every thrown value as an error.
33+
if (error instanceof ExecutionSnapshotNotFoundError) {
34+
return json({ error: "Snapshot not found" }, { status: 404 });
35+
}
3236
if (error instanceof SnapshotReadUnavailableError && error.retriable) {
3337
return json({ error: "Snapshot read temporarily unavailable" }, { status: 503 });
3438
}

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3389,6 +3389,7 @@ export class RunEngine {
33893389
return this.runAttemptSystem.resolveTaskRunContext(runId);
33903390
}
33913391

3392+
/** Throws `ExecutionSnapshotNotFoundError` when the since snapshot does not exist for this run. */
33923393
async getSnapshotsSince({
33933394
runId,
33943395
snapshotId,
@@ -3465,6 +3466,14 @@ export class RunEngine {
34653466
});
34663467
return result;
34673468
} catch (retryError) {
3469+
if (retryError instanceof ExecutionSnapshotNotFoundError) {
3470+
this.logger.error("getSnapshotsSince: since snapshot not found", {
3471+
runId,
3472+
snapshotId,
3473+
failedDuring: "primary_fallback",
3474+
});
3475+
throw retryError;
3476+
}
34683477
this.#rethrowIfSnapshotReadRetriable(retryError, runId, snapshotId);
34693478
this.logger.error("Failed to getSnapshotsSince", {
34703479
message: retryError instanceof Error ? retryError.message : retryError,
@@ -3476,6 +3485,12 @@ export class RunEngine {
34763485
}
34773486
}
34783487

3488+
// Logged apart from failed reads so it alerts on its own: runners only send snapshot IDs the
3489+
// engine gave them, so a miss means a forged or corrupted request. Alerting matches this exact message.
3490+
if (e instanceof ExecutionSnapshotNotFoundError) {
3491+
this.logger.error("getSnapshotsSince: since snapshot not found", { runId, snapshotId });
3492+
throw e;
3493+
}
34793494
this.#rethrowIfSnapshotReadRetriable(e, runId, snapshotId);
34803495
this.logger.error("Failed to getSnapshotsSince", {
34813496
message: e instanceof Error ? e.message : e,

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

Lines changed: 94 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import { containerTest } from "@internal/testcontainers";
22
import { trace } from "@internal/tracing";
3+
import { Logger } from "@trigger.dev/core/logger";
34
import {
45
PostgresRunStore,
56
RedisSnapshotStore,
7+
SnapshotReadUnavailableError,
68
TaskRunExecutionSnapshotStore,
79
type CompletedWaitpointResolver,
810
} from "@internal/run-store";
@@ -15,6 +17,7 @@ import {
1517
import { setTimeout } from "node:timers/promises";
1618
import { describe, expect } from "vitest";
1719
import type { PrismaClient, Waitpoint } from "@trigger.dev/database";
20+
import { ExecutionSnapshotNotFoundError } from "../errors.js";
1821
import { RunEngine } from "../index.js";
1922
import { getExecutionSnapshotsSince } from "../systems/executionSnapshotSystem.js";
2023
import { copySnapshotsToReplica, createTestMetricsMeter } from "./helpers/replicaTestHelpers.js";
@@ -390,9 +393,8 @@ describe("RunEngine getSnapshotsSince", () => {
390393
}
391394
);
392395

393-
containerTest("returns null for invalid snapshot ID", async ({ prisma, redisOptions }) => {
396+
containerTest("rejects an unknown snapshot ID", async ({ prisma, redisOptions }) => {
394397
const authenticatedEnvironment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
395-
396398
const engine = new RunEngine({
397399
prisma,
398400
worker: {
@@ -447,21 +449,24 @@ describe("RunEngine getSnapshotsSince", () => {
447449
prisma
448450
);
449451

450-
// Query with invalid snapshot ID
451-
const result = await engine.getSnapshotsSince({
452-
runId: run.id,
453-
snapshotId: "invalid-snapshot-id",
454-
});
455-
456-
// Should return null (caught by getSnapshotsSince error handler)
457-
expect(result).toBeNull();
452+
// Catches: an unknown since snapshot read as a failed read (null), which the route answers with 500.
453+
const logs = await captureLogs(() =>
454+
expect(
455+
engine.getSnapshotsSince({
456+
runId: run.id,
457+
snapshotId: "invalid-snapshot-id",
458+
})
459+
).rejects.toBeInstanceOf(ExecutionSnapshotNotFoundError)
460+
);
461+
// Catches: a not-found logged as a failed read, or losing its own error line.
462+
expectNotFoundLoggedSeparately(logs);
458463
} finally {
459464
await engine.quit();
460465
}
461466
});
462467

463468
containerTest(
464-
"returns null when the since snapshot belongs to a different run",
469+
"rejects with not-found when the since snapshot belongs to a different run",
465470
async ({ prisma, redisOptions }) => {
466471
const authenticatedEnvironment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
467472

@@ -559,12 +564,12 @@ describe("RunEngine getSnapshotsSince", () => {
559564
const runASnapshot = runASnapshots[0];
560565

561566
// Poll run B using a snapshot id that belongs to run A.
562-
const result = await engine.getSnapshotsSince({
563-
runId: runB.id,
564-
snapshotId: runASnapshot.id,
565-
});
566-
567-
expect(result).toBeNull();
567+
await expect(
568+
engine.getSnapshotsSince({
569+
runId: runB.id,
570+
snapshotId: runASnapshot.id,
571+
})
572+
).rejects.toBeInstanceOf(ExecutionSnapshotNotFoundError);
568573
} finally {
569574
await engine.quit();
570575
}
@@ -1060,10 +1065,9 @@ describe("RunEngine getSnapshotsSince", () => {
10601065
);
10611066

10621067
containerTest(
1063-
"returns null when the snapshot is missing on both replica and primary",
1068+
"rejects with not-found when the snapshot is missing on both replica and primary",
10641069
async ({ prisma, schemaOnlyPrisma, redisOptions }) => {
10651070
const { meter, getCounterValue } = createTestMetricsMeter();
1066-
10671071
const engine = new RunEngine({
10681072
prisma,
10691073
readOnlyPrisma: schemaOnlyPrisma,
@@ -1099,12 +1103,15 @@ describe("RunEngine getSnapshotsSince", () => {
10991103

11001104
try {
11011105
// runId is never consulted - the since-snapshot lookup throws on the bogus id first.
1102-
const result = await engine.getSnapshotsSince({
1103-
runId: "run_does_not_exist",
1104-
snapshotId: "snapshot_does_not_exist",
1105-
});
1106-
1107-
expect(result).toBeNull();
1106+
const logs = await captureLogs(() =>
1107+
expect(
1108+
engine.getSnapshotsSince({
1109+
runId: "run_does_not_exist",
1110+
snapshotId: "snapshot_does_not_exist",
1111+
})
1112+
).rejects.toBeInstanceOf(ExecutionSnapshotNotFoundError)
1113+
);
1114+
expectNotFoundLoggedSeparately(logs);
11081115

11091116
// Permanent misses are deliberately NOT counted - the counter only tracks
11101117
// reads actually served by the primary fallback.
@@ -1704,6 +1711,29 @@ describe("RunEngine getSnapshotsSince", () => {
17041711
);
17051712
});
17061713

1714+
// Records the structured lines the engine's Logger emits, the same JSON the log alarms match on.
1715+
async function captureLogs(fn: () => Promise<unknown>) {
1716+
const logs: Record<string, unknown>[] = [];
1717+
const original = Logger.onLog;
1718+
Logger.onLog = (log) => logs.push(log);
1719+
try {
1720+
await fn();
1721+
} finally {
1722+
Logger.onLog = original;
1723+
}
1724+
return logs;
1725+
}
1726+
1727+
function expectNotFoundLoggedSeparately(logs: Record<string, unknown>[]) {
1728+
expect(logs.filter((log) => log.message === "Failed to getSnapshotsSince")).toEqual([]);
1729+
expect(logs).toContainEqual(
1730+
expect.objectContaining({
1731+
message: "getSnapshotsSince: since snapshot not found",
1732+
level: "error",
1733+
})
1734+
);
1735+
}
1736+
17071737
// Counts the checkpoint lookups a since read makes through the run store, and records the client
17081738
// each one used.
17091739
class CheckpointLookupCountingStore extends PostgresRunStore {
@@ -2036,4 +2066,43 @@ describe("getExecutionSnapshotsSince checkpoint lookups for a MemoryDB-only run"
20362066
}
20372067
}
20382068
);
2069+
2070+
// Catches: an unknown since snapshot on a MemoryDB-only run read as a failed read (a 503 and the
2071+
// failed-read alarm), or a gapped history read as not-found.
2072+
containerTest(
2073+
"an unknown since snapshot is not-found while the run's history is whole, and fails closed once gapped",
2074+
async ({ prisma, redisOptions }) => {
2075+
const seeded = await seed(prisma, redisOptions);
2076+
try {
2077+
const reader = new TaskRunExecutionSnapshotStore(seeded.delegate, {
2078+
store: seeded.store,
2079+
mode: "redis-only",
2080+
logicalRunStoreRoute: "logical:1",
2081+
resolveCompletedWaitpoints: resolverReturning(() => false),
2082+
});
2083+
const since = (snapshotId: string) =>
2084+
getExecutionSnapshotsSince(
2085+
prisma,
2086+
seeded.runId,
2087+
snapshotId,
2088+
reader,
2089+
undefined,
2090+
seeded.env.id,
2091+
seeded.env.organizationId,
2092+
() => true
2093+
);
2094+
2095+
await expect(since("snapshot_doesnotexist")).rejects.toBeInstanceOf(
2096+
ExecutionSnapshotNotFoundError
2097+
);
2098+
2099+
await seeded.store.markGaps(seeded.runId);
2100+
await expect(since("snapshot_doesnotexist")).rejects.toBeInstanceOf(
2101+
SnapshotReadUnavailableError
2102+
);
2103+
} finally {
2104+
await seeded.store.quit();
2105+
}
2106+
}
2107+
);
20392108
});

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

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { assertNonNullable, containerTest } from "@internal/testcontainers";
22
import { trace } from "@internal/tracing";
33
import { expect } from "vitest";
4+
import { ExecutionSnapshotNotFoundError } from "../errors.js";
45
import { RunEngine } from "../index.js";
56
import { setTimeout } from "node:timers/promises";
67
import type { EventBusEventArgs } from "../eventBus.js";
@@ -1279,19 +1280,13 @@ describe("RunEngine Waitpoints", () => {
12791280
assertNonNullable(sinceLatest);
12801281
expect(sinceLatest.length).toBe(0);
12811282

1282-
// getSnapshotsSince with an invalid snapshotId should throw or return []
1283-
let threw = false;
1284-
try {
1285-
const sinceInvalid = await engine.getSnapshotsSince({
1283+
// An unknown since snapshot is a not-found, not a failed read.
1284+
await expect(
1285+
engine.getSnapshotsSince({
12861286
runId: run.id,
12871287
snapshotId: "invalid-id",
1288-
});
1289-
expect(sinceInvalid).toBeNull();
1290-
} catch (_e) {
1291-
threw = true;
1292-
}
1293-
// should never throw
1294-
expect(threw).toBe(false);
1288+
})
1289+
).rejects.toBeInstanceOf(ExecutionSnapshotNotFoundError);
12951290
} finally {
12961291
await engine.quit();
12971292
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export type {
1616
ShutdownOperation,
1717
} from "./engine/shutdown.js";
1818
export {
19+
ExecutionSnapshotNotFoundError,
1920
LatestExecutionSnapshotNotFoundError,
2021
RunDuplicateIdempotencyKeyError,
2122
RunOneTimeUseTokenError,

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,9 @@ describe("RedisSnapshotStore read retry", () => {
115115

116116
redisTest("getById returns the entry after one command timeout", async ({ redisOptions }) => {
117117
await withStore(redisOptions, async (store, client) => {
118-
const spy = vi.spyOn(client, "readSnapshotById").mockRejectedValueOnce(commandTimeout());
118+
const spy = vi
119+
.spyOn(client, "readSnapshotByIdOrAbsent")
120+
.mockRejectedValueOnce(commandTimeout());
119121
const read = await store.getById("run_1", "snap_1");
120122
expect(read?.entry).toMatchObject({ id: "snap_1" });
121123
expect(attempts(spy, client)).toBe(2);
@@ -125,7 +127,7 @@ describe("RedisSnapshotStore read retry", () => {
125127
redisTest("getById with retry off rejects on the first timeout", async ({ redisOptions }) => {
126128
await withStore(redisOptions, async (store, client) => {
127129
const timeout = commandTimeout();
128-
const spy = vi.spyOn(client, "readSnapshotById").mockRejectedValueOnce(timeout);
130+
const spy = vi.spyOn(client, "readSnapshotByIdOrAbsent").mockRejectedValueOnce(timeout);
129131
await expect(store.getById("run_1", "snap_1", { retry: false })).rejects.toBe(timeout);
130132
expect(attempts(spy, client)).toBe(1);
131133
});

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1129,6 +1129,30 @@ describe("environment scoping", () => {
11291129
}
11301130
});
11311131

1132+
// Catches: a whole keyspace's miss read as unanswerable (the since route then alerts as a failed
1133+
// read), or a keyspace that cannot answer read as authoritative.
1134+
redisTest(
1135+
"findById reports absent only when the keyspace is live and has no gaps",
1136+
async ({ redisOptions }) => {
1137+
const store = new RedisSnapshotStore({ redisOptions, completedTtlMs: 1000 });
1138+
try {
1139+
await store.append({ entry: entry({ id: "s1" }), kind: "birth", isTerminal: false });
1140+
1141+
expect(await store.findById("run_1", "s1")).toMatchObject({ id: "s1" });
1142+
expect(await store.findById("run_1", "nope")).toBe("absent");
1143+
expect(await store.findById("run_1", "s1", { environmentId: "env_other" })).toBe("absent");
1144+
expect(await store.getById("run_1", "nope")).toBeNull();
1145+
expect(await store.findById("run_absent", "nope")).toBeNull();
1146+
1147+
await store.markGaps("run_1");
1148+
expect(await store.findById("run_1", "nope")).toBeNull();
1149+
expect(await store.findById("run_1", "s1")).toBeNull();
1150+
} finally {
1151+
await store.quit();
1152+
}
1153+
}
1154+
);
1155+
11321156
redisTest("getLatest returns null for a run with no keys", async ({ redisOptions }) => {
11331157
const store = new RedisSnapshotStore({ redisOptions, completedTtlMs: 1000 });
11341158
try {

0 commit comments

Comments
 (0)