@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.
@@ -1554,7 +1554,35 @@ async function loadMetadata(storage, driver, entryId) {
1554
1554
  }
1555
1555
  return getOrCreateMetadata(storage, entryId);
1556
1556
  }
1557
- async function flush(storage, driver, onHistoryUpdated, pendingDeletions) {
1557
+ var flushQueues = /* @__PURE__ */ new WeakMap();
1558
+ function flush(storage, driver, onHistoryUpdated, pendingDeletions) {
1559
+ let queue = flushQueues.get(storage);
1560
+ if (!queue) {
1561
+ queue = { tail: Promise.resolve() };
1562
+ flushQueues.set(storage, queue);
1563
+ }
1564
+ if (queue.waiting && !pendingDeletions) {
1565
+ return queue.waiting;
1566
+ }
1567
+ const activeQueue = queue;
1568
+ const next = activeQueue.tail.then(() => {
1569
+ if (activeQueue.waiting === next) {
1570
+ activeQueue.waiting = void 0;
1571
+ }
1572
+ return flushSnapshot(
1573
+ storage,
1574
+ driver,
1575
+ onHistoryUpdated,
1576
+ pendingDeletions
1577
+ );
1578
+ });
1579
+ if (!pendingDeletions) {
1580
+ activeQueue.waiting = next;
1581
+ }
1582
+ activeQueue.tail = next.catch(() => void 0);
1583
+ return next;
1584
+ }
1585
+ async function flushSnapshot(storage, driver, onHistoryUpdated, pendingDeletions) {
1558
1586
  const writes = [];
1559
1587
  const dirtyEntries = [];
1560
1588
  const dirtyMetadata = [];
@@ -1608,31 +1636,45 @@ async function flush(storage, driver, onHistoryUpdated, pendingDeletions) {
1608
1636
  value: serializeWorkflowError(storage.error)
1609
1637
  });
1610
1638
  }
1611
- if (writes.length > 0) {
1612
- if (driver.atomicBatch) {
1613
- await driver.batch(writes);
1614
- } else {
1615
- for (const chunk of splitBatchWrites(writes)) {
1616
- await driver.batch(chunk);
1617
- }
1618
- }
1619
- }
1620
- if (pendingDeletions) {
1621
- const didChange = await runDeletes(driver, pendingDeletions);
1622
- if (didChange) {
1623
- historyUpdated = true;
1624
- }
1625
- }
1639
+ const savedNameCount = storage.nameRegistry.length;
1640
+ const savedState = storage.state;
1641
+ const savedOutput = storage.output;
1642
+ const savedError = storage.error;
1626
1643
  for (const entry of dirtyEntries) {
1627
1644
  entry.dirty = false;
1628
1645
  }
1629
1646
  for (const metadata of dirtyMetadata) {
1630
1647
  metadata.dirty = false;
1631
1648
  }
1632
- storage.flushedNameCount = storage.nameRegistry.length;
1633
- storage.flushedState = storage.state;
1634
- storage.flushedOutput = storage.output;
1635
- storage.flushedError = storage.error;
1649
+ try {
1650
+ if (writes.length > 0) {
1651
+ if (driver.atomicBatch) {
1652
+ await driver.batch(writes);
1653
+ } else {
1654
+ for (const chunk of splitBatchWrites(writes)) {
1655
+ await driver.batch(chunk);
1656
+ }
1657
+ }
1658
+ }
1659
+ if (pendingDeletions) {
1660
+ const didChange = await runDeletes(driver, pendingDeletions);
1661
+ if (didChange) {
1662
+ historyUpdated = true;
1663
+ }
1664
+ }
1665
+ } catch (error) {
1666
+ for (const entry of dirtyEntries) {
1667
+ entry.dirty = true;
1668
+ }
1669
+ for (const metadata of dirtyMetadata) {
1670
+ metadata.dirty = true;
1671
+ }
1672
+ throw error;
1673
+ }
1674
+ storage.flushedNameCount = savedNameCount;
1675
+ storage.flushedState = savedState;
1676
+ storage.flushedOutput = savedOutput;
1677
+ storage.flushedError = savedError;
1636
1678
  if (historyUpdated && onHistoryUpdated) {
1637
1679
  onHistoryUpdated();
1638
1680
  }
