-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathdelays.test.ts
More file actions
539 lines (479 loc) · 16.6 KB
/
Copy pathdelays.test.ts
File metadata and controls
539 lines (479 loc) · 16.6 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
import { containerTest, assertNonNullable } from "@internal/testcontainers";
import { trace } from "@internal/tracing";
import { expect } from "vitest";
import { RunEngine } from "../index.js";
import { setTimeout } from "timers/promises";
import { setupAuthenticatedEnvironment, setupBackgroundWorker } from "./setup.js";
vi.setConfig({ testTimeout: 60_000 });
describe("RunEngine delays", () => {
containerTest("Run start delayed", async ({ prisma, redisOptions }) => {
//create environment
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";
//create background worker
const backgroundWorker = await setupBackgroundWorker(
engine,
authenticatedEnvironment,
taskIdentifier
);
//trigger the run
const run = await engine.trigger(
{
number: 1,
friendlyId: "run_1234",
environment: authenticatedEnvironment,
taskIdentifier,
payload: "{}",
payloadType: "application/json",
context: {},
traceContext: {},
traceId: "t12345",
spanId: "s12345",
workerQueue: "main",
queue: "task/test-task",
isTest: false,
tags: [],
delayUntil: new Date(Date.now() + 500),
},
prisma
);
//should be delayed but not queued yet
const executionData = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData);
expect(executionData.snapshot.executionStatus).toBe("DELAYED");
//wait for 1 seconds
await setTimeout(1_000);
//should now be queued
const executionData2 = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData2);
expect(executionData2.snapshot.executionStatus).toBe("QUEUED");
} finally {
await engine.quit();
}
});
containerTest("Rescheduling a delayed run", async ({ prisma, redisOptions }) => {
//create environment
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";
//create background worker
const backgroundWorker = await setupBackgroundWorker(
engine,
authenticatedEnvironment,
taskIdentifier
);
//trigger the run
const run = await engine.trigger(
{
number: 1,
friendlyId: "run_1234",
environment: authenticatedEnvironment,
taskIdentifier,
payload: "{}",
payloadType: "application/json",
context: {},
traceContext: {},
traceId: "t12345",
spanId: "s12345",
workerQueue: "main",
queue: "task/test-task",
isTest: false,
tags: [],
delayUntil: new Date(Date.now() + 400),
},
prisma
);
//should be delayed but not queued yet
const executionData = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData);
expect(executionData.snapshot.executionStatus).toBe("DELAYED");
const rescheduleTo = new Date(Date.now() + 1_500);
const updatedRun = await engine.rescheduleDelayedRun({
runId: run.id,
delayUntil: rescheduleTo,
});
expect(updatedRun.delayUntil?.toISOString()).toBe(rescheduleTo.toISOString());
//wait so the initial delay passes
await setTimeout(1_000);
//should still be delayed (rescheduled)
const executionData2 = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData2);
expect(executionData2.snapshot.executionStatus).toBe("DELAYED");
//wait so the updated delay passes
await setTimeout(1_750);
//should now be queued
const executionData3 = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData3);
expect(executionData3.snapshot.executionStatus).toBe("QUEUED");
} finally {
await engine.quit();
}
});
containerTest("Delayed run with a ttl", async ({ prisma, redisOptions }) => {
//create environment
const authenticatedEnvironment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
const engine = new RunEngine({
prisma,
worker: {
redis: redisOptions,
workers: 1,
tasksPerWorker: 10,
pollIntervalMs: 100,
},
queue: {
redis: redisOptions,
ttlSystem: {
pollIntervalMs: 100,
batchSize: 10,
batchMaxWaitMs: 100,
},
},
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";
//create background worker
const backgroundWorker = await setupBackgroundWorker(
engine,
authenticatedEnvironment,
taskIdentifier
);
// TTL only expires runs still queued waiting on a concurrency slot.
// Once the delay elapses, the run gets enqueued; saturate env concurrency
// so it stays queued so the new TTL path can expire it.
await engine.runQueue.updateEnvConcurrencyLimits({
...authenticatedEnvironment,
maximumConcurrencyLimit: 0,
});
const enqueuedAfterDelayTimes: number[] = [];
engine.eventBus.on("runEnqueuedAfterDelay", () => {
enqueuedAfterDelayTimes.push(Date.now());
});
//trigger the run
const triggerTime = Date.now();
const run = await engine.trigger(
{
number: 1,
friendlyId: "run_1234",
environment: authenticatedEnvironment,
taskIdentifier,
payload: "{}",
payloadType: "application/json",
context: {},
traceContext: {},
traceId: "t12345",
spanId: "s12345",
workerQueue: "main",
queue: "task/test-task",
isTest: false,
tags: [],
delayUntil: new Date(triggerTime + 1000),
ttl: "2s",
},
prisma
);
//should be delayed but not queued yet
const executionData = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData);
expect(executionData.snapshot.executionStatus).toBe("DELAYED");
expect(run.status).toBe("DELAYED");
//wait so the delay elapses and the run is enqueued
await setTimeout(2_500);
//should now be queued
const executionData2 = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData2);
expect(executionData2.snapshot.executionStatus).toBe("QUEUED");
const run2 = await prisma.taskRun.findFirstOrThrow({
where: { id: run.id },
});
expect(run2.status).toBe("PENDING");
// TTL is armed at queue-enter time (not from triggerTime). With a 2s TTL
// and a 1s delay, the run becomes eligible to expire ~3s after trigger.
// Confirm the TTL was not armed against triggerTime (i.e. didn't already
// fire while still DELAYED), and that the run only expires after the
// queue-enter timestamp + ttl has elapsed.
expect(enqueuedAfterDelayTimes.length).toBe(1);
const enqueuedAt = enqueuedAfterDelayTimes[0]!;
expect(enqueuedAt - triggerTime).toBeGreaterThanOrEqual(1000);
//wait so the TTL fires (counted from when the run was enqueued)
await setTimeout(3_000);
// Status comes from the DB; the batch TTL path does not create
// execution snapshots, so getRunExecutionData may still show QUEUED.
const run3 = await prisma.taskRun.findFirstOrThrow({
where: { id: run.id },
});
expect(run3.status).toBe("EXPIRED");
assertNonNullable(run3.expiredAt);
// The expiry must happen after enqueue + ttl, not after trigger + ttl.
// Allow a small tolerance for poll interval + batch wait.
expect(run3.expiredAt.getTime()).toBeGreaterThanOrEqual(enqueuedAt + 2_000);
} finally {
await engine.quit();
}
});
containerTest("Cancelling a delayed run", async ({ prisma, redisOptions }) => {
//create environment
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";
//create background worker
const backgroundWorker = await setupBackgroundWorker(
engine,
authenticatedEnvironment,
taskIdentifier
);
//trigger the run with a 1 second delay
const run = await engine.trigger(
{
number: 1,
friendlyId: "run_1234",
environment: authenticatedEnvironment,
taskIdentifier,
payload: "{}",
payloadType: "application/json",
context: {},
traceContext: {},
traceId: "t12345",
spanId: "s12345",
workerQueue: "main",
queue: "task/test-task",
isTest: false,
tags: [],
delayUntil: new Date(Date.now() + 1000),
},
prisma
);
//verify it's delayed but not queued
const executionData = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData);
expect(executionData.snapshot.executionStatus).toBe("DELAYED");
expect(run.status).toBe("DELAYED");
//cancel the run
await engine.cancelRun({
runId: run.id,
reason: "Cancelled by test",
});
//verify it's cancelled
const executionData2 = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData2);
expect(executionData2.snapshot.executionStatus).toBe("FINISHED");
expect(executionData2.run.status).toBe("CANCELED");
//wait past the original delay time
await setTimeout(1500);
//verify the run is still cancelled
const executionData3 = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData3);
expect(executionData3.snapshot.executionStatus).toBe("FINISHED");
expect(executionData3.run.status).toBe("CANCELED");
//attempt to dequeue - should get nothing
await setTimeout(500);
const dequeued = await engine.dequeueFromWorkerQueue({
consumerId: "test_12345",
workerQueue: "main",
});
expect(dequeued.length).toBe(0);
//verify final state is still cancelled
const executionData4 = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData4);
expect(executionData4.snapshot.executionStatus).toBe("FINISHED");
expect(executionData4.run.status).toBe("CANCELED");
} finally {
await engine.quit();
}
});
containerTest(
"enqueueDelayedRun respects rescheduled delayUntil",
async ({ prisma, redisOptions }) => {
// This test verifies the race condition fix where if delayUntil is updated
// (e.g., by debounce reschedule) while the worker job is executing,
// the run should NOT be enqueued at the original time.
//
// The race condition occurs when:
// 1. Worker job is scheduled for T1
// 2. rescheduleDelayedRun updates delayUntil to T2 in DB
// 3. worker.reschedule() tries to update the job, but it's already dequeued
// 4. Original worker job fires and calls enqueueDelayedRun
//
// Without the fix: Run would be enqueued at T1 (wrong!)
// With the fix: enqueueDelayedRun checks delayUntil > now and skips
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);
// Create a delayed run with a short delay (300ms)
const run = await engine.trigger(
{
number: 1,
friendlyId: "run_1235",
environment: authenticatedEnvironment,
taskIdentifier,
payload: "{}",
payloadType: "application/json",
context: {},
traceContext: {},
traceId: "t12345",
spanId: "s12345",
workerQueue: "main",
queue: "task/test-task",
isTest: false,
tags: [],
delayUntil: new Date(Date.now() + 300),
},
prisma
);
// Verify it's delayed
const executionData = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData);
expect(executionData.snapshot.executionStatus).toBe("DELAYED");
// Simulate race condition: directly update delayUntil in the database to a future time
// This simulates what happens when rescheduleDelayedRun updates the DB but the
// worker.reschedule() call doesn't affect the already-dequeued job
const newDelayUntil = new Date(Date.now() + 10_000); // 10 seconds in the future
await prisma.taskRun.update({
where: { id: run.id },
data: { delayUntil: newDelayUntil },
});
// Wait past the original delay (500ms) so the worker job fires
await setTimeout(500);
// KEY ASSERTION: The run should still be DELAYED because the fix checks delayUntil > now
// Without the fix, the run would be QUEUED here (wrong!)
const executionData2 = await engine.getRunExecutionData({ runId: run.id });
assertNonNullable(executionData2);
expect(executionData2.snapshot.executionStatus).toBe("DELAYED");
// Note: We don't test the run eventually becoming QUEUED here because we only
// updated the DB (simulating the race). In the real scenario, rescheduleDelayedRun
// would also reschedule the worker job to fire at the new delayUntil time.
} finally {
await engine.quit();
}
}
);
});