@rivetkit/workflow-engine 3.0.6 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/context.ts CHANGED
@@ -32,12 +32,12 @@ import {
32
32
  } from "./location.js";
33
33
  import {
34
34
  createEntry,
35
- deleteEntriesWithPrefix,
36
35
  flush,
37
36
  getOrCreateMetadata,
38
37
  loadMetadata,
39
38
  type PendingDeletions,
40
39
  setEntry,
40
+ takeEntriesWithPrefix,
41
41
  } from "./storage.js";
42
42
  import type {
43
43
  BranchConfig,
@@ -71,6 +71,7 @@ import type {
71
71
  WorkflowQueueNextBatchOptions,
72
72
  WorkflowQueueNextOptions,
73
73
  } from "./types.js";
74
+ import { type LongTimeoutHandle, setLongTimeout } from "./utils.js";
74
75
 
75
76
  /**
76
77
  * Default values for step configuration.
@@ -295,6 +296,40 @@ function buildSchedulerYieldError(
295
296
  return new MessageWaitError(messageNames);
296
297
  }
297
298
 
299
+ /** A race branch waiting on the scheduler, and how to run it again in-process. */
300
+ interface YieldedRaceBranch {
301
+ error: SleepError | MessageWaitError | StepFailedError;
302
+ start: () => void;
303
+ }
304
+
305
+ /** A branch waiting only on messages has no deadline. */
306
+ function yieldedDeadline(yielded: YieldedRaceBranch): number | undefined {
307
+ const { error } = yielded;
308
+ if (error instanceof SleepError) {
309
+ return error.deadline;
310
+ }
311
+ if (error instanceof StepFailedError) {
312
+ return error.retryAt;
313
+ }
314
+ return undefined;
315
+ }
316
+
317
+ function earliestYieldedDeadline(
318
+ yieldedBranches: Map<string, YieldedRaceBranch>,
319
+ ): number | undefined {
320
+ let earliest: number | undefined;
321
+ for (const yielded of yieldedBranches.values()) {
322
+ const deadline = yieldedDeadline(yielded);
323
+ if (
324
+ deadline !== undefined &&
325
+ (earliest === undefined || deadline < earliest)
326
+ ) {
327
+ earliest = deadline;
328
+ }
329
+ }
330
+ return earliest;
331
+ }
332
+
298
333
  function controlFlowErrorPriority(error: Error): number {
299
334
  if (error instanceof EvictedError) {
300
335
  return 0;
@@ -343,6 +378,8 @@ export interface RollbackAction<T = unknown> {
343
378
  export class WorkflowContextImpl implements WorkflowContextInterface {
344
379
  private entryInProgress = false;
345
380
  private abortController: AbortController;
381
+ /** The run's signal. Race branches have their own, which eviction skips. */
382
+ private evictionSignal: AbortSignal;
346
383
  private currentLocation: Location;
347
384
  private visitedKeys: Set<string>;
348
385
  private runSpan?: WorkflowSpan;
@@ -374,6 +411,7 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
374
411
  ) {
375
412
  this.currentLocation = location;
376
413
  this.abortController = abortController ?? new AbortController();
414
+ this.evictionSignal = this.abortController.signal;
377
415
  this.mode = mode;
378
416
  this.rollbackActions = rollbackActions;
379
417
  this.rollbackCheckpointSet = rollbackCheckpointSet;
@@ -413,6 +451,11 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
413
451
  }
414
452
  }
415
453
 
454
+ /** Whether an enclosing race picked a winner and cancelled this branch. */
455
+ private isRaceCancelled(): boolean {
456
+ return this.abortSignal.reason instanceof CancelledError;
457
+ }
458
+
416
459
  private async flushStorage(): Promise<void> {
417
460
  await flush(this.storage, this.driver, this.historyNotifier);
418
461
  }
@@ -424,7 +467,7 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
424
467
  location: Location,
425
468
  abortController?: AbortController,
426
469
  ): WorkflowContextImpl {
427
- return new WorkflowContextImpl(
470
+ const branch = new WorkflowContextImpl(
428
471
  this.workflowId,
429
472
  this.storage,
430
473
  this.driver,
@@ -440,6 +483,8 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
440
483
  this.visitedKeys,
441
484
  this.runSpan,
442
485
  );
486
+ branch.evictionSignal = this.evictionSignal;
487
+ return branch;
443
488
  }
444
489
 
445
490
  /**
@@ -675,6 +720,34 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
675
720
  }
676
721
  }
677
722
 
723
+ /**
724
+ * Wait until `deadline`, a running race branch settles, or the workflow is
725
+ * evicted. The timer and abort listener are torn down on every outcome.
726
+ */
727
+ private async waitForRaceWake(
728
+ deadline: number,
729
+ runningBranches: Set<Promise<void>>,
730
+ ): Promise<void> {
731
+ let timer: ReturnType<typeof setLongTimeout> | undefined;
732
+ let onEvicted: (() => void) | undefined;
733
+ const wake = new Promise<void>((resolve) => {
734
+ timer = setLongTimeout(resolve, Math.max(0, deadline - Date.now()));
735
+ onEvicted = resolve;
736
+ this.evictionSignal.addEventListener("abort", onEvicted, {
737
+ once: true,
738
+ });
739
+ });
740
+
741
+ try {
742
+ await Promise.race([wake, ...runningBranches]);
743
+ } finally {
744
+ timer?.abort();
745
+ if (onEvicted) {
746
+ this.evictionSignal.removeEventListener("abort", onEvicted);
747
+ }
748
+ }
749
+ }
750
+
678
751
  // === Step ===
679
752
 
680
753
  async step<T>(
@@ -920,6 +993,11 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
920
993
  }
921
994
  }
922
995
 
996
+ // A race can cancel this branch while the metadata above loads.
997
+ if (this.isRaceCancelled()) {
998
+ throw new EvictedError();
999
+ }
1000
+
923
1001
  // Execute the step
924
1002
  const entry =
925
1003
  existing ?? createEntry(location, { type: "step", data: {} });
@@ -972,6 +1050,7 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
972
1050
  metadata.status = "completed";
973
1051
  metadata.error = undefined;
974
1052
  metadata.completedAt = Date.now();
1053
+ metadata.dirty = true;
975
1054
 
976
1055
  // Ephemeral steps don't trigger an immediate flush. This avoids the
977
1056
  // synchronous write overhead for transient operations. Note that the
@@ -995,10 +1074,20 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
995
1074
  });
