@nagi-js/core 0.1.1-rc.23 → 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
  };
@@ -649,8 +654,7 @@ var stepKinds = {
649
654
  event: (fact) => ({
650
655
  type: "step.completed",
651
656
  stepId: fact.stepId,
652
- attempt: fact.attempt,
653
- output: fact.output
657
+ attempt: fact.attempt
654
658
  })
655
659
  },
656
660
  "step.failed": {
@@ -669,16 +673,11 @@ var stepKinds = {
669
673
  }),
670
674
  release: (fact) => releaseStep(fact.stepId, false),
671
675
  // Only written on terminal failure (retries use step.retried).
672
- stream: (fact) => ({
673
- tag: "close-error",
674
- stepId: fact.stepId,
675
- error: fact.error
676
- }),
676
+ stream: (fact) => ({ tag: "close-error", stepId: fact.stepId }),
677
677
  event: (fact) => ({
678
678
  type: "step.failed",
679
679
  stepId: fact.stepId,
680
- attempt: fact.attempt,
681
- error: fact.error
680
+ attempt: fact.attempt
682
681
  })
683
682
  },
684
683
  "step.canceled": {
@@ -696,8 +695,12 @@ var stepKinds = {
696
695
  completedAt: fact.at
697
696
  }),
698
697
  release: (fact) => releaseStep(fact.stepId, false),
699
- stream: null,
700
- 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
+ })
701
704
  },
702
705
  "step.retried": {
703
706
  fold: (draft, fact) => foldStep(
@@ -717,7 +720,13 @@ var stepKinds = {
717
720
  attempt: fact.attempt,
718
721
  error: fact.error
719
722
  }),
720
- 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
+ }),
721
730
  stream: (fact) => ({
722
731
  tag: "retry",
723
732
  stepId: fact.stepId,
@@ -761,8 +770,9 @@ var stepKinds = {
761
770
  },
762
771
  rows: (fact) => ({ row: "step", status: "reset", stepId: fact.stepId }),
763
772
  release: (fact) => releaseStep(fact.stepId, true),
764
- stream: null,
765
- 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 })
766
776
  },
767
777
  "step.abort-requested": {
768
778
  fold: (draft, fact) => foldStep(
@@ -1224,17 +1234,33 @@ function synthesizeReplayFlow(dag, liveFlow) {
1224
1234
  for (const canonStep of dag.steps) {
1225
1235
  const shell = synthesized[canonStep.id];
1226
1236
  if (shell === void 0) continue;
1227
- const synthesizedNeeds = {};
1228
- for (const upstreamId of canonStep.needs) {
1229
- 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];
1230
1246
  if (upstreamShell === void 0) {
1231
1247
  throw new NagiRuntimeError(
1232
- `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.`
1233
1249
  );
1234
1250
  }
1235
- synthesizedNeeds[upstreamId] = upstreamShell;
1251
+ needs[alias] = { step: upstreamShell, optional: ref.optional };
1252
+ }
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
+ );
1236
1262
  }
1237
- setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
1263
+ setDef(shell, { ...getDef(shell), needs });
1238
1264
  }
