Skip to content

Commit c0b053f

Browse files
committed
test(webapp,run-engine,run-store): caller-driven replica-lag + idempotency guards
Guards for the production fixes in the base PR. Each fixed site has a caller-driven test that drives the real exported route/presenter/service/engine caller against a real Postgres with the owning replica frozen (shared laggingReplica primitive), and goes RED when the fix is reverted; tolerated read-view sites carry a caller-driven GREEN proof of self-healing. The global-scope idempotency guard drives the real dedup + claim path through a real MollifierBuffer over a Redis testcontainer, incl. the cross-DB andWait and the expired/failed clear-and-recreate reacquire cases.
1 parent fb8fcfe commit c0b053f

55 files changed

Lines changed: 19364 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

apps/webapp/test/batchServices.replicaLag.test.ts

Lines changed: 679 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
// Under replica lag, BulkActionService.process (CANCEL and REPLAY) tolerates a member whose row has
2+
// not replicated: the per-batch member-hydration findRuns misses, the member is skipped this pass (no
3+
// throw, no mutation — not cancelled, not replayed), and the run stays live on the primary. The id set
4+
// comes from ClickHouse, fed downstream of Postgres and lagging more than the PG replica, so an id
5+
// cannot reach this batch before its PG row is on the replica — the skip window is unreachable.
6+
//
7+
// Drives the REAL exported BulkActionService.process against a real Postgres testcontainer. Tenant +
8+
// group are seeded on the primary; only orthogonal peripherals are mocked (ClickHouse-sourced id list,
9+
// commonWorker enqueue, db/engine/run-store singletons so the module imports don't construct at load).
10+
// The member-hydration store is a real PostgresRunStore whose read replica is frozen via the shared
11+
// laggingReplica primitive.
12+
13+
import { heteroPostgresTest, laggingReplica } from "@internal/testcontainers";
14+
import { PostgresRunStore } from "@internal/run-store";
15+
import { BulkActionStatus, BulkActionType, type PrismaClient } from "@trigger.dev/database";
16+
import { BulkActionId } from "@trigger.dev/core/v3/isomorphic";
17+
import { describe, expect, vi } from "vitest";
18+
19+
vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 });
20+
21+
// Prevent the db / engine / run-store singletons from constructing at import (the service is driven with
22+
// an explicitly-injected prisma + store).
23+
vi.mock("~/db.server", () => ({ prisma: {}, $replica: {} }));
24+
vi.mock("~/v3/runEngine.server", () => ({ engine: {} }));
25+
vi.mock("~/v3/runStore.server", () => ({ runStore: {} }));
26+
// commonWorker.enqueue is the "next batch" scheduling side effect — orthogonal to the hydration read.
27+
vi.mock("~/v3/commonWorker.server", () => ({ commonWorker: { enqueue: vi.fn(async () => {}) } }));
28+
// ClickHouse client factory — the id list is injected via the RunsRepository mock below.
29+
vi.mock("~/services/clickhouse/clickhouseFactoryInstance.server", () => ({
30+
clickhouseFactory: { getClickhouseForOrganization: vi.fn(async () => ({})) },
31+
}));
32+
// RunsRepository.listRunIds is the ClickHouse-sourced id page. Keep parseRunListInputOptions REAL; swap
33+
// only the repository so listRunIds returns our controlled member id set + a terminal (null) cursor.
34+
const listHolder = vi.hoisted(() => ({ runIds: [] as string[] }));
35+
vi.mock("~/services/runsRepository/runsRepository.server", async (importOriginal) => ({
36+
...((await importOriginal()) as Record<string, unknown>),
37+
RunsRepository: class {
38+
constructor(_opts: any) {}
39+
async listRunIds() {
40+
return { runIds: listHolder.runIds, pagination: { nextCursor: null, previousCursor: null } };
41+
}
42+
async countRuns() {
43+
return listHolder.runIds.length;
44+
}
45+
},
46+
}));
47+
48+
import { BulkActionService } from "~/v3/services/bulk/BulkActionV2.server";
49+
50+
let seq = 0;
51+
52+
async function seedTenant(prisma: PrismaClient, suffix: string) {
53+
const organization = await prisma.organization.create({
54+
data: { title: `Org ${suffix}`, slug: `org-${suffix}` },
55+
});
56+
const project = await prisma.project.create({
57+
data: {
58+
name: `Project ${suffix}`,
59+
slug: `project-${suffix}`,
60+
externalRef: `proj_${suffix}`,
61+
organizationId: organization.id,
62+
},
63+
});
64+
const environment = await prisma.runtimeEnvironment.create({
65+
data: {
66+
type: "DEVELOPMENT",
67+
slug: "dev",
68+
projectId: project.id,
69+
organizationId: organization.id,
70+
apiKey: `tr_dev_${suffix}`,
71+
pkApiKey: `pk_dev_${suffix}`,
72+
shortcode: `short_${suffix}`,
73+
},
74+
});
75+
return { organization, project, environment };
76+
}
77+
78+
async function seedRun(
79+
prisma: PrismaClient,
80+
seed: { organization: { id: string }; project: { id: string }; environment: { id: string } },
81+
suffix: string,
82+
status: "EXECUTING" | "COMPLETED_SUCCESSFULLY"
83+
) {
84+
const runId = `run_${suffix}`;
85+
await prisma.taskRun.create({
86+
data: {
87+
id: runId,
88+
engine: "V2",
89+
status,
90+
friendlyId: `run_fr_${suffix}`,
91+
taskIdentifier: "my-task",
92+
payload: "{}",
93+
payloadType: "application/json",
94+
traceId: `trace_${suffix}`,
95+
spanId: `span_${suffix}`,
96+
queue: "task/my-task",
97+
runtimeEnvironmentId: seed.environment.id,
98+
projectId: seed.project.id,
99+
organizationId: seed.organization.id,
100+
environmentType: "DEVELOPMENT",
101+
},
102+
});
103+
return runId;
104+
}
105+
106+
async function seedGroup(
107+
prisma: PrismaClient,
108+
seed: { project: { id: string }; environment: { id: string } },
109+
type: BulkActionType
110+
) {
111+
const { id, friendlyId } = BulkActionId.generate();
112+
await prisma.bulkActionGroup.create({
113+
data: {
114+
id,
115+
friendlyId,
116+
projectId: seed.project.id,
117+
environmentId: seed.environment.id,
118+
type,
119+
params: {},
120+
queryName: "bulk_action_v1",
121+
status: BulkActionStatus.PENDING,
122+
totalCount: 1,
123+
},
124+
});
125+
return id;
126+
}
127+
128+
describe("BulkActionV2.process tolerates members whose rows have not replicated", () => {
129+
// CANCEL.
130+
heteroPostgresTest(
131+
"CANCEL skips a member whose row has not replicated, leaving the run live on the primary",
132+
async ({ prisma14 }) => {
133+
const prisma = prisma14 as unknown as PrismaClient;
134+
const suffix = `bulk_cancel_${seq++}`;
135+
const seed = await seedTenant(prisma, suffix);
136+
const runId = await seedRun(prisma, seed, suffix, "EXECUTING");
137+
const groupId = await seedGroup(prisma, seed, BulkActionType.CANCEL);
138+
139+
listHolder.runIds = [runId];
140+
141+
// Member-hydration store: primary live, taskRun frozen-missing on the replica.
142+
const replica = laggingReplica(prisma, [{ model: "taskRun", mode: "missing" }]);
143+
const store = new PostgresRunStore({
144+
prisma,
145+
readOnlyPrisma: replica.client as never,
146+
schemaVariant: "legacy",
147+
});
148+
149+
const service = new BulkActionService(prisma as never, prisma as never, store);
150+
await service.process(groupId, { continueInline: true });
151+
152+
// The hydration read really hit the (lagging) replica.
153+
expect(replica.wasHit("taskRun")).toBe(true);
154+
155+
// OBSERVABLE OUTPUT: the member was SKIPPED — the run was NOT cancelled (still EXECUTING).
156+
const onPrimary = await prisma.taskRun.findFirstOrThrow({ where: { id: runId } });
157+
expect(onPrimary.status).toBe("EXECUTING");
158+
159+
// No progress was counted for the skipped member (success=0, failure=0).
160+
const group = await prisma.bulkActionGroup.findFirstOrThrow({ where: { id: groupId } });
161+
expect(group.successCount).toBe(0);
162+
expect(group.failureCount).toBe(0);
163+
}
164+
);
165+
166+
// REPLAY.
167+
heteroPostgresTest(
168+
"REPLAY skips a member whose row has not replicated, leaving the run live on the primary",
169+
async ({ prisma14 }) => {
170+
const prisma = prisma14 as unknown as PrismaClient;
171+
const suffix = `bulk_replay_${seq++}`;
172+
const seed = await seedTenant(prisma, suffix);
173+
const runId = await seedRun(prisma, seed, suffix, "COMPLETED_SUCCESSFULLY");
174+
const groupId = await seedGroup(prisma, seed, BulkActionType.REPLAY);
175+
176+
listHolder.runIds = [runId];
177+
178+
const replica = laggingReplica(prisma, [{ model: "taskRun", mode: "missing" }]);
179+
const store = new PostgresRunStore({
180+
prisma,
181+
readOnlyPrisma: replica.client as never,
182+
schemaVariant: "legacy",
183+
});
184+
185+
const service = new BulkActionService(prisma as never, prisma as never, store);
186+
await service.process(groupId, { continueInline: true });
187+
188+
expect(replica.wasHit("taskRun")).toBe(true);
189+
190+
// OBSERVABLE OUTPUT: the member was SKIPPED — no child replay run was created for this member.
191+
const childRuns = await prisma.taskRun.findMany({
192+
where: { rootTaskRunId: runId },
193+
});
194+
expect(childRuns).toHaveLength(0);
195+
196+
const group = await prisma.bulkActionGroup.findFirstOrThrow({ where: { id: groupId } });
197+
expect(group.successCount).toBe(0);
198+
expect(group.failureCount).toBe(0);
199+
200+
// The skip is pure lag: the member run is genuinely live on the primary.
201+
const onPrimary = await prisma.taskRun.findFirstOrThrow({ where: { id: runId } });
202+
expect(onPrimary.friendlyId).toBe(`run_fr_${suffix}`);
203+
}
204+
);
205+
});

0 commit comments

Comments
 (0)