-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathgetSnapshotsSince.test.ts
More file actions
680 lines (610 loc) · 21.4 KB
/
getSnapshotsSince.test.ts
File metadata and controls
680 lines (610 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
import { containerTest } from "@internal/testcontainers";
import { trace } from "@internal/tracing";
import { expect, describe } from "vitest";
import { RunEngine } from "../index.js";
import { setupAuthenticatedEnvironment, setupBackgroundWorker } from "./setup.js";
import { setTimeout } from "node:timers/promises";
import {
generateTestScenarios,
type SnapshotTestScenario,
} from "./helpers/executionStateMachine.js";
import {
createWaitpointsWithOutput,
setupTestScenario,
generateLargeOutput,
} from "./helpers/snapshotTestHelpers.js";
import { generateFriendlyId } from "@trigger.dev/core/v3/isomorphic";
vi.setConfig({ testTimeout: 120_000 });
describe("RunEngine getSnapshotsSince", () => {
containerTest(
"returns empty array when querying from latest snapshot",
async ({ prisma, redisOptions }) => {
const authenticatedEnvironment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
const engine = new RunEngine({
prisma,
worker: {
redis: redisOptions,
workers: 1,
tasksPerWorker: 10,
pollIntervalMs: 100,
},
queue: {
redis: redisOptions,
},
runLock: {
redis: redisOptions,
},
machines: {
defaultMachine: "small-1x",
machines: {
"small-1x": {
name: "small-1x" as const,
cpu: 0.5,
memory: 0.5,
centsPerMs: 0.0001,
},
},
baseCostInCents: 0.0001,
},
tracer: trace.getTracer("test", "0.0.0"),
});
try {
const taskIdentifier = "test-task";
await setupBackgroundWorker(engine, authenticatedEnvironment, taskIdentifier);
const runFriendlyId = generateFriendlyId("run");
const run = await engine.trigger(
{
number: 1,
friendlyId: runFriendlyId,
environment: authenticatedEnvironment,
taskIdentifier,
payload: "{}",
payloadType: "application/json",
context: {},
traceContext: {},
traceId: "t_empty",
spanId: "s_empty",
workerQueue: "main",
queue: "task/test-task",
isTest: false,
tags: [],
},
prisma
);
await setTimeout(500);
const dequeued = await engine.dequeueFromWorkerQueue({
consumerId: "test_empty",
workerQueue: "main",
});
// Get all snapshots
const allSnapshots = await prisma.taskRunExecutionSnapshot.findMany({
where: { runId: run.id, isValid: true },
orderBy: { createdAt: "asc" },
});
expect(allSnapshots.length).toBeGreaterThan(0);
// Query from the last snapshot
const lastSnapshot = allSnapshots[allSnapshots.length - 1];
const result = await engine.getSnapshotsSince({
runId: run.id,
snapshotId: lastSnapshot.id,
});
expect(result).not.toBeNull();
expect(result!.length).toBe(0);
} finally {
await engine.quit();
}
}
);
containerTest(
"returns snapshots after the specified one with waitpoints only on latest",
async ({ prisma, redisOptions }) => {
const authenticatedEnvironment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
const engine = new RunEngine({
prisma,
worker: {
redis: redisOptions,
workers: 1,
tasksPerWorker: 10,
pollIntervalMs: 100,
},
queue: {
redis: redisOptions,
},
runLock: {
redis: redisOptions,
},
machines: {
defaultMachine: "small-1x",
machines: {
"small-1x": {
name: "small-1x" as const,
cpu: 0.5,
memory: 0.5,
centsPerMs: 0.0001,
},
},
baseCostInCents: 0.0001,
},
tracer: trace.getTracer("test", "0.0.0"),
});
try {
const taskIdentifier = "test-task";
await setupBackgroundWorker(engine, authenticatedEnvironment, taskIdentifier);
const runFriendlyId = generateFriendlyId("run");
const run = await engine.trigger(
{
number: 1,
friendlyId: runFriendlyId,
environment: authenticatedEnvironment,
taskIdentifier,
payload: "{}",
payloadType: "application/json",
context: {},
traceContext: {},
traceId: "t_wp",
spanId: "s_wp",
workerQueue: "main",
queue: "task/test-task",
isTest: false,
tags: [],
},
prisma
);
await setTimeout(500);
const dequeued = await engine.dequeueFromWorkerQueue({
consumerId: "test_wp",
workerQueue: "main",
});
// Start attempt
await engine.startRunAttempt({
runId: dequeued[0].run.id,
snapshotId: dequeued[0].snapshot.id,
});
// Create and block with a waitpoint
const { waitpoint } = await engine.createDateTimeWaitpoint({
projectId: authenticatedEnvironment.project.id,
environmentId: authenticatedEnvironment.id,
completedAfter: new Date(Date.now() + 50),
});
await engine.blockRunWithWaitpoint({
runId: run.id,
waitpoints: [waitpoint.id],
projectId: authenticatedEnvironment.project.id,
organizationId: authenticatedEnvironment.organization.id,
});
// Poll until the waitpoint is completed by the background worker
for (let i = 0; i < 50; i++) {
await setTimeout(100);
const wp = await prisma.waitpoint.findFirst({
where: { id: waitpoint.id },
select: { status: true },
});
if (wp?.status === "COMPLETED") break;
}
// Allow time for the snapshot to be created after waitpoint completion
await setTimeout(200);
// Get all snapshots
const allSnapshots = await prisma.taskRunExecutionSnapshot.findMany({
where: { runId: run.id, isValid: true },
orderBy: { createdAt: "asc" },
});
expect(allSnapshots.length).toBeGreaterThanOrEqual(3);
// Query from the first snapshot
const result = await engine.getSnapshotsSince({
runId: run.id,
snapshotId: allSnapshots[0].id,
});
expect(result).not.toBeNull();
expect(result!.length).toBeGreaterThanOrEqual(2);
// The latest snapshot should have completedWaitpoints
const latest = result![result!.length - 1];
expect(latest.completedWaitpoints.length).toBeGreaterThan(0);
// Earlier snapshots should have empty waitpoints (optimization)
for (let i = 0; i < result!.length - 1; i++) {
expect(result![i].completedWaitpoints.length).toBe(0);
}
} finally {
await engine.quit();
}
}
);
containerTest(
"handles multiple waitpoints correctly - only latest has them",
async ({ prisma, redisOptions }) => {
const authenticatedEnvironment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
const engine = new RunEngine({
prisma,
worker: {
redis: redisOptions,
workers: 1,
tasksPerWorker: 10,
pollIntervalMs: 100,
},
queue: {
redis: redisOptions,
},
runLock: {
redis: redisOptions,
},
machines: {
defaultMachine: "small-1x",
machines: {
"small-1x": {
name: "small-1x" as const,
cpu: 0.5,
memory: 0.5,
centsPerMs: 0.0001,
},
},
baseCostInCents: 0.0001,
},
tracer: trace.getTracer("test", "0.0.0"),
});
try {
const taskIdentifier = "test-task";
await setupBackgroundWorker(engine, authenticatedEnvironment, taskIdentifier);
const runFriendlyId = generateFriendlyId("run");
const run = await engine.trigger(
{
number: 1,
friendlyId: runFriendlyId,
environment: authenticatedEnvironment,
taskIdentifier,
payload: "{}",
payloadType: "application/json",
context: {},
traceContext: {},
traceId: "t_mwp",
spanId: "s_mwp",
workerQueue: "main",
queue: "task/test-task",
isTest: false,
tags: [],
},
prisma
);
await setTimeout(500);
const dequeued = await engine.dequeueFromWorkerQueue({
consumerId: "test_mwp",
workerQueue: "main",
});
await engine.startRunAttempt({
runId: dequeued[0].run.id,
snapshotId: dequeued[0].snapshot.id,
});
// Create multiple waitpoints
const waitpointCount = 5;
const waitpointPromises = Array.from({ length: waitpointCount }).map(() =>
engine.createManualWaitpoint({
environmentId: authenticatedEnvironment.id,
projectId: authenticatedEnvironment.projectId,
})
);
const waitpoints = await Promise.all(waitpointPromises);
// Block the run with all waitpoints
for (const { waitpoint } of waitpoints) {
await engine.blockRunWithWaitpoint({
runId: run.id,
waitpoints: waitpoint.id,
projectId: authenticatedEnvironment.projectId,
organizationId: authenticatedEnvironment.organizationId,
});
}
// Complete all waitpoints
for (const { waitpoint } of waitpoints) {
await engine.completeWaitpoint({ id: waitpoint.id });
}
await setTimeout(500);
// Get all snapshots
const allSnapshots = await prisma.taskRunExecutionSnapshot.findMany({
where: { runId: run.id, isValid: true },
orderBy: { createdAt: "asc" },
});
// Query from early in the sequence
const result = await engine.getSnapshotsSince({
runId: run.id,
snapshotId: allSnapshots[0].id,
});
expect(result).not.toBeNull();
expect(result!.length).toBeGreaterThan(0);
// Only the latest should have waitpoints
const latest = result![result!.length - 1];
// Earlier snapshots must have empty completedWaitpoints
for (let i = 0; i < result!.length - 1; i++) {
expect(result![i].completedWaitpoints.length).toBe(0);
}
} finally {
await engine.quit();
}
}
);
containerTest("returns null for invalid snapshot ID", async ({ prisma, redisOptions }) => {
const authenticatedEnvironment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
const engine = new RunEngine({
prisma,
worker: {
redis: redisOptions,
workers: 1,
tasksPerWorker: 10,
pollIntervalMs: 100,
},
queue: {
redis: redisOptions,
},
runLock: {
redis: redisOptions,
},
machines: {
defaultMachine: "small-1x",
machines: {
"small-1x": {
name: "small-1x" as const,
cpu: 0.5,
memory: 0.5,
centsPerMs: 0.0001,
},
},
baseCostInCents: 0.0001,
},
tracer: trace.getTracer("test", "0.0.0"),
});
try {
const taskIdentifier = "test-task";
await setupBackgroundWorker(engine, authenticatedEnvironment, taskIdentifier);
const runFriendlyId = generateFriendlyId("run");
const run = await engine.trigger(
{
number: 1,
friendlyId: runFriendlyId,
environment: authenticatedEnvironment,
taskIdentifier,
payload: "{}",
payloadType: "application/json",
context: {},
traceContext: {},
traceId: "t_invalid",
spanId: "s_invalid",
workerQueue: "main",
queue: "task/test-task",
isTest: false,
tags: [],
},
prisma
);
// Query with invalid snapshot ID
const result = await engine.getSnapshotsSince({
runId: run.id,
snapshotId: "invalid-snapshot-id",
});
// Should return null (caught by getSnapshotsSince error handler)
expect(result).toBeNull();
} finally {
await engine.quit();
}
});
// Direct database tests for the core function
containerTest(
"direct test: large waitpoint scenario - 100 waitpoints with 10KB outputs",
async ({ prisma, redisOptions }) => {
const authenticatedEnvironment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
const engine = new RunEngine({
prisma,
worker: {
redis: redisOptions,
workers: 1,
tasksPerWorker: 10,
pollIntervalMs: 100,
},
queue: {
redis: redisOptions,
},
runLock: {
redis: redisOptions,
},
machines: {
defaultMachine: "small-1x",
machines: {
"small-1x": {
name: "small-1x" as const,
cpu: 0.5,
memory: 0.5,
centsPerMs: 0.0001,
},
},
baseCostInCents: 0.0001,
},
tracer: trace.getTracer("test", "0.0.0"),
});
try {
// Create scenario directly in database
const scenario = await setupTestScenario(prisma, authenticatedEnvironment, {
totalWaitpoints: 100,
outputSizeKB: 10,
snapshotConfigs: [
{ status: "RUN_CREATED", completedWaitpointCount: 0 },
{ status: "QUEUED", completedWaitpointCount: 0 },
{ status: "PENDING_EXECUTING", completedWaitpointCount: 0 },
{ status: "EXECUTING", completedWaitpointCount: 0 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 0 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 50 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 100 },
{ status: "EXECUTING", completedWaitpointCount: 100 },
{ status: "FINISHED", completedWaitpointCount: 100 },
],
});
// Query from early snapshot
const result = await engine.getSnapshotsSince({
runId: scenario.run.id,
snapshotId: scenario.snapshots[2].id, // After PENDING_EXECUTING
});
expect(result).not.toBeNull();
expect(result!.length).toBe(6); // EXECUTING through FINISHED
// Latest should have all 100 waitpoints
const latest = result![result!.length - 1];
expect(latest.completedWaitpoints.length).toBe(100);
// Verify all earlier snapshots have empty waitpoints
for (let i = 0; i < result!.length - 1; i++) {
expect(result![i].completedWaitpoints.length).toBe(0);
}
} finally {
await engine.quit();
}
}
);
containerTest(
"direct test: zombie run scenario - 236 waitpoints with 100KB outputs, 24 snapshots",
async ({ prisma, redisOptions }) => {
const authenticatedEnvironment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
const engine = new RunEngine({
prisma,
worker: {
redis: redisOptions,
workers: 1,
tasksPerWorker: 10,
pollIntervalMs: 100,
},
queue: {
redis: redisOptions,
},
runLock: {
redis: redisOptions,
},
machines: {
defaultMachine: "small-1x",
machines: {
"small-1x": {
name: "small-1x" as const,
cpu: 0.5,
memory: 0.5,
centsPerMs: 0.0001,
},
},
baseCostInCents: 0.0001,
},
tracer: trace.getTracer("test", "0.0.0"),
});
try {
// This scenario matches the exact conditions that caused the NAPI error
// 24 snapshots × 236 waitpoints × 100KB = ~570MB if not optimized
const scenario = await setupTestScenario(prisma, authenticatedEnvironment, {
totalWaitpoints: 236,
outputSizeKB: 100,
snapshotConfigs: [
{ status: "RUN_CREATED", completedWaitpointCount: 0 },
{ status: "QUEUED", completedWaitpointCount: 0 },
{ status: "PENDING_EXECUTING", completedWaitpointCount: 0 },
{ status: "EXECUTING", completedWaitpointCount: 0 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 0 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 100 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 200 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 236 },
{ status: "SUSPENDED", completedWaitpointCount: 236, hasCheckpoint: true },
{ status: "QUEUED", completedWaitpointCount: 236 },
{ status: "PENDING_EXECUTING", completedWaitpointCount: 236 },
{ status: "EXECUTING", completedWaitpointCount: 236 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 236 },
{ status: "SUSPENDED", completedWaitpointCount: 236, hasCheckpoint: true },
{ status: "QUEUED", completedWaitpointCount: 236 },
{ status: "PENDING_EXECUTING", completedWaitpointCount: 236 },
{ status: "EXECUTING", completedWaitpointCount: 236 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 236 },
{ status: "SUSPENDED", completedWaitpointCount: 236, hasCheckpoint: true },
{ status: "QUEUED", completedWaitpointCount: 236 },
{ status: "PENDING_EXECUTING", completedWaitpointCount: 236 },
{ status: "EXECUTING", completedWaitpointCount: 236 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 236 },
{ status: "EXECUTING", completedWaitpointCount: 236 },
],
});
expect(scenario.snapshots.length).toBe(24);
expect(scenario.waitpoints.length).toBe(236);
// Query from the 6th snapshot (after waitpoints start completing)
const queryFromIndex = 5;
const result = await engine.getSnapshotsSince({
runId: scenario.run.id,
snapshotId: scenario.snapshots[queryFromIndex].id,
});
expect(result).not.toBeNull();
// Should return snapshots after index 5, which is 24 - 6 = 18 snapshots
expect(result!.length).toBe(24 - queryFromIndex - 1);
// Latest should have all 236 waitpoints
const latest = result![result!.length - 1];
expect(latest.completedWaitpoints.length).toBe(236);
// All other snapshots should have 0 waitpoints (optimization)
for (let i = 0; i < result!.length - 1; i++) {
expect(result![i].completedWaitpoints.length).toBe(0);
}
// Verify the outputs are present and correct size
for (const wp of latest.completedWaitpoints) {
expect(wp.output).toBeDefined();
// ~100KB output as JSON string
expect(typeof wp.output).toBe("string");
}
} finally {
await engine.quit();
}
}
);
containerTest(
"direct test: verifies chunked fetching works with 500+ waitpoints",
async ({ prisma, redisOptions }) => {
const authenticatedEnvironment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
const engine = new RunEngine({
prisma,
worker: {
redis: redisOptions,
workers: 1,
tasksPerWorker: 10,
pollIntervalMs: 100,
},
queue: {
redis: redisOptions,
},
runLock: {
redis: redisOptions,
},
machines: {
defaultMachine: "small-1x",
machines: {
"small-1x": {
name: "small-1x" as const,
cpu: 0.5,
memory: 0.5,
centsPerMs: 0.0001,
},
},
baseCostInCents: 0.0001,
},
tracer: trace.getTracer("test", "0.0.0"),
});
try {
// 500 waitpoints requires 5 chunks (100 per chunk)
const scenario = await setupTestScenario(prisma, authenticatedEnvironment, {
totalWaitpoints: 500,
outputSizeKB: 10, // Smaller outputs for faster test
snapshotConfigs: [
{ status: "RUN_CREATED", completedWaitpointCount: 0 },
{ status: "QUEUED", completedWaitpointCount: 0 },
{ status: "EXECUTING", completedWaitpointCount: 0 },
{ status: "EXECUTING_WITH_WAITPOINTS", completedWaitpointCount: 500 },
{ status: "EXECUTING", completedWaitpointCount: 500 },
],
});
const result = await engine.getSnapshotsSince({
runId: scenario.run.id,
snapshotId: scenario.snapshots[0].id,
});
expect(result).not.toBeNull();
expect(result!.length).toBe(4);
const latest = result![result!.length - 1];
expect(latest.completedWaitpoints.length).toBe(500);
// All other snapshots should be empty
for (let i = 0; i < result!.length - 1; i++) {
expect(result![i].completedWaitpoints.length).toBe(0);
}
} finally {
await engine.quit();
}
}
);
});