1239
1265
  return {
1240
1266
  id: liveFlow.id,
@@ -1267,7 +1293,13 @@ function decideSignal(args) {
1267
1293
  if (isStepTerminal(step)) return NOOP;
1268
1294
  if (step.tag === "awaitingSignal") {
1269
1295
  const source = incoming ?? runState.bufferedSignals[stepId];
1270
- 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
+ }
1271
1303
  const { attempt } = step;
1272
1304
  return {
1273
1305
  kind: "deliver",
@@ -1443,8 +1475,10 @@ function supersede(args) {
1443
1475
  }
1444
1476
 
1445
1477
  // src/stream-hub.ts
1446
- function isStreamOver(state, stepId) {
1447
- 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";
1448
1482
  }
1449
1483
  var STREAM_SUBSCRIBER_BUFFER_CAP = 256;
1450
1484
  var STREAM_REPLAY_BUFFER_CAP = 256;
@@ -1519,11 +1553,12 @@ var InMemoryStreamHub = class _InMemoryStreamHub {
1519
1553
  static key(runId, stepId) {
1520
1554
  return `${runId}::${stepId}`;
1521
1555
  }
1522
- openChannel(key) {
1556
+ openChannel(runId, stepId) {
1557
+ const key = _InMemoryStreamHub.key(runId, stepId);
1523
1558
  if (this.closedKeys.has(key)) return void 0;
1524
1559
  let channel = this.channels.get(key);
1525
1560
  if (channel === void 0) {
1526
- channel = { subscribers: /* @__PURE__ */ new Set(), replay: [] };
1561
+ channel = { runId, stepId, subscribers: /* @__PURE__ */ new Set(), replay: [] };
1527
1562
  this.channels.set(key, channel);
1528
1563
  }
1529
1564
  return channel;
@@ -1544,7 +1579,7 @@ var InMemoryStreamHub = class _InMemoryStreamHub {
1544
1579
  return subs;
1545
1580
  }
1546
1581
  publishChunk(runId, stepId, chunk) {
1547
- const channel = this.openChannel(_InMemoryStreamHub.key(runId, stepId));
1582
+ const channel = this.openChannel(runId, stepId);
1548
1583
  if (channel === void 0) return;
1549
1584
  const event = { kind: "chunk", chunk };
1550
1585
  channel.replay.push(event);
@@ -1566,39 +1601,56 @@ var InMemoryStreamHub = class _InMemoryStreamHub {
1566
1601
  const subs = this.closeChannel(_InMemoryStreamHub.key(runId, stepId));
1567
1602
  for (const sub of subs ?? []) sub.close();
1568
1603
  }
1569
- closeError(runId, stepId, error) {
1604
+ closeError(runId, stepId) {
1570
1605
  const subs = this.closeChannel(_InMemoryStreamHub.key(runId, stepId));
1571
- const event = { kind: "error", error };
1606
+ const event = { kind: "error" };
1572
1607
  for (const sub of subs ?? []) {
1573
1608
  sub.push(event);
1574
1609
  sub.close();
1575
1610
  }
1576
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
+ }
1577
1620
  apply(runId, effect) {
1578
1621
  switch (effect.tag) {
1579
1622
  case "close-ok":
1580
1623
  this.closeOk(runId, effect.stepId);
1581
1624
  return;
1582
1625
  case "close-error":
1583
- this.closeError(runId, effect.stepId, effect.error);
1626
+ this.closeError(runId, effect.stepId);
1584
1627
  return;
1585
1628
  case "retry":
1586
1629
  this.signalRetry(runId, effect.stepId, effect.nextAttempt);
1587
1630
  return;
1631
+ case "reopen":
1632
+ this.reopen(runId, effect.stepId);
1633
+ return;
1588
1634
  case "close-run":
1589
1635
  this.closeRun(runId);
1590
1636
  return;
1591
1637
  }
1592
1638
  }
1593
1639
  closeRun(runId) {
1594
- const prefix = `${runId}::`;
1595
- for (const key of this.channels.keys()) {
1596
- 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) {
1597
1642
  for (const sub of this.closeChannel(key) ?? []) sub.close();
1598
1643
  }
1599
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
+ }
1600
1652
  subscribeStream(runId, stepId, opts) {
1601
- const channel = this.openChannel(_InMemoryStreamHub.key(runId, stepId));
1653
+ const channel = this.openChannel(runId, stepId);
1602
1654
  if (channel === void 0) return EMPTY_CLOSED_STREAM;
1603
1655
  const sub = new Subscriber();
1604
1656
  if (opts?.replayBuffered === true) {
@@ -1850,7 +1902,7 @@ var InMemoryStore = class {
1850
1902
  }
1851
1903
  }
1852
1904
  }
1853
- async tryStartRun(runId, fact, concurrency) {
1905
+ async tryStartRun(runId, fact, concurrency, seed) {
1854
1906
  if (this.runRows.has(runId)) {
1855
1907
  return { started: false, canceled: [] };
1856
1908
  }
@@ -1870,6 +1922,11 @@ var InMemoryStore = class {
1870
1922
  this.slotByRun.set(runId, slot);
1871
1923
  }
1872
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
+ }
1873
1930
  return { started: true, canceled };
1874
1931
  }
1875
1932
  // No real tx to join: every write here is visible, and announced, the moment
@@ -1894,7 +1951,7 @@ var InMemoryStore = class {
1894
1951
  ([, row]) => row.parent?.stepId === parentStepId && (row.status === "pending" || row.status === "running")
1895
1952
  );
1896
1953
  }
1897
- async loadRunState(runId) {
1954
+ async loadRunState(runId, _tx) {
1898
1955
  return foldRun(runId, this.facts.get(runId) ?? []);
1899
1956
  }
1900
1957
  async claimStep(runId, stepId, attempt) {
@@ -1979,6 +2036,9 @@ var InMemoryStore = class {
1979
2036
  this.writeFact(runId, decision.received);
1980
2037
  this.writeFact(runId, decision.completed);
1981
2038
  return decision.result;
2039
+ case "park":
2040
+ this.release(runId, decision.release);
2041
+ return decision.result;
1982
2042
  }
1983
2043
  }
1984
2044
  async upsertTimer(runId, stepId, fireAt) {
@@ -2120,7 +2180,7 @@ var InMemoryStore = class {
2120
2180
  };
2121
2181
  stream = {
2122
2182
  subscribeStream: (runId, stepId, opts) => {
2123
- if (isStreamOver(foldRun(runId, this.facts.get(runId) ?? []), stepId)) {
2183
+ if (streamEndOf(foldRun(runId, this.facts.get(runId) ?? []), stepId) !== "open") {
2124
2184
  return EMPTY_CLOSED_STREAM2;
2125
2185
  }
2126
2186
  return this.streamHub.subscribeStream(runId, stepId, opts);
@@ -2239,6 +2299,6 @@ var InMemoryClock = class {
2239
2299
  }
2240
2300
  };
2241
2301
 
2242
- 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 };
2243
- //# sourceMappingURL=chunk-DPTPJZEG.js.map
2244
- //# sourceMappingURL=chunk-DPTPJZEG.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