996
1075
  return output;
997
1076
  } catch (error) {
1077
+ // The race that cancelled this step deletes its entry, so a
1078
+ // cancellation is not a failure to record or retry.
1079
+ if (this.isRaceCancelled()) {
1080
+ stepSpan?.finish("failed");
1081
+ throw new EvictedError();
1082
+ }
1083
+
998
1084
  if (entry.kind.type === "step") {
999
1085
  entry.kind.data.error = String(error);
1000
1086
  }
1001
1087
  entry.dirty = true;
1088
+ // A sibling branch can save this step's running metadata while the
1089
+ // callback runs, so the failure status must be saved again.
1090
+ metadata.dirty = true;
1002
1091
 
1003
1092
  // Timeout errors are treated as critical by default. Steps opt
1004
1093
  // into retrying on timeout with retryOnTimeout: true.
@@ -1145,23 +1234,33 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
1145
1234
  timeoutMs: number,
1146
1235
  stepName: string,
1147
1236
  ): Promise<T> {
1148
- if (timeoutMs <= 0) {
1149
- return promise;
1150
- }
1237
+ let interrupt!: (error: Error) => void;
1238
+ const interrupted = new Promise<never>((_, reject) => {
1239
+ interrupt = reject;
1240
+ });
1151
1241
 
1152
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
1153
- const timeoutPromise = new Promise<never>((_, reject) => {
1154
- timeoutId = setTimeout(() => {
1155
- reject(new StepTimeoutError(stepName, timeoutMs));
1242
+ // A timeout of 0 or a non-finite timeout such as Infinity disables the timeout.
1243
+ let timeout: LongTimeoutHandle | undefined;
1244
+ if (timeoutMs > 0 && Number.isFinite(timeoutMs)) {
1245
+ timeout = setLongTimeout(() => {
1246
+ interrupt(new StepTimeoutError(stepName, timeoutMs));
1156
1247
  }, timeoutMs);
1157
- });
1248
+ }
1249
+
1250
+ // A race that cancels this step stops awaiting it, as a timeout does.
1251
+ // Eviction does not interrupt a step, so its result is still recorded.
1252
+ const onAbort = () => {
1253
+ if (this.isRaceCancelled()) {
1254
+ interrupt(new EvictedError());
1255
+ }
1256
+ };
1257
+ this.abortSignal.addEventListener("abort", onAbort, { once: true });
1158
1258
 
1159
1259
  try {
1160
- return await Promise.race([promise, timeoutPromise]);
1260
+ return await Promise.race([promise, interrupted]);
1161
1261
  } finally {
1162
- if (timeoutId !== undefined) {
1163
- clearTimeout(timeoutId);
1164
- }
1262
+ timeout?.abort();
1263
+ this.abortSignal.removeEventListener("abort", onAbort);
1165
1264
  }
1166
1265
  }
1167
1266
 
@@ -2348,8 +2447,11 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
2348
2447
  // Create abort controller for cancellation
2349
2448
  const raceAbortController = new AbortController();
2350
2449
 
2351
- // Track all branch promises to wait for cleanup
2352
- const branchPromises: Promise<void>[] = [];
2450
+ // Track branches with in-process work to wait for cleanup
2451
+ const runningBranches = new Set<Promise<void>>();
2452
+
2453
+ // Track the wait of each branch that yielded, and how to run it again
2454
+ const yieldedBranches = new Map<string, YieldedRaceBranch>();
2353
2455
 
2354
2456
  // Track winner info
2355
2457
  let winnerName: string | null = null;
@@ -2357,7 +2459,6 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
2357
2459
  let hasWinner = false;
2358
2460
  const errors: Record<string, Error> = {};
2359
2461
  const lateErrors: Array<{ name: string; error: string }> = [];
2360
- let schedulerYieldState: SchedulerYieldState | undefined;
2361
2462
  let propagatedError: Error | undefined;
2362
2463
 
2363
2464
  // Check for replay winners first
@@ -2415,122 +2516,199 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
2415
2516
  continue;
2416
2517
  }
2417
2518
 
2418
- const branchCtx = this.createBranch(
2419
- branchLocation,
2420
- raceAbortController,
2421
- );
2422
-
2423
2519
  branchStatus.status = "running";
2424
2520
  branchStatus.error = undefined;
2425
2521
  entry.dirty = true;
2426
2522
 
2427
2523
  // Validate inside the run promise so a divergence reaches the
2428
- // rejection handler below instead of being dropped by allSettled.
2524
+ // rejection handler below instead of being dropped.
2429
2525
  const runBranch = async () => {
2526
+ const branchCtx = this.createBranch(
2527
+ branchLocation,
2528
+ raceAbortController,
2529
+ );
2430
2530
  const output = await branch.run(branchCtx);
2431
2531
  branchCtx.validateComplete();
2432
2532
  return output;
2433
2533
  };
2434
2534
 
2435
- const branchPromise = runBranch().then(
2436
- async (output) => {
2437
- if (hasWinner) {
2438
- // This branch completed after a winner was determined
2439
- // Still record the completion for observability
2440
- branchStatus.status = "completed";
2441
- branchStatus.output = output;
2442
- branchStatus.error = undefined;
2443
- entry.dirty = true;
2444
- return;
2445
- }
2446
-
2447
- if (propagatedError) {
2448
- branchStatus.status = "completed";
2449
- branchStatus.output = output;
2450
- branchStatus.error = undefined;
2451
- entry.dirty = true;
2452
- return;
2453
- }
2535
+ const startBranch = () => {
2536
+ const branchPromise = runBranch()
2537
+ .then(
2538
+ async (output) => {
2539
+ if (hasWinner) {
2540
+ // This branch completed after a winner was determined
2541
+ // Still record the completion for observability
2542
+ branchStatus.status = "completed";
2543
+ branchStatus.output = output;
2544
+ branchStatus.error = undefined;
2545
+ entry.dirty = true;
2546
+ return;
2547
+ }
2548
+
2549
+ if (propagatedError) {
2550
+ branchStatus.status = "completed";
2551
+ branchStatus.output = output;
2552
+ branchStatus.error = undefined;
2553
+ entry.dirty = true;
2554
+ return;
2555
+ }
2556
+
2557
+ hasWinner = true;
2558
+ winnerName = branch.name;
2559
+ winnerValue = output;
2560
+
2561
+ branchStatus.status = "completed";
2562
+ branchStatus.output = output;
2563
+ branchStatus.error = undefined;
2564
+ raceData.winner = branch.name;
2565
+ entry.dirty = true;
2566
+
2567
+ // Cancel other branches
2568
+ raceAbortController.abort(new CancelledError());
2569
+ },
2570
+ (error) => {
2571
+ if (hasWinner) {
2572
+ if (
2573
+ error instanceof CancelledError ||
2574
+ error instanceof EvictedError ||
2575
+ error instanceof SleepError ||
2576
+ error instanceof MessageWaitError
2577
+ ) {
2578
+ branchStatus.status = "cancelled";
2579
+ } else {
2580
+ lateErrors.push({
2581
+ name: branch.name,
2582
+ error: String(error),
2583
+ });
2584
+ }
2585
+ entry.dirty = true;
2586
+ return;
2587
+ }
2588
+
2589
+ if (
2590
+ error instanceof SleepError ||
2591
+ error instanceof MessageWaitError ||
2592
+ error instanceof StepFailedError
2593
+ ) {
2594
+ yieldedBranches.set(branch.name, {
2595
+ error,
2596
+ start: startBranch,
2597
+ });
2598
+ branchStatus.status = "running";
2599
+ branchStatus.error = undefined;
2600
+ entry.dirty = true;
2601
+ return;
2602
+ }
2603
+
2604
+ if (
2605
+ error instanceof EvictedError ||
2606
+ error instanceof HistoryDivergedError ||
2607
+ error instanceof EntryInProgressError ||
2608
+ error instanceof RollbackCheckpointError ||
2609
+ error instanceof RollbackStopError
2610
+ ) {
2611
+ propagatedError = selectControlFlowError(
2612
+ propagatedError,
2613
+ error,
2614
+ );
2615
+ branchStatus.status = "running";
2616
+ branchStatus.error = undefined;
2617
+ entry.dirty = true;
2618
+ return;
2619
+ }
2620
+
2621
+ if (error instanceof CancelledError) {
2622
+ branchStatus.status = "cancelled";
2623
+ } else {
2624
+ branchStatus.status = "failed";
2625
+ branchStatus.output = undefined;
2626
+ branchStatus.error = String(error);
2627
+ errors[branch.name] = error as Error;
2628
+ }
2629
+ entry.dirty = true;
2630
+ },
2631
+ )
2632
+ .finally(() => {
2633
+ runningBranches.delete(branchPromise);
2634
+ });
2635
+ runningBranches.add(branchPromise);
2636
+ };
2454
2637
 
2455
- hasWinner = true;
2456
- winnerName = branch.name;
2457
- winnerValue = output;
2638
+ startBranch();
2639
+ }
2458
2640
 
2459
- branchStatus.status = "completed";
2460
- branchStatus.output = output;
2461
- branchStatus.error = undefined;
2462
- raceData.winner = branch.name;
2463
- entry.dirty = true;
2641
+ // A cancelled branch also cancels the races nested inside it.
2642
+ const parentSignal = this.abortSignal;
2643
+ const forwardCancellation = () => {
2644
+ if (parentSignal.reason instanceof CancelledError) {
2645
+ raceAbortController.abort(parentSignal.reason);
2646
+ }
2647
+ };
2648
+ forwardCancellation();
2649
+ parentSignal.addEventListener("abort", forwardCancellation, {
2650
+ once: true,
2651
+ });
2464
2652
 
2465
- // Cancel other branches
2466
- raceAbortController.abort();
2467
- },
2468
- (error) => {
2469
- if (hasWinner) {
2470
- if (
2471
- error instanceof CancelledError ||
2472
- error instanceof EvictedError
2473
- ) {
2474
- branchStatus.status = "cancelled";
2475
- } else {
2476
- lateErrors.push({
2477
- name: branch.name,
2478
- error: String(error),
2479
- });
2653
+ // Wait for all branches to complete or be cancelled. Nothing else wakes
2654
+ // a yielded branch while another still has in-process work, because the
2655
+ // scheduler only takes over once every branch has settled.
2656
+ let scheduledWakeAt: number | undefined;
2657
+ try {
2658
+ while (runningBranches.size > 0) {
2659
+ const canWake =
2660
+ !propagatedError &&
2661
+ !raceAbortController.signal.aborted &&
2662
+ !this.evictionSignal.aborted;
2663
+
2664
+ if (canWake) {
2665
+ const now = Date.now();
2666
+ for (const [branchName, yielded] of yieldedBranches) {
2667
+ if ((yieldedDeadline(yielded) ?? Infinity) <= now) {
2668
+ yieldedBranches.delete(branchName);
2669
+ yielded.start();
2480
2670
  }
2481
- entry.dirty = true;
2482
- return;
2483
2671
  }
2672
+ }
2484
2673
 
2485
- if (
2486
- error instanceof SleepError ||
2487
- error instanceof MessageWaitError ||
2488
- error instanceof StepFailedError
2489
- ) {
2490
- schedulerYieldState = mergeSchedulerYield(
2491
- schedulerYieldState,
2492
- error,
2493
- );
2494
- branchStatus.status = "running";
2495
- branchStatus.error = undefined;
2496
- entry.dirty = true;
2497
- return;
2498
- }
2674
+ const wakeAt = canWake
2675
+ ? earliestYieldedDeadline(yieldedBranches)
2676
+ : undefined;
2677
+ if (wakeAt === undefined) {
2678
+ await Promise.race(runningBranches);
2679
+ continue;
2680
+ }
2499
2681
 
2500
- if (
2501
- error instanceof EvictedError ||
2502
- error instanceof HistoryDivergedError ||
2503
- error instanceof EntryInProgressError ||
2504
- error instanceof RollbackCheckpointError ||
2505
- error instanceof RollbackStopError
2506
- ) {
2682
+ // Keep the deadline durable, because the scheduler only arms it
2683
+ // if this run reaches a yield.
2684
+ if (wakeAt !== scheduledWakeAt) {
2685
+ scheduledWakeAt = wakeAt;
2686
+ try {
2687
+ await this.driver.setAlarm(this.workflowId, wakeAt);
2688
+ } catch (error) {
2507
2689
  propagatedError = selectControlFlowError(
2508
2690
  propagatedError,
2509
- error,
2691
+ error as Error,
2510
2692
  );
2511
- branchStatus.status = "running";
2512
- branchStatus.error = undefined;
2513
- entry.dirty = true;
2514
- return;
2515
2693
  }
2516
2694
 
2517
- if (error instanceof CancelledError) {
2518
- branchStatus.status = "cancelled";
2519
- } else {
2520
- branchStatus.status = "failed";
2521
- branchStatus.output = undefined;
2522
- branchStatus.error = String(error);
2523
- errors[branch.name] = error as Error;
2524
- }
2525
- entry.dirty = true;
2526
- },
2527
- );
2695
+ // A branch can settle during this write, so compute the wake again.
2696
+ continue;
2697
+ }
2528
2698
 
2529
- branchPromises.push(branchPromise);
2699
+ await this.waitForRaceWake(wakeAt, runningBranches);
2700
+ }
2701
+ } finally {
2702
+ parentSignal.removeEventListener("abort", forwardCancellation);
2530
2703
  }
2531
2704
 
2532
- // Wait for all branches to complete or be cancelled
2533
- await Promise.allSettled(branchPromises);
2705
+ // A cancelled race has no winner to report to its parent branch.
2706
+ if (!hasWinner && raceAbortController.signal.aborted) {
2707
+ propagatedError = selectControlFlowError(
2708
+ propagatedError,
2709
+ new EvictedError(),
2710
+ );
2711
+ }
2534
2712
 
2535
2713
  if (propagatedError) {
2536
2714
  await this.flushStorage();
@@ -2545,6 +2723,13 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
2545
2723
  )
2546
2724
  ) {
2547
2725
  await this.flushStorage();
2726
+ let schedulerYieldState: SchedulerYieldState | undefined;
2727
+ for (const { error } of yieldedBranches.values()) {
2728
+ schedulerYieldState = mergeSchedulerYield(
2729
+ schedulerYieldState,
2730
+ error,
2731
+ );
2732
+ }
2548
2733
  if (!schedulerYieldState) {
2549
2734
  throw new Error(
2550
2735
  `Race "${name}" has pending branches without a scheduler yield`,
@@ -2553,27 +2738,35 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
2553
2738
  throw buildSchedulerYieldError(schedulerYieldState);
2554
2739
  }
2555
2740
 
2556
- // Clean up entries from non-winning branches
2741
+ // Clean up entries from non-winning branches. The flush saves the
2742
+ // winner before it deletes them, so a crash in between leaves only
2743
+ // stale loser entries, which replay skips because the race has a winner.
2744
+ let loserDeletions: PendingDeletions | undefined;
2557
2745
  if (hasWinner && winnerName !== null) {
2746
+ loserDeletions = { prefixes: [], keys: [], ranges: [] };
2558
2747
  for (const branch of branches) {
2559
2748
  if (branch.name !== winnerName) {
2749
+ if (yieldedBranches.has(branch.name)) {
2750
+ raceData.branches[branch.name].status = "cancelled";
2751
+ entry.dirty = true;
2752
+ }
2560
2753
  const branchLocation = appendName(
2561
2754
  this.storage,
2562
2755
  location,
2563
2756
  branch.name,
2564
2757
  );
2565
- await deleteEntriesWithPrefix(
2758
+ const deletions = takeEntriesWithPrefix(
2566
2759
  this.storage,
2567
- this.driver,
2568
2760
  branchLocation,
2569
- this.historyNotifier,
2570
2761
  );
2762
+ loserDeletions.prefixes.push(...deletions.prefixes);
2763
+ loserDeletions.keys.push(...deletions.keys);
2571
2764
  }
2572
2765
  }
2573
2766
  }
2574
2767
 
2575
2768
  // Flush final state
2576
- await this.flushStorage();
2769
+ await this.flushStorageWithDeletions(loserDeletions);
2577
2770
 
2578
2771
  // Log late errors if any (these occurred after a winner was determined)
2579
2772
  if (lateErrors.length > 0) {