@@ -1693,6 +1735,22 @@ async function runDeletes(driver, deletions) {
1693
1735
  }
1694
1736
  return metadataOps.length > 0 || historyOps.length > 0;
1695
1737
  }
1738
+ function takeEntriesWithPrefix(storage, prefixLocation) {
1739
+ const metadataKeys = [];
1740
+ for (const [key, entry] of [...storage.history.entries]) {
1741
+ if (!isLocationPrefix(prefixLocation, entry.location)) {
1742
+ continue;
1743
+ }
1744
+ metadataKeys.push(buildEntryMetadataKey(entry.id));
1745
+ storage.entryMetadata.delete(entry.id);
1746
+ storage.history.entries.delete(key);
1747
+ }
1748
+ return {
1749
+ prefixes: [buildHistoryPrefix(prefixLocation)],
1750
+ keys: metadataKeys,
1751
+ ranges: []
1752
+ };
1753
+ }
1696
1754
  async function deleteEntriesWithPrefix(storage, driver, prefixLocation, onHistoryUpdated) {
1697
1755
  const entries = [...storage.history.entries].filter(
1698
1756
  ([, entry]) => isLocationPrefix(prefixLocation, entry.location)
@@ -1719,6 +1777,30 @@ function setEntry(storage, location, entry) {
1719
1777
  storage.history.entries.set(key, entry);
1720
1778
  }
1721
1779
 
1780
+ // src/utils.ts
1781
+ function sleep(ms) {
1782
+ return new Promise((resolve) => setTimeout(resolve, ms));
1783
+ }
1784
+ var TIMEOUT_MAX = 2147483647;
1785
+ function setLongTimeout(listener, after) {
1786
+ let timeout;
1787
+ function start(remaining) {
1788
+ if (remaining <= TIMEOUT_MAX) {
1789
+ timeout = setTimeout(listener, remaining);
1790
+ } else {
1791
+ timeout = setTimeout(() => {
1792
+ start(remaining - TIMEOUT_MAX);
1793
+ }, TIMEOUT_MAX);
1794
+ }
1795
+ }
1796
+ start(after);
1797
+ return {
1798
+ abort: () => {
1799
+ if (timeout !== void 0) clearTimeout(timeout);
1800
+ }
1801
+ };
1802
+ }
1803
+
1722
1804
  // src/context.ts
1723
1805
  var DEFAULT_MAX_RETRIES = 3;
1724
1806
  var DEFAULT_RETRY_BACKOFF_BASE = 100;
@@ -1847,6 +1929,26 @@ function buildSchedulerYieldError(state) {
1847
1929
  }
1848
1930
  return new MessageWaitError(messageNames);
1849
1931
  }
1932
+ function yieldedDeadline(yielded) {
1933
+ const { error } = yielded;
1934
+ if (error instanceof SleepError) {
1935
+ return error.deadline;
1936
+ }
1937
+ if (error instanceof StepFailedError) {
1938
+ return error.retryAt;
1939
+ }
1940
+ return void 0;
1941
+ }
1942
+ function earliestYieldedDeadline(yieldedBranches) {
1943
+ let earliest;
1944
+ for (const yielded of yieldedBranches.values()) {
1945
+ const deadline = yieldedDeadline(yielded);
1946
+ if (deadline !== void 0 && (earliest === void 0 || deadline < earliest)) {
1947
+ earliest = deadline;
1948
+ }
1949
+ }
1950
+ return earliest;
1951
+ }
1850
1952
  function controlFlowErrorPriority(error) {
1851
1953
  if (error instanceof EvictedError) {
1852
1954
  return 0;
@@ -1879,6 +1981,7 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
1879
1981
  this.messageDriver = messageDriver;
1880
1982
  this.currentLocation = location;
1881
1983
  this.abortController = abortController ?? new AbortController();
1984
+ this.evictionSignal = this.abortController.signal;
1882
1985
  this.mode = mode;
1883
1986
  this.rollbackActions = rollbackActions;
1884
1987
  this.rollbackCheckpointSet = rollbackCheckpointSet;
@@ -1890,6 +1993,8 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
1890
1993
  }
1891
1994
  entryInProgress = false;
1892
1995
  abortController;
1996
+ /** The run's signal. Race branches have their own, which eviction skips. */
1997
+ evictionSignal;
1893
1998
  currentLocation;
1894
1999
  visitedKeys;
1895
2000
  runSpan;
@@ -1925,6 +2030,10 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
1925
2030
  throw new EvictedError();
1926
2031
  }
1927
2032
  }
