@nagi-js/core 0.1.1-rc.22 → 0.1.1-rc.24

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.
@@ -397,7 +397,7 @@ var flowKinds = {
397
397
  // Closes every still-open channel of the run, so a subscriber to a skipped
398
398
  // or never-emitting step never hangs.
399
399
  stream: () => CLOSE_RUN,
400
- event: (fact) => ({ type: "flow.completed", output: fact.output })
400
+ event: () => ({ type: "flow.completed" })
401
401
  },
402
402
  "flow.failed": {
403
403
  fold: (draft, fact) => {
@@ -411,7 +411,7 @@ var flowKinds = {
411
411
  }),
412
412
  release: () => RELEASE_RUN,
413
413
  stream: () => CLOSE_RUN,
414
- event: (fact) => ({ type: "flow.failed", error: fact.error })
414
+ event: () => ({ type: "flow.failed" })
415
415
  },
416
416
  "flow.canceled": {
417
417
  fold: (draft, fact) => {
@@ -460,7 +460,12 @@ var leaseKinds = {
460
460
  stepId: fact.stepId,
461
461
  attempt: fact.attempt
462
462
  }),
463
- stream: null,
463
+ // Subscribers are told the reaped attempt is superseded, same as a normal retry.
464
+ stream: (fact) => ({
465
+ tag: "retry",
466
+ stepId: fact.stepId,
467
+ nextAttempt: fact.attempt + 1
468
+ }),
464
469
  event: null
465
470
  }
466
471
  };
