@rivetkit/workflow-engine 0.0.0-main.72cbc7c → 0.0.0-main.79e97f1

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
@@ -21,7 +21,7 @@ import {
21
21
  StepExhaustedError,
22
22
  StepFailedError,
23
23
  } from "./errors.js";
24
- import { buildLoopIterationRange, buildEntryMetadataKey } from "./keys.js";
24
+ import { buildEntryMetadataKey, buildLoopIterationRange } from "./keys.js";
25
25
  import {
26
26
  appendLoopIteration,
27
27
  appendName,
@@ -36,13 +36,12 @@ import {
36
36
  flush,
37
37
  getOrCreateMetadata,
38
38
  loadMetadata,
39
- setEntry,
40
39
  type PendingDeletions,
40
+ setEntry,
41
41
  } from "./storage.js";
42
42
  import type {
43
43
  BranchConfig,
44
44
  BranchOutput,
45
- BranchStatus,
46
45
  Entry,
47
46
  EntryKindType,
48
47
  EntryMetadata,
@@ -66,13 +65,12 @@ import type {
66
65
  WorkflowError,
67
66
  WorkflowErrorEvent,
68
67
  WorkflowErrorHandler,
68
+ WorkflowMessageDriver,
69
69
  WorkflowQueue,
70
70
  WorkflowQueueMessage,
71
71
  WorkflowQueueNextBatchOptions,
72
72
  WorkflowQueueNextOptions,
73
- WorkflowMessageDriver,
74
73
  } from "./types.js";
75
- import { sleep } from "./utils.js";
76
74
 
77
75
  /**
78
76
  * Default values for step configuration.
@@ -505,8 +503,7 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
505
503
  * Throws HistoryDivergedError if duplicate detected.
506
504
  */
507
505
  private checkDuplicateName(name: string): void {
508
- const fullKey =
509
- locationToKey(this.storage, this.currentLocation) + "/" + name;
506
+ const fullKey = `${locationToKey(this.storage, this.currentLocation)}/${name}`;
510
507
  if (this.usedNamesInExecution.has(fullKey)) {
511
508
  throw new HistoryDivergedError(
512
509
  `Duplicate entry name "${name}" at location "${locationToKey(this.storage, this.currentLocation)}". ` +
@@ -580,7 +577,7 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
580
577
  const isUnderPrefix =
581
578
  prefix === ""
582
579
  ? true // Root: all keys are children
583
- : key.startsWith(prefix + "/") || key === prefix;
580
+ : key.startsWith(`${prefix}/`) || key === prefix;
584
581
 
585
582
  if (isUnderPrefix) {
586
583
  if (!this.visitedKeys.has(key)) {
@@ -603,25 +600,33 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
603
600
  }
604
601
 
605
602
  /**
606
- * Wait for eviction message.
607
- *
608
- * The event listener uses { once: true } to auto-remove after firing,
609
- * preventing memory leaks if this method is called multiple times.
603
+ * Wait for `ms`, rejecting early with EvictedError if the workflow is
604
+ * evicted. Both the timer and the abort listener are torn down on either
605
+ * outcome, so a completed sleep never leaves a dangling listener on the
606
+ * long-lived run abort signal.
610
607
  */
611
- waitForEviction(): Promise<never> {
612
- return new Promise((_, reject) => {
613
- if (this.abortSignal.aborted) {
614
- reject(new EvictedError());
615
- return;
608
+ private async sleepOrEvict(ms: number): Promise<void> {
609
+ if (this.abortSignal.aborted) {
610
+ throw new EvictedError();
611
+ }
612
+ let timer: ReturnType<typeof setTimeout> | undefined;
613
+ let onAbort: (() => void) | undefined;
614
+ try {
615
+ await new Promise<void>((resolve, reject) => {
616
+ timer = setTimeout(resolve, ms);
617
+ onAbort = () => reject(new EvictedError());
618
+ this.abortSignal.addEventListener("abort", onAbort, {
619
+ once: true,
620
+ });
621
+ });
622
+ } finally {
623
+ if (timer !== undefined) {
624
+ clearTimeout(timer);
616
625
  }
617
- this.abortSignal.addEventListener(
618
- "abort",
619
- () => {
620
- reject(new EvictedError());
621
- },
622
- { once: true },
623
- );
624
- });
626
+ if (onAbort) {
627
+ this.abortSignal.removeEventListener("abort", onAbort);
628
+ }
629
+ }
625
630
  }
626
631
 
627
632
  // === Step ===
@@ -825,10 +830,7 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
825
830
  const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
826
831
 
827
832
  if (metadata.attempts > maxRetries) {
828
- // Prefer step history error, but fall back to metadata since
829
- // driver implementations may persist metadata without the history
830
- // entry error (e.g. partial writes/crashes between attempts).
831
- const lastError = stepData.error ?? metadata.error;
833
+ const lastError = metadata.error;
832
834
  const exhaustedError = new StepExhaustedError(
833
835
  config.name,
834
836
  lastError,
@@ -941,15 +943,16 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
941
943
  });
942
944
  return output;
943
945
  } catch (error) {
944
- // Timeout errors are treated as critical (no retry)
945
- if (error instanceof StepTimeoutError) {
946
- if (entry.kind.type === "step") {
947
- entry.kind.data.error = String(error);
948
- }
949
- entry.dirty = true;
946
+ if (entry.kind.type === "step") {
947
+ entry.kind.data.error = String(error);
948
+ }
949
+ entry.dirty = true;
950
+
951
+ // Timeout errors are treated as critical by default. Steps opt
952
+ // into retrying on timeout with retryOnTimeout: true.
953
+ if (error instanceof StepTimeoutError && !config.retryOnTimeout) {
950
954
  metadata.status = "exhausted";
951
955
  metadata.error = String(error);
952
- await this.flushStorage();
953
956
  await this.notifyStepError(config, metadata.attempts, error, {
954
957
  willRetry: false,
955
958
  });
@@ -967,13 +970,8 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
967
970
  error instanceof CriticalError ||
968
971
  error instanceof RollbackError
969
972
  ) {
970
- if (entry.kind.type === "step") {
971
- entry.kind.data.error = String(error);
972
- }
973
- entry.dirty = true;
974
973
  metadata.status = "exhausted";
975
974
  metadata.error = String(error);
976
- await this.flushStorage();
977
975
  await this.notifyStepError(config, metadata.attempts, error, {
978
976
  willRetry: false,
979
977
  });
@@ -990,15 +988,10 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
990
988
  );
991
989
  }
992
990
 
993
- if (entry.kind.type === "step") {
994
- entry.kind.data.error = String(error);
995
- }
996
- entry.dirty = true;
997
991
  const willRetry = metadata.attempts <= maxRetries;
998
992
  metadata.status = willRetry ? "failed" : "exhausted";
999
993
  metadata.error = String(error);
1000
994
 
1001
- await this.flushStorage();
1002
995
  if (willRetry) {
1003
996
  const retryDelay = calculateBackoff(
1004
997
  metadata.attempts,
@@ -1023,7 +1016,10 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
1023
1016
  attachTryStepFailure(
1024
1017
  new StepExhaustedError(config.name, String(error)),
1025
1018
  {
1026
- kind: "exhausted",
1019
+ kind:
1020
+ error instanceof StepTimeoutError
1021
+ ? "timeout"
1022
+ : "exhausted",
1027
1023
  stepName: config.name,
1028
1024
  attempts: metadata.attempts,
1029
1025
  error: extractErrorInfo(error),
@@ -1042,7 +1038,9 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
1042
1038
  *
1043
1039
  * Note: This does NOT cancel the underlying operation. JavaScript Promises
1044
1040
  * cannot be cancelled once started. When a timeout occurs:
1045
- * - The step is marked as failed with StepTimeoutError
1041
+ * - The step is rejected with StepTimeoutError. By default this is treated
1042
+ * as a critical failure with no retry. Set retryOnTimeout: true on the
1043
+ * step config to retry timeouts like any other error.
1046
1044
  * - The underlying async operation continues running in the background
1047
1045
  * - Any side effects from the operation may still occur
1048
1046
  *
@@ -1493,7 +1491,7 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
1493
1491
 
1494
1492
  // Short sleep: wait in memory
1495
1493
  if (remaining < this.driver.workerPollInterval) {
1496
- await Promise.race([sleep(remaining), this.waitForEviction()]);
1494
+ await this.sleepOrEvict(remaining);
1497
1495
 
1498
1496
  this.checkEvicted();
1499
1497
 
@@ -2583,4 +2581,97 @@ export class WorkflowContextImpl implements WorkflowContextInterface {
2583
2581
  setEntry(this.storage, location, entry);
2584
2582
  await this.flushStorage();
2585
2583
  }
2584
+
2585
+ // === Version ===
2586
+
2587
+ async getVersion(name: string, latest: number): Promise<number> {
2588
+ this.assertNotInProgress();
2589
+ this.checkEvicted();
2590
+
2591
+ this.entryInProgress = true;
2592
+ try {
2593
+ return await this.executeGetVersion(name, latest);
2594
+ } finally {
2595
+ this.entryInProgress = false;
2596
+ }
2597
+ }
2598
+
2599
+ private async executeGetVersion(
2600
+ name: string,
2601
+ latest: number,
2602
+ ): Promise<number> {
2603
+ if (!Number.isInteger(latest) || latest < 1) {
2604
+ throw new Error(
2605
+ `getVersion("${name}", ${latest}): latest must be an integer >= 1`,
2606
+ );
2607
+ }
2608
+
2609
+ // Check for duplicate name in current execution
2610
+ this.checkDuplicateName(name);
2611
+
2612
+ const location = appendName(this.storage, this.currentLocation, name);
2613
+ const key = locationToKey(this.storage, location);
2614
+ const existing = this.storage.history.entries.get(key);
2615
+
2616
+ // Mark this entry as visited for validateComplete
2617
+ this.markVisited(key);
2618
+
2619
+ this.stopRollbackIfMissing(existing);
2620
+
2621
+ if (existing) {
2622
+ if (existing.kind.type !== "version_check") {
2623
+ throw new HistoryDivergedError(
2624
+ `Expected version_check at ${key}, found ${existing.kind.type}`,
2625
+ );
2626
+ }
2627
+ // Pure replay: this instance is already pinned at this location.
2628
+ return existing.kind.data.resolved;
2629
+ }
2630
+
2631
+ // No recorded version at this location. Decide whether this instance
2632
+ // already executed past this point under older code (old in-flight) or
2633
+ // is reaching it fresh at the live frontier.
2634
+ //
2635
+ // The discriminator is "is there any unvisited history entry under the
2636
+ // current scope?". Entries created earlier in this same run are already
2637
+ // marked visited, so the only unvisited entries under the scope are
2638
+ // leftovers from a prior run, which proves this scope already executed
2639
+ // under code that predates this gate. Such instances resolve to the
2640
+ // implicit floor version 1 (old branch); fresh instances resolve to
2641
+ // `latest`.
2642
+ const resolved = this.hasUnvisitedUnderCurrentScope(key) ? 1 : latest;
2643
+
2644
+ const entry = createEntry(location, {
2645
+ type: "version_check",
2646
+ data: { resolved, latest },
2647
+ });
2648
+ setEntry(this.storage, location, entry);
2649
+ await this.flushStorage();
2650
+
2651
+ return resolved;
2652
+ }
2653
+
2654
+ /**
2655
+ * Returns true if any history entry under the current location scope
2656
+ * (other than `excludeKey`) has not yet been visited this run. Used by
2657
+ * getVersion to detect an old in-flight instance whose scope was already
2658
+ * executed by code that predates a version gate.
2659
+ */
2660
+ private hasUnvisitedUnderCurrentScope(excludeKey: string): boolean {
2661
+ const prefix = locationToKey(this.storage, this.currentLocation);
2662
+
2663
+ for (const key of this.storage.history.entries.keys()) {
2664
+ if (key === excludeKey) {
2665
+ continue;
2666
+ }
2667
+ const isUnderPrefix =
2668
+ prefix === ""
2669
+ ? true
2670
+ : key.startsWith(`${prefix}/`) || key === prefix;
2671
+ if (isUnderPrefix && !this.visitedKeys.has(key)) {
2672
+ return true;
2673
+ }
2674
+ }
2675
+ return false;
2676
+ }
2586
2677
  }
package/src/driver.ts CHANGED
@@ -30,6 +30,12 @@ export interface KVWrite {
30
30
  * See architecture.md "Isolation Model" for details.
31
31
  */
32
32
  export interface EngineDriver {
33
+ /**
34
+ * Requires each logical storage flush to reach `batch` as one indivisible
35
+ * unit. The driver must reject an oversized unit instead of splitting it.
36
+ */
37
+ readonly atomicBatch?: boolean;
38
+
33
39
  // === KV Operations ===
34
40
 
35
41
  /**
package/src/index.ts CHANGED
@@ -13,6 +13,7 @@ export {
13
13
  } from "./context.js";
14
14
  // Driver
15
15
  export type { EngineDriver, KVEntry, KVWrite } from "./driver.js";
16
+ export { extractErrorInfo } from "./error-utils.js";
16
17
  // Errors
17
18
  export {
18
19
  CancelledError,
@@ -29,7 +30,6 @@ export {
29
30
  StepExhaustedError,
30
31
  StepFailedError,
31
32
  } from "./errors.js";
32
- export { extractErrorInfo } from "./error-utils.js";
33
33
 
34
34
  // Location utilities
35
35
  export {
@@ -82,9 +82,6 @@ export type {
82
82
  PathSegment,
83
83
  RaceEntry,
84
84
  RemovedEntry,
85
- WorkflowEntryMetadataSnapshot,
86
- WorkflowHistoryEntry,
87
- WorkflowHistorySnapshot,
88
85
  RollbackCheckpointEntry,
89
86
  RollbackContextInterface,
90
87
  RunWorkflowOptions,
@@ -102,20 +99,23 @@ export type {
102
99
  TryStepFailure,
103
100
  TryStepResult,
104
101
  WorkflowContextInterface,
102
+ WorkflowEntryMetadataSnapshot,
105
103
  WorkflowError,
106
104
  WorkflowErrorEvent,
107
105
  WorkflowErrorHandler,
108
106
  WorkflowFunction,
109
107
  WorkflowHandle,
110
- WorkflowRollbackErrorEvent,
108
+ WorkflowHistoryEntry,
109
+ WorkflowHistorySnapshot,
110
+ WorkflowMessageDriver,
111
111
  WorkflowQueue,
112
112
  WorkflowQueueMessage,
113
113
  WorkflowQueueNextBatchOptions,
114
114
  WorkflowQueueNextOptions,
115
- WorkflowMessageDriver,
116
115
  WorkflowResult,
117
- WorkflowRunMode,
116
+ WorkflowRollbackErrorEvent,
118
117
  WorkflowRunErrorEvent,
118
+ WorkflowRunMode,
119
119
  WorkflowState,
120
120
  WorkflowStepErrorEvent,
121
121
  } from "./types.js";
@@ -185,9 +185,9 @@ import type {
185
185
  RunWorkflowOptions,
186
186
  Storage,
187
187
  WorkflowErrorEvent,
188
- WorkflowHistorySnapshot,
189
188
  WorkflowFunction,
190
189
  WorkflowHandle,
190
+ WorkflowHistorySnapshot,
191
191
  WorkflowMessageDriver,
192
192
  WorkflowResult,
193
193
  WorkflowRunMode,
@@ -532,26 +532,46 @@ async function executeLiveWorkflow<TInput, TOutput>(
532
532
  const hasDeadline = result.sleepUntil !== undefined;
533
533
 
534
534
  if (hasMessages && hasDeadline) {
535
- // Wait for EITHER a message OR the deadline (for queue.next timeout)
535
+ // Wait for EITHER a message OR the deadline (for queue.next timeout).
536
+ // Scope both waiters to a per-iteration controller chained to the run
537
+ // signal so that whichever loses the race is cancelled immediately.
538
+ // Otherwise the loser (a message waiter or an armed sleep timer) stays
539
+ // registered on the long-lived run signal and leaks once per cycle.
540
+ const iterationAbort = new AbortController();
541
+ const onRunAbort = () => iterationAbort.abort();
542
+ if (abortController.signal.aborted) {
543
+ iterationAbort.abort();
544
+ } else {
545
+ abortController.signal.addEventListener("abort", onRunAbort, {
546
+ once: true,
547
+ });
548
+ }
549
+ const messagePromise = awaitWithEviction(
550
+ driver.waitForMessages(
551
+ result.waitingForMessages!,
552
+ iterationAbort.signal,
553
+ ),
554
+ iterationAbort.signal,
555
+ );
556
+ const sleepPromise = waitForSleep(
557
+ runtime,
558
+ result.sleepUntil!,
559
+ iterationAbort.signal,
560
+ );
561
+ // Swallow the loser's rejection once it is aborted below so it does
562
+ // not surface as an unhandled rejection.
563
+ messagePromise.catch(() => {});
564
+ sleepPromise.catch(() => {});
536
565
  try {
537
- const messagePromise = awaitWithEviction(
538
- driver.waitForMessages(
539
- result.waitingForMessages!,
540
- abortController.signal,
541
- ),
542
- abortController.signal,
543
- );
544
- const sleepPromise = waitForSleep(
545
- runtime,
546
- result.sleepUntil!,
547
- abortController.signal,
548
- );
549
566
  await Promise.race([messagePromise, sleepPromise]);
550
567
  } catch (error) {
551
568
  if (error instanceof EvictedError) {
552
569
  return lastResult;
553
570
  }
554
571
  throw error;
572
+ } finally {
573
+ iterationAbort.abort();
574
+ abortController.signal.removeEventListener("abort", onRunAbort);
555
575
  }
556
576
  continue;
557
577
  }
package/src/location.ts CHANGED
@@ -159,7 +159,7 @@ export function getChildEntries(
159
159
  const isChild =
160
160
  parentKey === ""
161
161
  ? true
162
- : key.startsWith(parentKey + "/") || key === parentKey;
162
+ : key.startsWith(`${parentKey}/`) || key === parentKey;
163
163
 
164
164
  if (isChild) {
165
165
  // Return the actual entry's location, not the parent location
package/src/storage.ts CHANGED
@@ -318,8 +318,12 @@ export async function flush(
318
318
  }
319
319
 
320
320
  if (writes.length > 0) {
321
- for (const chunk of splitBatchWrites(writes)) {
322
- await driver.batch(chunk);
321
+ if (driver.atomicBatch) {
322
+ await driver.batch(writes);
323
+ } else {
324
+ for (const chunk of splitBatchWrites(writes)) {
325
+ await driver.batch(chunk);
326
+ }
323
327
  }
324
328
  }
325
329
 
package/src/types.ts CHANGED
@@ -135,6 +135,17 @@ export interface RemovedEntry {
135
135
  originalName?: string;
136
136
  }
137
137
 
138
+ /**
139
+ * Version check entry data - records which version of a code path this
140
+ * workflow instance is pinned to at a given location.
141
+ */
142
+ export interface VersionCheckEntry {
143
+ /** The version this instance resolved to at this location. */
144
+ resolved: number;
145
+ /** The `latest` value seen when this entry was first resolved (diagnostics). */
146
+ latest: number;
147
+ }
148
+
138
149
  /**
139
150
  * All possible entry kind types.
140
151
  */
@@ -146,7 +157,8 @@ export type EntryKindType =
146
157
  | "rollback_checkpoint"
147
158
  | "join"
148
159
  | "race"
149
- | "removed";
160
+ | "removed"
161
+ | "version_check";
150
162
 
151
163
  /**
152
164
  * Type-specific entry data.
@@ -159,7 +171,8 @@ export type EntryKind =
159
171
  | { type: "rollback_checkpoint"; data: RollbackCheckpointEntry }
160
172
  | { type: "join"; data: JoinEntry }
161
173
  | { type: "race"; data: RaceEntry }
162
- | { type: "removed"; data: RemovedEntry };
174
+ | { type: "removed"; data: RemovedEntry }
175
+ | { type: "version_check"; data: VersionCheckEntry };
163
176
 
164
177
  /**
165
178
  * An entry in the workflow history.
@@ -399,6 +412,8 @@ export interface StepConfig<T> {
399
412
  retryBackoffMax?: number;
400
413
  /** Timeout in ms for step execution (default: 30000). Set to 0 to disable. */
401
414
  timeout?: number;
415
+ /** If true, step timeouts retry like any other error instead of failing immediately as critical. Default: false. */
416
+ retryOnTimeout?: boolean;
402
417
  }
403
418
 
404
419
  export type TryStepCatchKind =
@@ -455,7 +470,7 @@ export type LoopResult<S, T> =
455
470
  * `Loop.continue(undefined)`.
456
471
  */
457
472
  export type LoopIterationResult<S, T> = Promise<
458
- LoopResult<S, T> | (S extends undefined ? void : never)
473
+ LoopResult<S, T> | (S extends undefined ? undefined : never)
459
474
  >;
460
475
 
461
476
  /**
@@ -537,6 +552,8 @@ export interface WorkflowContextInterface {
537
552
 
538
553
  removed(name: string, originalType: EntryKindType): Promise<void>;
539
554
 
555
+ getVersion(name: string, latest: number): Promise<number>;
556
+
540
557
  isEvicted(): boolean;
541
558
  }
542
559