2033
+ /** Whether an enclosing race picked a winner and cancelled this branch. */
2034
+ isRaceCancelled() {
2035
+ return this.abortSignal.reason instanceof CancelledError;
2036
+ }
1928
2037
  async flushStorage() {
1929
2038
  await flush(this.storage, this.driver, this.historyNotifier);
1930
2039
  }
@@ -1932,7 +2041,7 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
1932
2041
  * Create a new branch context for parallel/nested execution.
1933
2042
  */
1934
2043
  createBranch(location, abortController) {
1935
- return new _WorkflowContextImpl(
2044
+ const branch = new _WorkflowContextImpl(
1936
2045
  this.workflowId,
1937
2046
  this.storage,
1938
2047
  this.driver,
@@ -1948,6 +2057,8 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
1948
2057
  this.visitedKeys,
1949
2058
  this.runSpan
1950
2059
  );
2060
+ branch.evictionSignal = this.evictionSignal;
2061
+ return branch;
1951
2062
  }
1952
2063
  /**
1953
2064
  * Log a debug message using the configured logger.
@@ -2127,6 +2238,29 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
2127
2238
  }
2128
2239
  }
2129
2240
  }
2241
+ /**
2242
+ * Wait until `deadline`, a running race branch settles, or the workflow is
2243
+ * evicted. The timer and abort listener are torn down on every outcome.
2244
+ */
2245
+ async waitForRaceWake(deadline, runningBranches) {
2246
+ let timer;
2247
+ let onEvicted;
2248
+ const wake = new Promise((resolve) => {
2249
+ timer = setLongTimeout(resolve, Math.max(0, deadline - Date.now()));
2250
+ onEvicted = resolve;
2251
+ this.evictionSignal.addEventListener("abort", onEvicted, {
2252
+ once: true
2253
+ });
2254
+ });
2255
+ try {
2256
+ await Promise.race([wake, ...runningBranches]);
2257
+ } finally {
2258
+ timer == null ? void 0 : timer.abort();
2259
+ if (onEvicted) {
2260
+ this.evictionSignal.removeEventListener("abort", onEvicted);
2261
+ }
2262
+ }
2263
+ }
2130
2264
  // === Step ===
2131
2265
  async step(nameOrConfig, run) {
2132
2266
  this.assertNotInProgress();
@@ -2313,6 +2447,9 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
2313
2447
  throw new SleepError(retryAt);
2314
2448
  }
2315
2449
  }
2450
+ if (this.isRaceCancelled()) {
2451
+ throw new EvictedError();
2452
+ }
2316
2453
  const entry = existing ?? createEntry(location, { type: "step", data: {} });