@@ -605,6 +610,9 @@ function releaseStep(stepId, timer) {
605
610
  function inFlight(prev, attempt) {
606
611
  return (prev.tag === "running" || prev.tag === "awaitingSignal" || prev.tag === "awaitingChild" || prev.tag === "aborting") && prev.attempt === attempt;
607
612
  }
613
+ function settles(prev, attempt) {
614
+ return !isStepTerminal(prev) && attempt <= attemptOf(prev);
615
+ }
608
616
  var stepKinds = {
609
617
  "step.started": {
610
618
  fold: (draft, fact) => foldStep(
@@ -631,7 +639,7 @@ var stepKinds = {
631
639
  fold: (draft, fact) => foldStep(
632
640
  draft,
633
641
  fact.stepId,
634
- (prev) => isStepTerminal(prev) ? prev : { tag: "completed", attempt: fact.attempt, output: fact.output }
642
+ (prev) => settles(prev, fact.attempt) ? { tag: "completed", attempt: fact.attempt, output: fact.output } : prev
635
643
  ),
636
644
  rows: (fact) => ({
637
645
  row: "step",
@@ -646,15 +654,14 @@ var stepKinds = {
646
654
  event: (fact) => ({
647
655
  type: "step.completed",
648
656
  stepId: fact.stepId,
649
- attempt: fact.attempt,
650
- output: fact.output
657
+ attempt: fact.attempt
651
658
  })
652
659
  },
653
660
  "step.failed": {
654
661
  fold: (draft, fact) => foldStep(
655
662
  draft,
656
663
  fact.stepId,
657
- (prev) => isStepTerminal(prev) ? prev : { tag: "failed", attempt: fact.attempt, error: fact.error }
664
+ (prev) => settles(prev, fact.attempt) ? { tag: "failed", attempt: fact.attempt, error: fact.error } : prev
658
665
  ),
659
666
  rows: (fact) => ({
660
667
  row: "step",
@@ -666,21 +673,16 @@ var stepKinds = {
666
673
  }),
667
674
  release: (fact) => releaseStep(fact.stepId, false),
668
675
  // Only written on terminal failure (retries use step.retried).
669
- stream: (fact) => ({
670
- tag: "close-error",
671
- stepId: fact.stepId,
672
- error: fact.error
673
- }),
676
+ stream: (fact) => ({ tag: "close-error", stepId: fact.stepId }),
674
677
  event: (fact) => ({
675
678
  type: "step.failed",
676
679
  stepId: fact.stepId,
677
- attempt: fact.attempt,
678
- error: fact.error
680
+ attempt: fact.attempt
679
681
  })
680
682
  },
681
683
  "step.canceled": {
682
684
  fold: (draft, fact) => foldStep(draft, fact.stepId, (prev) => {
683
- if (isStepTerminal(prev)) return prev;
685
+ if (!settles(prev, fact.attempt)) return prev;
684
686
  const cause = prev.tag === "aborting" ? { kind: "aborted", ...compact({ error: fact.error }) } : { kind: "run-canceled" };
685
687
  return { tag: "canceled", cause };
686
688
  }),
@@ -693,8 +695,12 @@ var stepKinds = {
693
695
  completedAt: fact.at
694
696
  }),
695
697
  release: (fact) => releaseStep(fact.stepId, false),
696
- stream: null,
697
- event: null
698
+ stream: (fact) => ({ tag: "close-ok", stepId: fact.stepId }),
699
+ event: (fact) => ({
700
+ type: "step.canceled",
701
+ stepId: fact.stepId,
702
+ attempt: fact.attempt
703
+ })
698
704
  },
699
705
  "step.retried": {
700
706
  fold: (draft, fact) => foldStep(
@@ -714,7 +720,13 @@ var stepKinds = {
714
720
  attempt: fact.attempt,
715
721
  error: fact.error
716
722
  }),
717
- release: null,
723
+ // The failed attempt is over; a lingering lease would be reaped mid-backoff
724
+ // and re-dispatch the retry early.
725
+ release: (fact) => ({
726
+ tag: "release-lease",
727
+ stepId: fact.stepId,
728
+ attempt: fact.attempt
729
+ }),
718
730
  stream: (fact) => ({
719
731
  tag: "retry",
720
732
  stepId: fact.stepId,
@@ -758,8 +770,9 @@ var stepKinds = {
758
770
  },
759
771
  rows: (fact) => ({ row: "step", status: "reset", stepId: fact.stepId }),
760
772
  release: (fact) => releaseStep(fact.stepId, true),
761
- stream: null,
762
- event: null
773
+ stream: (fact) => ({ tag: "reopen", stepId: fact.stepId }),
774
+ // On a completed/failed run this is the reopen.
775
+ event: (fact) => ({ type: "step.reset", stepId: fact.stepId })
763
776
  },
764
777
  "step.abort-requested": {
765
778
  fold: (draft, fact) => foldStep(
@@ -1221,17 +1234,33 @@ function synthesizeReplayFlow(dag, liveFlow) {
1221
1234
  for (const canonStep of dag.steps) {
1222
1235
  const shell = synthesized[canonStep.id];
1223
1236
  if (shell === void 0) continue;
1224
- const synthesizedNeeds = {};
1225
- for (const upstreamId of canonStep.needs) {
1226
- const upstreamShell = synthesized[upstreamId];
1237
+ const liveDef = getDef(liveSteps[canonStep.id]);
1238
+ if (liveDef.kind !== canonStep.kind) {
1239
+ throw new NagiRuntimeError(
1240
+ `Drift-allowed replay: step "${canonStep.id}" is a ${canonStep.kind} in the snapshot but a ${liveDef.kind} live.`
1241
+ );
1242
+ }
1243
+ const needs = {};
1244
+ for (const [alias, ref] of Object.entries(liveDef.needs)) {
1245
+ const upstreamShell = synthesized[ref.step.id];
1227
1246
  if (upstreamShell === void 0) {
1228
1247
  throw new NagiRuntimeError(
1229
- `Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
1248
+ `Drift-allowed replay: step "${canonStep.id}" needs upstream "${ref.step.id}" which the snapshot does not declare.`
1230
1249
  );
1231
1250
  }
1232
- synthesizedNeeds[upstreamId] = upstreamShell;
1251
+ needs[alias] = { step: upstreamShell, optional: ref.optional };
1233
1252
  }
1234
- setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
1253
+ const liveNeedIds = new Set(
1254
+ Object.values(liveDef.needs).map((ref) => ref.step.id)
1255
+ );
1256
+ const canonNeedIds = new Set(canonStep.needs);
1257
+ const sameNeeds = liveNeedIds.size === canonNeedIds.size && [...liveNeedIds].every((id) => canonNeedIds.has(id));
1258
+ if (!sameNeeds) {
1259
+ throw new NagiRuntimeError(
1260
+ `Drift-allowed replay: step "${canonStep.id}" needs [${[...canonNeedIds].sort().join(", ")}] in the snapshot but [${[...liveNeedIds].sort().join(", ")}] live.`
1261
+ );
1262
+ }
1263
+ setDef(shell, { ...getDef(shell), needs });
1235
1264
  }
1236
1265
  return {
1237
1266
  id: liveFlow.id,
@@ -1264,7 +1293,13 @@ function decideSignal(args) {
1264
1293
  if (isStepTerminal(step)) return NOOP;
1265
1294
  if (step.tag === "awaitingSignal") {
1266
1295
  const source = incoming ?? runState.bufferedSignals[stepId];
1267
- if (source === void 0) return NOOP;
1296
+ if (source === void 0) {
1297
+ return {
1298
+ kind: "park",
1299
+ release: { tag: "release-step", stepId, timer: false },
1300
+ result: { tag: "noop" }
1301
+ };
1302
+ }
1268
1303
  const { attempt } = step;
1269
1304
  return {
1270
1305
  kind: "deliver",
@@ -1440,8 +1475,10 @@ function supersede(args) {
1440
1475
  }
1441
1476
 
1442
1477
  // src/stream-hub.ts
1443
- function isStreamOver(state, stepId) {
1444
- return isTerminalRun(state) || isStepTerminal(stepStateOf(state, stepId));
1478
+ function streamEndOf(state, stepId) {
1479
+ const step = stepStateOf(state, stepId);
1480
+ if (step.tag === "failed") return "error";
1481
+ return isTerminalRun(state) || isStepTerminal(step) ? "ok" : "open";
1445
1482
  }
1446
1483
  var STREAM_SUBSCRIBER_BUFFER_CAP = 256;
1447
1484
  var STREAM_REPLAY_BUFFER_CAP = 256;
@@ -1516,11 +1553,12 @@ var InMemoryStreamHub = class _InMemoryStreamHub {
1516
1553
  static key(runId, stepId) {
1517
1554
  return `${runId}::${stepId}`;
1518
1555
  }
1519
- openChannel(key) {
1556
+ openChannel(runId, stepId) {
1557
+ const key = _InMemoryStreamHub.key(runId, stepId);
1520
1558
  if (this.closedKeys.has(key)) return void 0;
1521
1559
  let channel = this.channels.get(key);
1522
1560
  if (channel === void 0) {
1523
- channel = { subscribers: /* @__PURE__ */ new Set(), replay: [] };
1561
+ channel = { runId, stepId, subscribers: /* @__PURE__ */ new Set(), replay: [] };
1524
1562
  this.channels.set(key, channel);
1525
1563
  }
1526
1564
  return channel;
@@ -1541,7 +1579,7 @@ var InMemoryStreamHub = class _InMemoryStreamHub {
1541
1579
  return subs;
1542
1580
  }
1543
1581
  publishChunk(runId, stepId, chunk) {
1544
- const channel = this.openChannel(_InMemoryStreamHub.key(runId, stepId));
1582
+ const channel = this.openChannel(runId, stepId);
1545
1583
  if (channel === void 0) return;
1546
1584
  const event = { kind: "chunk", chunk };
1547
1585
  channel.replay.push(event);
@@ -1563,39 +1601,56 @@ var InMemoryStreamHub = class _InMemoryStreamHub {
1563
1601
  const subs = this.closeChannel(_InMemoryStreamHub.key(runId, stepId));
1564
1602
  for (const sub of subs ?? []) sub.close();
1565
1603
  }
1566
- closeError(runId, stepId, error) {
1604
+ closeError(runId, stepId) {
1567
1605
  const subs = this.closeChannel(_InMemoryStreamHub.key(runId, stepId));
1568
- const event = { kind: "error", error };
1606
+ const event = { kind: "error" };
1569
1607
  for (const sub of subs ?? []) {
1570
1608
  sub.push(event);
1571
1609
  sub.close();
1572
1610
  }
1573
1611
  }
1612
+ // A reset step runs again: forget that it closed, and drop the superseded
1613
+ // run's buffered chunks from any channel still open.
1614
+ reopen(runId, stepId) {
1615
+ const key = _InMemoryStreamHub.key(runId, stepId);
1616
+ this.closedKeys.delete(key);
1617
+ const channel = this.channels.get(key);
1618
+ if (channel !== void 0) channel.replay.length = 0;
1619
+ }
1574
1620
  apply(runId, effect) {
1575
1621
  switch (effect.tag) {
1576
1622
  case "close-ok":
1577
1623
  this.closeOk(runId, effect.stepId);
1578
1624
  return;
1579
1625
  case "close-error":
1580
- this.closeError(runId, effect.stepId, effect.error);
1626
+ this.closeError(runId, effect.stepId);
1581
1627
  return;
1582
1628
  case "retry":
1583
1629
  this.signalRetry(runId, effect.stepId, effect.nextAttempt);
1584
1630
  return;
1631
+ case "reopen":
1632
+ this.reopen(runId, effect.stepId);
1633
+ return;
1585
1634
  case "close-run":
1586
1635
  this.closeRun(runId);
1587
1636
  return;
1588
1637
  }
1589
1638
  }
1590
1639
  closeRun(runId) {
1591
- const prefix = `${runId}::`;
1592
- for (const key of this.channels.keys()) {
1593
- if (!key.startsWith(prefix)) continue;
1640
+ const keys = [...this.channels.entries()].filter(([, channel]) => channel.runId === runId).map(([key]) => key);
1641
+ for (const key of keys) {
1594
1642
  for (const sub of this.closeChannel(key) ?? []) sub.close();
1595
1643
  }
1596
1644
  }
1645
+ // Open channels only — the ones a lost close frame could leave hanging.
1646
+ openStreams() {
1647
+ return [...this.channels.values()].map(({ runId, stepId }) => ({
1648
+ runId,
1649
+ stepId
1650
+ }));
1651
+ }
1597
1652
  subscribeStream(runId, stepId, opts) {
1598
- const channel = this.openChannel(_InMemoryStreamHub.key(runId, stepId));
1653
+ const channel = this.openChannel(runId, stepId);
1599
1654
  if (channel === void 0) return EMPTY_CLOSED_STREAM;
1600
1655
  const sub = new Subscriber();
1601
1656
  if (opts?.replayBuffered === true) {
@@ -1706,11 +1761,16 @@ function nextStepRow(prev, delta) {
1706
1761
  }
1707
1762
  return { ...prev, error: delta.error };
1708
1763
  case "completed":
1709
- return settle(prev, delta.attempt, delta, delta.output, null);
1710
1764
  case "failed":
1711
- return settle(prev, delta.attempt, delta, null, delta.error);
1712
1765
  case "canceled":
1713
- return settle(prev, delta.attempt, delta, null, delta.error);
1766
+ if (prev === void 0 || prev.attempt < delta.attempt) return prev;
1767
+ return settle(
1768
+ prev,
1769
+ delta.attempt,
1770
+ delta,
1771
+ delta.status === "completed" ? delta.output : null,
1772
+ delta.status === "completed" ? null : delta.error
1773
+ );
1714
1774
  case "skipped":
1715
1775
  return settle(
1716
1776
  prev,
@@ -1842,7 +1902,7 @@ var InMemoryStore = class {
1842
1902
  }
1843
1903
  }
1844
1904
  }
1845
- async tryStartRun(runId, fact, concurrency) {
1905
+ async tryStartRun(runId, fact, concurrency, seed) {
1846
1906
  if (this.runRows.has(runId)) {
1847
1907
  return { started: false, canceled: [] };
1848
1908
  }
@@ -1862,6 +1922,11 @@ var InMemoryStore = class {
1862
1922
  this.slotByRun.set(runId, slot);
1863
1923
  }
1864
1924
  this.writeFact(runId, fact);
1925
+ if (seed !== void 0) {
1926
+ for (const stepId of seed.steps) {
1927
+ await seed.queue.enqueue(runId, stepId, { flowId: seed.flowId });
1928
+ }
1929
+ }
1865
1930
  return { started: true, canceled };
1866
1931
  }
1867
1932
  // No real tx to join: every write here is visible, and announced, the moment
@@ -1886,7 +1951,7 @@ var InMemoryStore = class {
1886
1951
  ([, row]) => row.parent?.stepId === parentStepId && (row.status === "pending" || row.status === "running")
1887
1952
  );
1888
1953
  }
1889
- async loadRunState(runId) {
1954
+ async loadRunState(runId, _tx) {
1890
1955
  return foldRun(runId, this.facts.get(runId) ?? []);
1891
1956
  }
1892
1957
  async claimStep(runId, stepId, attempt) {
@@ -1971,6 +2036,9 @@ var InMemoryStore = class {
1971
2036
  this.writeFact(runId, decision.received);
1972
2037
  this.writeFact(runId, decision.completed);
1973
2038
  return decision.result;
2039
+ case "park":
2040
+ this.release(runId, decision.release);
2041
+ return decision.result;
1974
2042
  }
1975
2043
  }
1976
2044
  async upsertTimer(runId, stepId, fireAt) {
@@ -2112,7 +2180,7 @@ var InMemoryStore = class {
2112
2180
  };
2113
2181
  stream = {
2114
2182
  subscribeStream: (runId, stepId, opts) => {
2115
- if (isStreamOver(foldRun(runId, this.facts.get(runId) ?? []), stepId)) {
2183
+ if (streamEndOf(foldRun(runId, this.facts.get(runId) ?? []), stepId) !== "open") {
2116
2184
  return EMPTY_CLOSED_STREAM2;
2117
2185
  }
2118
2186
  return this.streamHub.subscribeStream(runId, stepId, opts);
@@ -2231,6 +2299,6 @@ var InMemoryClock = class {
2231
2299
  }
2232
2300
  };
2233
2301
 
2234
- export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, Facts, InMemoryClock, InMemoryQueue, InMemoryRunEventHub, InMemoryStore, InMemoryStreamHub, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiStepTimeoutError, NagiValidationError, STREAM_REPLAY_BUFFER_CAP, STREAM_SUBSCRIBER_BUFFER_CAP, admitsRunEnd, asStepMapWithDefs, attachDef, attemptOf, compact, decideExpiredLeaseAction, decideSignal, decideTimeout, defaultSnapshotGonePolicy, dequeueBackoff, errorOf, factConsequences, fingerprintFlows, foldRun, getDef, handlerDef, isAbortRequested, isRunEnd, isStepTerminal, isStreamOver, isTerminalRun, isTerminalRunEvent, makeEmit, makeFlowOf, makeSignals, needsStepIds, normalizeNeeds, outputOf, peekDef, pinRun, registerFlows, requireCurrent, resolveNeeds, resolveRetry, resolvedOf, runCancelCause, runStatusOf, selectExpired, selectPruneBatch, serializeError, stepBackoff, stepStateOf, stepStatusOf, supersede, unwrap, validate, validationError };
2235
- //# sourceMappingURL=chunk-PUAV56FC.js.map
2236
- //# sourceMappingURL=chunk-PUAV56FC.js.map
2302
+ export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, Facts, InMemoryClock, InMemoryQueue, InMemoryRunEventHub, InMemoryStore, InMemoryStreamHub, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiStepTimeoutError, NagiValidationError, STREAM_REPLAY_BUFFER_CAP, STREAM_SUBSCRIBER_BUFFER_CAP, admitsRunEnd, asStepMapWithDefs, attachDef, attemptOf, compact, decideExpiredLeaseAction, decideSignal, decideTimeout, defaultSnapshotGonePolicy, dequeueBackoff, errorOf, factConsequences, fingerprintFlows, foldRun, getDef, handlerDef, isAbortRequested, isRunEnd, isStepTerminal, isTerminalRun, isTerminalRunEvent, makeEmit, makeFlowOf, makeSignals, needsStepIds, normalizeNeeds, outputOf, peekDef, pinRun, registerFlows, requireCurrent, resolveNeeds, resolveRetry, resolvedOf, runCancelCause, runStatusOf, selectExpired, selectPruneBatch, serializeError, stepBackoff, stepStateOf, stepStatusOf, streamEndOf, supersede, unwrap, validate, validationError };
2303
+ //# sourceMappingURL=chunk-TXWUVL6W.js.map
2304
+ //# sourceMappingURL=chunk-TXWUVL6W.js.map