2317
2454
  if (!existing) {
2318
2455
  this.log("debug", {
@@ -2353,6 +2490,7 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
2353
2490
  metadata.status = "completed";
2354
2491
  metadata.error = void 0;
2355
2492
  metadata.completedAt = Date.now();
2493
+ metadata.dirty = true;
2356
2494
  if (!config2.ephemeral) {
2357
2495
  this.log("debug", {
2358
2496
  msg: "flushing step",
@@ -2369,10 +2507,15 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
2369
2507
  });
2370
2508
  return output;
2371
2509
  } catch (error) {
2510
+ if (this.isRaceCancelled()) {
2511
+ stepSpan == null ? void 0 : stepSpan.finish("failed");
2512
+ throw new EvictedError();
2513
+ }
2372
2514
  if (entry.kind.type === "step") {
2373
2515
  entry.kind.data.error = String(error);
2374
2516
  }
2375
2517
  entry.dirty = true;
2518
+ metadata.dirty = true;
2376
2519
  if (error instanceof StepTimeoutError && !config2.retryOnTimeout) {
2377
2520
  stepSpan == null ? void 0 : stepSpan.finish("failed", error);
2378
2521
  metadata.status = "exhausted";
@@ -2491,21 +2634,27 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
2491
2634
  return output;
2492
2635
  }
2493
2636
  async executeWithTimeout(promise, timeoutMs, stepName) {
2494
- if (timeoutMs <= 0) {
2495
- return promise;
2496
- }
2497
- let timeoutId;
2498
- const timeoutPromise = new Promise((_, reject) => {
2499
- timeoutId = setTimeout(() => {
2500
- reject(new StepTimeoutError(stepName, timeoutMs));
2501
- }, timeoutMs);
2637
+ let interrupt;
2638
+ const interrupted = new Promise((_, reject) => {
2639
+ interrupt = reject;
2502
2640
  });
2641
+ let timeout;
2642
+ if (timeoutMs > 0 && Number.isFinite(timeoutMs)) {
2643
+ timeout = setLongTimeout(() => {
2644
+ interrupt(new StepTimeoutError(stepName, timeoutMs));
2645
+ }, timeoutMs);
2646
+ }
2647
+ const onAbort = () => {
2648
+ if (this.isRaceCancelled()) {
2649
+ interrupt(new EvictedError());
2650
+ }
2651
+ };
2652
+ this.abortSignal.addEventListener("abort", onAbort, { once: true });
2503
2653
  try {
2504
- return await Promise.race([promise, timeoutPromise]);
2654
+ return await Promise.race([promise, interrupted]);
2505
2655
  } finally {
2506
- if (timeoutId !== void 0) {
2507
- clearTimeout(timeoutId);
2508
- }
2656
+ timeout == null ? void 0 : timeout.abort();
2657
+ this.abortSignal.removeEventListener("abort", onAbort);
2509
2658
  }
2510
2659
  }
2511
2660
  // === Loop ===
@@ -3377,13 +3526,13 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
3377
3526
  }
3378
3527
  const raceData = entry.kind.data;
3379
3528
  const raceAbortController = new AbortController();
3380
- const branchPromises = [];
3529
+ const runningBranches = /* @__PURE__ */ new Set();
3530
+ const yieldedBranches = /* @__PURE__ */ new Map();
3381
3531
  let winnerName = null;
3382
3532
  let winnerValue;
3383
3533
  let hasWinner = false;
3384
3534
  const errors = {};
3385
3535
  const lateErrors = [];
3386
- let schedulerYieldState;
3387
3536
  let propagatedError;
3388
3537
  for (const branch of branches) {
3389
3538
  const branchStatus = raceData.branches[branch.name];
@@ -3425,91 +3574,146 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
3425
3574
  this.markSettledHistoryVisited(branchLocation);
3426
3575
  continue;
3427
3576
  }
3428
- const branchCtx = this.createBranch(
3429
- branchLocation,
3430
- raceAbortController
3431
- );
3432
3577
  branchStatus.status = "running";
3433
3578
  branchStatus.error = void 0;
3434
3579
  entry.dirty = true;
3435
3580
  const runBranch = async () => {
3581
+ const branchCtx = this.createBranch(
3582
+ branchLocation,
3583
+ raceAbortController
3584
+ );
3436
3585
  const output = await branch.run(branchCtx);
3437
3586
  branchCtx.validateComplete();
3438
3587
  return output;
3439
3588
  };
3440
- const branchPromise = runBranch().then(
3441
- async (output) => {
3442
- if (hasWinner) {
3443
- branchStatus.status = "completed";
3444
- branchStatus.output = output;
3445
- branchStatus.error = void 0;
3446
- entry.dirty = true;
3447
- return;
3448
- }
3449
- if (propagatedError) {
3589
+ const startBranch = () => {
3590
+ const branchPromise = runBranch().then(
3591
+ async (output) => {
3592
+ if (hasWinner) {
3593
+ branchStatus.status = "completed";
3594
+ branchStatus.output = output;
3595
+ branchStatus.error = void 0;
3596
+ entry.dirty = true;
3597
+ return;
3598
+ }
3599
+ if (propagatedError) {
3600
+ branchStatus.status = "completed";
3601
+ branchStatus.output = output;
3602
+ branchStatus.error = void 0;
3603
+ entry.dirty = true;
3604
+ return;
3605
+ }
3606
+ hasWinner = true;
3607
+ winnerName = branch.name;
3608
+ winnerValue = output;
3450
3609
  branchStatus.status = "completed";
3451
3610
  branchStatus.output = output;
3452
3611
  branchStatus.error = void 0;
3612
+ raceData.winner = branch.name;
3453
3613
  entry.dirty = true;
3454
- return;
3455
- }
3456
- hasWinner = true;
3457
- winnerName = branch.name;
3458
- winnerValue = output;
3459
- branchStatus.status = "completed";
3460
- branchStatus.output = output;
3461
- branchStatus.error = void 0;
3462
- raceData.winner = branch.name;
3463
- entry.dirty = true;
3464
- raceAbortController.abort();
3465
- },
3466
- (error) => {
3467
- if (hasWinner) {
3468
- if (error instanceof CancelledError || error instanceof EvictedError) {
3614
+ raceAbortController.abort(new CancelledError());
3615
+ },
3616
+ (error) => {
3617
+ if (hasWinner) {
3618
+ if (error instanceof CancelledError || error instanceof EvictedError || error instanceof SleepError || error instanceof MessageWaitError) {
3619
+ branchStatus.status = "cancelled";
3620
+ } else {
3621
+ lateErrors.push({
3622
+ name: branch.name,
3623
+ error: String(error)
3624
+ });
3625
+ }
3626
+ entry.dirty = true;
3627
+ return;
3628
+ }
3629
+ if (error instanceof SleepError || error instanceof MessageWaitError || error instanceof StepFailedError) {
3630
+ yieldedBranches.set(branch.name, {
3631
+ error,
3632
+ start: startBranch
3633
+ });
3634
+ branchStatus.status = "running";
3635
+ branchStatus.error = void 0;
3636
+ entry.dirty = true;
3637
+ return;
3638
+ }
3639
+ if (error instanceof EvictedError || error instanceof HistoryDivergedError || error instanceof EntryInProgressError || error instanceof RollbackCheckpointError || error instanceof RollbackStopError) {
3640
+ propagatedError = selectControlFlowError(
3641
+ propagatedError,
3642
+ error
3643
+ );
3644
+ branchStatus.status = "running";
3645
+ branchStatus.error = void 0;
3646
+ entry.dirty = true;
3647
+ return;
3648
+ }
3649
+ if (error instanceof CancelledError) {
3469
3650
  branchStatus.status = "cancelled";
3470
3651
  } else {
3471
- lateErrors.push({
3472
- name: branch.name,
3473
- error: String(error)
3474
- });
3652
+ branchStatus.status = "failed";
3653
+ branchStatus.output = void 0;
3654
+ branchStatus.error = String(error);
3655
+ errors[branch.name] = error;
3475
3656
  }
3476
3657
  entry.dirty = true;
3477
- return;
3478
3658
  }
3479
- if (error instanceof SleepError || error instanceof MessageWaitError || error instanceof StepFailedError) {
3480
- schedulerYieldState = mergeSchedulerYield(
3481
- schedulerYieldState,
3482
- error
3483
- );
3484
- branchStatus.status = "running";
3485
- branchStatus.error = void 0;
3486
- entry.dirty = true;
3487
- return;
3659
+ ).finally(() => {
3660
+ runningBranches.delete(branchPromise);
3661
+ });
3662
+ runningBranches.add(branchPromise);
3663
+ };
3664
+ startBranch();
3665
+ }
3666
+ const parentSignal = this.abortSignal;
3667
+ const forwardCancellation = () => {
3668
+ if (parentSignal.reason instanceof CancelledError) {
3669
+ raceAbortController.abort(parentSignal.reason);
3670
+ }
3671
+ };
3672
+ forwardCancellation();
3673
+ parentSignal.addEventListener("abort", forwardCancellation, {
3674
+ once: true
3675
+ });
3676
+ let scheduledWakeAt;
3677
+ try {
3678
+ while (runningBranches.size > 0) {
3679
+ const canWake = !propagatedError && !raceAbortController.signal.aborted && !this.evictionSignal.aborted;
3680
+ if (canWake) {
3681
+ const now = Date.now();
3682
+ for (const [branchName, yielded] of yieldedBranches) {
3683
+ if ((yieldedDeadline(yielded) ?? Infinity) <= now) {
3684
+ yieldedBranches.delete(branchName);
3685
+ yielded.start();
3686
+ }
3488
3687
  }
3489
- if (error instanceof EvictedError || error instanceof HistoryDivergedError || error instanceof EntryInProgressError || error instanceof RollbackCheckpointError || error instanceof RollbackStopError) {
3688
+ }
3689
+ const wakeAt = canWake ? earliestYieldedDeadline(yieldedBranches) : void 0;
3690
+ if (wakeAt === void 0) {
3691
+ await Promise.race(runningBranches);
3692
+ continue;
3693
+ }
3694
+ if (wakeAt !== scheduledWakeAt) {
3695
+ scheduledWakeAt = wakeAt;
3696
+ try {
3697
+ await this.driver.setAlarm(this.workflowId, wakeAt);
3698
+ } catch (error) {
3490
3699
  propagatedError = selectControlFlowError(
3491
3700
  propagatedError,
3492
3701
  error
3493
3702
  );
3494
- branchStatus.status = "running";
3495
- branchStatus.error = void 0;
3496
- entry.dirty = true;
3497
- return;
3498
- }
3499
- if (error instanceof CancelledError) {
3500
- branchStatus.status = "cancelled";
3501
- } else {
3502
- branchStatus.status = "failed";
3503
- branchStatus.output = void 0;
3504
- branchStatus.error = String(error);
3505
- errors[branch.name] = error;
3506
3703
  }
3507
- entry.dirty = true;
3704
+ continue;
3508
3705
  }
3706
+ await this.waitForRaceWake(wakeAt, runningBranches);
3707
+ }
3708
+ } finally {
3709
+ parentSignal.removeEventListener("abort", forwardCancellation);
3710
+ }
3711
+ if (!hasWinner && raceAbortController.signal.aborted) {
3712
+ propagatedError = selectControlFlowError(
3713
+ propagatedError,
3714
+ new EvictedError()
3509
3715
  );
3510
- branchPromises.push(branchPromise);
3511
3716
  }
3512
- await Promise.allSettled(branchPromises);
3513
3717
  if (propagatedError) {
3514
3718
  await this.flushStorage();
3515
3719
  throw propagatedError;
@@ -3518,6 +3722,13 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
3518
3722
  (branch) => branch.status === "pending" || branch.status === "running"
3519
3723
  )) {
3520
3724
  await this.flushStorage();
3725
+ let schedulerYieldState;
3726
+ for (const { error } of yieldedBranches.values()) {
3727
+ schedulerYieldState = mergeSchedulerYield(
3728
+ schedulerYieldState,
3729
+ error
3730
+ );
3731
+ }
3521
3732
  if (!schedulerYieldState) {
3522
3733
  throw new Error(
3523
3734
  `Race "${name}" has pending branches without a scheduler yield`
@@ -3525,24 +3736,30 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
3525
3736
  }
3526
3737
  throw buildSchedulerYieldError(schedulerYieldState);
3527
3738
  }
3739
+ let loserDeletions;
3528
3740
  if (hasWinner && winnerName !== null) {
3741
+ loserDeletions = { prefixes: [], keys: [], ranges: [] };
3529
3742
  for (const branch of branches) {
3530
3743
  if (branch.name !== winnerName) {
3744
+ if (yieldedBranches.has(branch.name)) {
3745
+ raceData.branches[branch.name].status = "cancelled";
3746
+ entry.dirty = true;
3747
+ }
3531
3748
  const branchLocation = appendName(
3532
3749
  this.storage,
3533
3750
  location,
3534
3751
  branch.name
3535
3752
  );
3536
- await deleteEntriesWithPrefix(
3753
+ const deletions = takeEntriesWithPrefix(
3537
3754
  this.storage,
3538
- this.driver,
3539
- branchLocation,
3540
- this.historyNotifier
3755
+ branchLocation
3541
3756
  );
3757
+ loserDeletions.prefixes.push(...deletions.prefixes);
3758
+ loserDeletions.keys.push(...deletions.keys);
3542
3759
  }
3543
3760
  }
3544
3761
  }
3545
- await this.flushStorage();
3762
+ await this.flushStorageWithDeletions(loserDeletions);
3546
3763
  if (lateErrors.length > 0) {
3547
3764
  console.warn(
3548
3765
  `Race "${name}" had ${lateErrors.length} branch(es) fail after winner was determined:`,
@@ -3661,30 +3878,6 @@ var WorkflowContextImpl = class _WorkflowContextImpl {
3661
3878
  }
3662
3879
  };
3663
3880
 
3664
- // src/utils.ts
3665
- function sleep(ms) {
3666
- return new Promise((resolve) => setTimeout(resolve, ms));
3667
- }
3668
- var TIMEOUT_MAX = 2147483647;
3669
- function setLongTimeout(listener, after) {
3670
- let timeout;
3671
- function start(remaining) {
3672
- if (remaining <= TIMEOUT_MAX) {
3673
- timeout = setTimeout(listener, remaining);
3674
- } else {
3675
- timeout = setTimeout(() => {
3676
- start(remaining - TIMEOUT_MAX);
3677
- }, TIMEOUT_MAX);
3678
- }
3679
- }
3680
- start(after);
3681
- return {
3682
- abort: () => {
3683
- if (timeout !== void 0) clearTimeout(timeout);
3684
- }
3685
- };
3686
- }
3687
-
3688
3881
  // src/index.ts
3689
3882
  var Loop = {
3690
3883
  continue: (state) => ({
@@ -4434,15 +4627,15 @@ export {
4434
4627
  deleteEntriesWithPrefix,
4435
4628
  getEntry,
4436
4629
  setEntry,
4630
+ sleep,
4437
4631
  DEFAULT_MAX_RETRIES,
4438
4632
  DEFAULT_RETRY_BACKOFF_BASE,
4439
4633
  DEFAULT_RETRY_BACKOFF_MAX,
4440
4634
  DEFAULT_LOOP_HISTORY_PRUNE_INTERVAL,
4441
4635
  DEFAULT_STEP_TIMEOUT,
4442
4636
  WorkflowContextImpl,
4443
- sleep,
4444
4637
  Loop,
4445
4638
  runWorkflow,
4446
4639
  replayWorkflowFromStep
4447
4640
  };
4448
- //# sourceMappingURL=chunk-JMOI2OHA.js.map
4641
+ //# sourceMappingURL=chunk-NIKZ2NOQ.js.map