@nagi-js/core 0.1.1-rc.23 → 0.1.1-rc.25

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/dist/index.js CHANGED
@@ -1,9 +1,29 @@
1
- import { InMemoryClock, makeEmit, registerFlows, fingerprintFlows, makeFlowOf, makeSignals, compact, validationError, NagiRuntimeError, NagiSnapshotDriftError, requireCurrent, serializeError, NagiSignalTimeoutError, validate, Facts, foldRun, stepStateOf, isStepTerminal, isTerminalRun, dequeueBackoff, defaultSnapshotGonePolicy, DEFAULT_REAPER_INTERVAL_MS, runStatusOf, runCancelCause, asStepMapWithDefs, needsStepIds, getDef, stepStatusOf, handlerDef, resolveRetry, isAbortRequested, resolveNeeds, stepBackoff, NagiCanceledError, NagiStepTimeoutError, peekDef, attachDef, NagiNonRetryableError, pinRun, normalizeNeeds } from './chunk-DPTPJZEG.js';
2
- export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, InMemoryClock, InMemoryQueue, InMemoryRunEventHub, InMemoryStore, InMemoryStreamHub, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiStepTimeoutError, NagiValidationError, STREAM_REPLAY_BUFFER_CAP, STREAM_SUBSCRIBER_BUFFER_CAP, admitsRunEnd, attemptOf, decideExpiredLeaseAction, decideSignal, decideTimeout, defaultSnapshotGonePolicy, errorOf, factConsequences, isRunEnd, isStepTerminal, isStreamOver, isTerminalRun, isTerminalRunEvent, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, selectExpired, selectPruneBatch, stepStateOf, stepStatusOf, supersede, unwrap } from './chunk-DPTPJZEG.js';
1
+ import { InMemoryClock, makeEmit, registerFlows, fingerprintFlows, makeFlowOf, makeSignals, compact, validationError, NagiRuntimeError, NagiSnapshotDriftError, requireCurrent, serializeError, NagiSignalTimeoutError, validate, Facts, foldRun, stepStateOf, dequeueBackoff, defaultSnapshotGonePolicy, DEFAULT_REAPER_INTERVAL_MS, isTerminalRun, runStatusOf, runCancelCause, isStepTerminal, stepStatusOf, asStepMapWithDefs, getDef, handlerDef, resolveRetry, isAbortRequested, needsStepIds, resolveNeeds, stepBackoff, NagiCanceledError, NagiStepTimeoutError, peekDef, attachDef, NagiNonRetryableError, pinRun, normalizeNeeds } from './chunk-TXWUVL6W.js';
2
+ export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, InMemoryClock, InMemoryQueue, InMemoryRunEventHub, InMemoryStore, InMemoryStreamHub, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiStepTimeoutError, NagiValidationError, STREAM_REPLAY_BUFFER_CAP, STREAM_SUBSCRIBER_BUFFER_CAP, admitsRunEnd, attemptOf, decideExpiredLeaseAction, decideSignal, decideTimeout, defaultSnapshotGonePolicy, errorOf, factConsequences, isRunEnd, isStepTerminal, isTerminalRun, isTerminalRunEvent, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, selectExpired, selectPruneBatch, stepStateOf, stepStatusOf, streamEndOf, supersede, unwrap } from './chunk-TXWUVL6W.js';
3
3
 
4
4
  // src/builder.ts
5
+ var MAX_TIMER_MS = 2147483647;
6
+ function assertHandlerTimeout(ms) {
7
+ if (ms === void 0) return;
8
+ if (!Number.isInteger(ms) || ms < 1 || ms > MAX_TIMER_MS) {
9
+ throw validationError(
10
+ `timeoutMs must be an integer between 1 and ${MAX_TIMER_MS} (got ${ms}). Omit it for no deadline.`,
11
+ ["timeoutMs"]
12
+ );
13
+ }
14
+ }
15
+ function assertSignalTimeout(ms) {
16
+ if (ms === "unbounded") return;
17
+ if (!Number.isFinite(ms) || ms < 1) {
18
+ throw validationError(
19
+ `timeoutMs must be "unbounded" or a finite number >= 1 (got ${ms}).`,
20
+ ["timeoutMs"]
21
+ );
22
+ }
23
+ }
5
24
  function makeBuilder() {
6
25
  function handler(kind, config) {
26
+ assertHandlerTimeout(config.timeoutMs);
7
27
  const def = {
8
28
  kind,
9
29
  needs: normalizeNeeds(config.needs),
@@ -21,6 +41,7 @@ function makeBuilder() {
21
41
  return attachDef({ kind, id: "" }, def);
22
42
  }
23
43
  function signal(config) {
44
+ assertSignalTimeout(config.timeoutMs);
24
45
  const def = {
25
46
  kind: "signal",
26
47
  needs: normalizeNeeds(config.needs),
@@ -183,6 +204,13 @@ async function deriveChildRunId(key) {
183
204
  const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
184
205
  return `run-${uuid}`;
185
206
  }
207
+ function currentChildRunId(state, stepId) {
208
+ return deriveChildRunId({
209
+ runId: state.runId,
210
+ stepId,
211
+ generation: state.resetCounts[stepId] ?? 0
212
+ });
213
+ }
186
214
 
187
215
  // src/exec/hooks.ts
188
216
  function makeHooks(deps) {
@@ -244,18 +272,18 @@ function resolveExecutionFact(args) {
244
272
  if (postState.phase.tag === "canceled") {
245
273
  return {
246
274
  fact: Facts.stepCanceled(runId, stepId, attempt, at),
247
- abortedHere: false
275
+ outcome: "run-canceled"
248
276
  };
249
277
  }
250
278
  if (isAbortRequested(stepStateOf(postState, stepId), attempt)) {
251
279
  return {
252
280
  fact: Facts.stepCanceled(runId, stepId, attempt, at),
253
- abortedHere: true
281
+ outcome: "aborted"
254
282
  };
255
283
  }
256
284
  return {
257
285
  fact: Facts.stepCompleted(runId, stepId, attempt, output, at),
258
- abortedHere: false
286
+ outcome: "completed"
259
287
  };
260
288
  }
261
289
  function every(intervalMs, tick) {
@@ -441,6 +469,16 @@ function makeActivityCtx(args) {
441
469
  }
442
470
 
443
471
  // src/exec/message.ts
472
+ function dispatchedOf(outcome, output) {
473
+ switch (outcome) {
474
+ case "completed":
475
+ return { tag: "completed", output };
476
+ case "run-canceled":
477
+ return { tag: "canceled", cause: "run" };
478
+ case "aborted":
479
+ return { tag: "canceled", cause: "step" };
480
+ }
481
+ }
444
482
  function startInput(def, input) {
445
483
  switch (def.kind) {
446
484
  case "task":
@@ -452,9 +490,29 @@ function startInput(def, input) {
452
490
  return null;
453
491
  }
454
492
  }
493
+ function isSupersededAttempt(step, attempt) {
494
+ switch (step.tag) {
495
+ case "backoff":
496
+ return attempt <= step.failedAttempt;
497
+ case "running":
498
+ case "awaitingSignal":
499
+ case "awaitingChild":
500
+ case "aborting":
501
+ return attempt < step.attempt;
502
+ default:
503
+ return false;
504
+ }
505
+ }
455
506
  function makeMessage(deps, hooks, progression) {
456
507
  const { fireHook, fireStepLifecycle } = hooks;
457
508
  const { advance } = progression;
509
+ async function fireStepCanceled(base, error) {
510
+ await fireHook(
511
+ deps.hooks?.onStepError,
512
+ { ...base, error, at: deps.clock.now() },
513
+ "onStepError"
514
+ );
515
+ }
458
516
  async function dispatchMessage(message) {
459
517
  const { queue } = deps;
460
518
  const resolution = await deps.flowOf(message.runId);
@@ -525,8 +583,10 @@ function makeMessage(deps, hooks, progression) {
525
583
  if (preState.phase.tag === "canceled") return { tag: "skip" };
526
584
  const preStep = stepStateOf(preState, stepId);
527
585
  if (preStep.tag === "completed" || preStep.tag === "failed" || preStep.tag === "skipped") {
528
- return isTerminalRun(preState) ? { tag: "skip" } : { tag: "recover" };
586
+ return isTerminalRun(preState) || message.readCount <= 1 ? { tag: "skip" } : { tag: "recover" };
529
587
  }
588
+ if (preStep.tag === "canceled") return { tag: "skip" };
589
+ if (isSupersededAttempt(preStep, attempt)) return { tag: "skip" };
530
590
  const claim = await store.claimStep(runId, stepId, attempt);
531
591
  if (claim === null) return { tag: "skip" };
532
592
  return { tag: "run", def: getDef(step), state: preState };
@@ -606,6 +666,12 @@ function makeMessage(deps, hooks, progression) {
606
666
  switch (outcome.tag) {
607
667
  case "parked":
608
668
  return;
669
+ case "canceled":
670
+ await fireStepCanceled(
671
+ { runId, flowId: flow2.id, stepId, attempt, kind: def.kind },
672
+ serializeError(new NagiAbortError(runId, outcome.cause))
673
+ );
674
+ return;
609
675
  case "advance":
610
676
  await advance(runId);
611
677
  return;
@@ -674,30 +740,41 @@ function makeMessage(deps, hooks, progression) {
674
740
  signal: ac.signal,
675
741
  emitLog: deps.emitLog
676
742
  };
677
- let abortedHere = false;
678
- const settle = async (output) => {
743
+ let outcome = "completed";
744
+ const settle = async (output, tx) => {
745
+ if (ac.signal.reason instanceof NagiStepTimeoutError)
746
+ throw ac.signal.reason;
679
747
  const resolved = resolveExecutionFact({
680
- postState: await store.loadRunState(runId),
748
+ postState: await store.loadRunState(runId, tx),
681
749
  runId,
682
750
  stepId,
683
751
  attempt,
684
752
  output,
685
753
  at: clock.now()
686
754
  });
687
- abortedHere = resolved.abortedHere;
755
+ outcome = resolved.outcome;
688
756
  return { output, fact: resolved.fact };
689
757
  };
690
758
  const inTx = (body) => store.runStep(
691
759
  runId,
692
760
  stepId,
693
761
  attempt,
694
- async (tx) => settle(await body(makeStepCtx({ ...ctxArgs, tx })))
762
+ async (tx) => settle(await body(makeStepCtx({ ...ctxArgs, tx })), tx)
695
763
  );
764
+ const runBody = async (body) => {
765
+ try {
766
+ return await body();
767
+ } catch (err) {
768
+ throw unwrapDeadline(err, ac.signal);
769
+ }
770
+ };
696
771
  try {
697
772
  let output;
698
773
  switch (def.kind) {
699
774
  case "task":
700
- output = await inTx((ctx) => def.run({ input, needs, ctx }));
775
+ output = await inTx(
776
+ (ctx) => runBody(() => def.run({ input, needs, ctx }))
777
+ );
701
778
  break;
702
779
  case "streaming":
703
780
  output = await inTx(
@@ -705,7 +782,7 @@ function makeMessage(deps, hooks, progression) {
705
782
  runId,
706
783
  stepId,
707
784
  base,
708
- (ctx) => def.run({ input, needs, ctx })
785
+ (ctx) => runBody(() => def.run({ input, needs, ctx }))
709
786
  )
710
787
  );
711
788
  break;
@@ -714,19 +791,17 @@ function makeMessage(deps, hooks, progression) {
714
791
  // in a short runStep tx, through the same settle as a task.
715
792
  case "activity": {
716
793
  const ctx = makeActivityCtx(ctxArgs);
717
- const out = await def.run({ input, needs, ctx });
794
+ const out = await runBody(() => def.run({ input, needs, ctx }));
718
795
  output = await store.runStep(
719
796
  runId,
720
797
  stepId,
721
798
  attempt,
722
- () => settle(out)
799
+ (tx) => settle(out, tx)
723
800
  );
724
801
  break;
725
802
  }
726
803
  }
727
- return abortedHere ? { tag: "parked" } : { tag: "completed", output };
728
- } catch (err) {
729
- throw unwrapDeadline(err, ac.signal);
804
+ return dispatchedOf(outcome, output);
730
805
  } finally {
731
806
  await watcher.stop();
732
807
  deadline?.stop();
@@ -741,7 +816,7 @@ function makeMessage(deps, hooks, progression) {
741
816
  );
742
817
  }
743
818
  const generation = state.resetCounts[stepId] ?? 0;
744
- const childRunId = await deriveChildRunId({ runId, stepId, generation });
819
+ const childRunId = await currentChildRunId(state, stepId);
745
820
  const childState = await deps.store.loadRunState(childRunId);
746
821
  if (isTerminalRun(childState)) {
747
822
  await progression.wakeParentFromChild(childRunId);
@@ -786,6 +861,11 @@ function makeMessage(deps, hooks, progression) {
786
861
  outcome.includeError ? error : void 0
787
862
  )
788
863
  );
864
+ const cause = postState.phase.tag === "canceled" ? "run" : "step";
865
+ await fireStepCanceled(
866
+ base,
867
+ outcome.includeError ? error : serializeError(new NagiAbortError(runId, cause))
868
+ );
789
869
  return outcome.advanceAfter ? { tag: "advance" } : { tag: "parked" };
790
870
  }
791
871
  case "retry": {
@@ -827,6 +907,7 @@ function makeMessage(deps, hooks, progression) {
827
907
  runId,
828
908
  Facts.stepCanceled(runId, stepId, attempt, clock.now(), error)
829
909
  );
910
+ await fireStepCanceled(base, error);
830
911
  await progression.terminate(
831
912
  { kind: "resolved", runId, flow: flow2 },
832
913
  {
@@ -901,7 +982,8 @@ function flowTermination(flow2, runState) {
901
982
  let failure;
902
983
  for (const stepId of Object.keys(flow2.steps)) {
903
984
  const state = stepStateOf(runState, stepId);
904
- if (!isStepTerminal(state)) return { kind: "running" };
985
+ if (!isStepTerminal(state) || state.tag === "canceled")
986
+ return { kind: "running" };
905
987
  if (state.tag === "failed" && failure === void 0) failure = state.error;
906
988
  }
907
989
  if (failure !== void 0) return { kind: "failed", error: failure };
@@ -921,7 +1003,24 @@ function nextTransition(flow2, runState) {
921
1003
  const { runnable, skip } = nextRunnable({ flow: flow2, runState, input });
922
1004
  if (runnable.length > 0) return { kind: "dispatch", runnable, skip };
923
1005
  if (skip.length > 0) return { kind: "skip", skip };
924
- return { kind: "waiting" };
1006
+ const canceled = canceledStepsIfIdle(flow2, runState);
1007
+ return canceled.length > 0 ? { kind: "stalled", canceled } : { kind: "waiting" };
1008
+ }
1009
+ var IN_FLIGHT_TAGS = /* @__PURE__ */ new Set([
1010
+ "running",
1011
+ "awaitingSignal",
1012
+ "awaitingChild",
1013
+ "backoff",
1014
+ "aborting"
1015
+ ]);
1016
+ function canceledStepsIfIdle(flow2, runState) {
1017
+ const canceled = [];
1018
+ for (const stepId of Object.keys(flow2.steps)) {
1019
+ const state = stepStateOf(runState, stepId);
1020
+ if (state.tag === "canceled") canceled.push(stepId);
1021
+ else if (IN_FLIGHT_TAGS.has(state.tag)) return [];
1022
+ }
1023
+ return canceled;
925
1024
  }
926
1025
  function computeFlowOutput(flow2, runState) {
927
1026
  if (flow2.output === void 0) return null;
@@ -931,13 +1030,19 @@ function computeFlowOutput(flow2, runState) {
931
1030
  }
932
1031
  return flow2.output(stepOutputs);
933
1032
  }
934
- function resetFactsOf(flow2, origin) {
1033
+ function resetFactsOf(flow2, runState, origin) {
935
1034
  const { runId, stepId, at } = origin;
936
- const set = origin.scope === "step" ? [stepId] : descendantsOf(flow2, stepId);
1035
+ const all = descendantsOf(flow2, stepId);
1036
+ const set = origin.scope === "step" ? all.filter(
1037
+ (id) => id === stepId || holdsNoValue(stepStateOf(runState, id))
1038
+ ) : all;
937
1039
  return set.map(
938
1040
  (id) => id === stepId ? Facts.stepReset(origin) : Facts.stepReset({ runId, stepId: id, at, cascadedFrom: stepId })
939
1041
  );
940
1042
  }
1043
+ function holdsNoValue(s) {
1044
+ return s.tag === "failed" || s.tag === "canceled" || s.tag === "skipped";
1045
+ }
941
1046
  function descendantsOf(flow2, stepId) {
942
1047
  const children = /* @__PURE__ */ new Map();
943
1048
  const addEdge = (from, to) => {
@@ -1016,6 +1121,13 @@ function makeProgression(deps, hooks) {
1016
1121
  case "settled":
1017
1122
  case "waiting":
1018
1123
  return;
1124
+ case "stalled":
1125
+ deps.emitLog({
1126
+ level: "warn",
1127
+ msg: "nagi: run stalled on canceled step(s) \u2014 replay({ from }) to recover",
1128
+ attrs: { runId, stepIds: t.canceled }
1129
+ });
1130
+ return;
1019
1131
  case "complete":
1020
1132
  await terminate(
1021
1133
  { kind: "resolved", runId, flow: flow2 },
@@ -1029,7 +1141,10 @@ function makeProgression(deps, hooks) {
1029
1141
  );
1030
1142
  return;
1031
1143
  case "dispatch":
1032
- await recordSkips(runId, t.skip);
1144
+ if (t.skip.length > 0) {
1145
+ await recordSkips(runId, t.skip);
1146
+ continue;
1147
+ }
1033
1148
  for (const stepId of t.runnable)
1034
1149
  await queue.enqueue(runId, stepId, { flowId: flow2.id });
1035
1150
  return;
@@ -1179,6 +1294,14 @@ function makeProgression(deps, hooks) {
1179
1294
  });
1180
1295
  return;
1181
1296
  }
1297
+ if (await currentChildRunId(parentState, parentStepId) !== childRunId) {
1298
+ deps.emitLog({
1299
+ level: "info",
1300
+ msg: "nagi: subflow wake skipped \u2014 child is from a superseded generation",
1301
+ attrs: { parentRunId, parentStepId, childRunId }
1302
+ });
1303
+ return;
1304
+ }
1182
1305
  const attempt = parentStep.attempt;
1183
1306
  const parentFlow = requireCurrent(await deps.flowOf(parentRunId));
1184
1307
  await settleSubflowStep({
@@ -1275,65 +1398,77 @@ function makeReplay(deps) {
1275
1398
  throw resolution.error;
1276
1399
  }
1277
1400
  const { flow: flow2 } = resolution;
1278
- if (opts.from !== void 0) {
1279
- if (!(opts.from in flow2.steps)) {
1280
- throw validationError(
1281
- `replay({ from }): step "${opts.from}" is not a step in flow "${flow2.id}".`,
1282
- ["from"]
1283
- );
1284
- }
1285
- await abortInFlight(runState, opts.from);
1286
- const resets = resetFactsOf(flow2, {
1287
- runId,
1288
- stepId: opts.from,
1289
- at: clock.now(),
1290
- ...compact({ scope: opts.scope })
1291
- });
1292
- for (const fact of resets) await store.appendFact(runId, fact);
1401
+ if (opts.from !== void 0 && !(opts.from in flow2.steps)) {
1402
+ throw validationError(
1403
+ `replay({ from }): step "${opts.from}" is not a step in flow "${flow2.id}".`,
1404
+ ["from"]
1405
+ );
1293
1406
  }
1294
1407
  const run = { runId, flow: flow2 };
1295
- if (opts.fireHooks !== false) {
1296
- await deps.dispatcherFor({ kind: "enqueue", run }).advance(runId);
1297
- return;
1298
- }
1299
- const inline = makeInlineQueue(queue);
1300
- const dispatcher = deps.dispatcherFor({
1301
- kind: "inline",
1302
- run,
1303
- queue: inline
1304
- });
1408
+ const inline = opts.fireHooks === false ? makeInlineQueue(queue) : void 0;
1409
+ const dispatcher = deps.dispatcherFor(
1410
+ inline === void 0 ? { kind: "enqueue", run } : { kind: "inline", run, queue: inline }
1411
+ );
1305
1412
  try {
1413
+ if (opts.from !== void 0) {
1414
+ await resetFrom(flow2, runState, opts.from, opts.scope, dispatcher);
1415
+ }
1306
1416
  await dispatcher.advance(runId);
1307
- await drainInline(dispatcher, inline);
1417
+ if (inline !== void 0) await drainInline(dispatcher, inline);
1308
1418
  } finally {
1309
- await inline.handOff();
1419
+ await inline?.handOff();
1420
+ }
1421
+ }
1422
+ async function resetFrom(flow2, runState, from, scope, dispatcher) {
1423
+ const { runId } = runState;
1424
+ const origin = { runId, stepId: from, ...compact({ scope }) };
1425
+ const inFlight = resetFactsOf(flow2, runState, {
1426
+ ...origin,
1427
+ at: clock.now()
1428
+ }).map((f) => f.stepId);
1429
+ await abortInFlight(runState, inFlight);
1430
+ const current = await store.loadRunState(runId);
1431
+ const resets = resetFactsOf(flow2, current, { ...origin, at: clock.now() });
1432
+ for (const fact of resets) await store.appendFact(runId, fact);
1433
+ for (const { stepId } of resets) {
1434
+ if (stepStateOf(current, stepId).tag !== "awaitingChild") continue;
1435
+ await dispatcher.cancel(await currentChildRunId(current, stepId), {
1436
+ cause: "explicit",
1437
+ reason: `superseded by replay({ from: "${from}" })`
1438
+ });
1310
1439
  }
1311
1440
  }
1312
- async function abortInFlight(state, stepId) {
1313
- if (stepStateOf(state, stepId).tag !== "running") return;
1441
+ async function abortInFlight(state, stepIds) {
1442
+ const waiting = /* @__PURE__ */ new Map();
1443
+ for (const id of stepIds) {
1444
+ if (stepStateOf(state, id).tag === "running") waiting.set(id, 0);
1445
+ }
1314
1446
  const { runId } = state;
1315
- let aborted = 0;
1316
1447
  const start = Date.now();
1317
- for (let s = state; ; s = await store.loadRunState(runId)) {
1318
- const step = stepStateOf(s, stepId);
1319
- if (step.tag === "pending" || isStepTerminal(step) || isTerminalRun(s)) {
1320
- return;
1321
- }
1322
- if (step.tag === "running" && step.attempt > aborted) {
1323
- aborted = step.attempt;
1324
- await store.appendFact(
1325
- runId,
1326
- Facts.stepAbortRequested({
1448
+ for (let s = state; waiting.size > 0; s = await store.loadRunState(runId)) {
1449
+ if (isTerminalRun(s)) return;
1450
+ for (const [stepId, aborted] of waiting) {
1451
+ const step = stepStateOf(s, stepId);
1452
+ if (step.tag === "pending" || isStepTerminal(step)) {
1453
+ waiting.delete(stepId);
1454
+ } else if (step.tag === "running" && step.attempt > aborted) {
1455
+ waiting.set(stepId, step.attempt);
1456
+ await store.appendFact(
1327
1457
  runId,
1328
- stepId,
1329
- attempt: step.attempt,
1330
- at: clock.now()
1331
- })
1332
- );
1458
+ Facts.stepAbortRequested({
1459
+ runId,
1460
+ stepId,
1461
+ attempt: step.attempt,
1462
+ at: clock.now()
1463
+ })
1464
+ );
1465
+ }
1333
1466
  }
1467
+ const [stuck] = waiting;
1468
+ if (stuck === void 0) return;
1334
1469
  if (Date.now() - start >= ABORT_SETTLE_DEADLINE_MS) {
1335
1470
  throw new NagiRuntimeError(
1336
- `replay({ from }): timed out after ${ABORT_SETTLE_DEADLINE_MS}ms waiting for step "${stepId}" (attempt ${aborted}) to honor abort signal. Handler may be ignoring ctx.signal.`
1471
+ `replay({ from }): timed out after ${ABORT_SETTLE_DEADLINE_MS}ms waiting for step "${stuck[0]}" (attempt ${stuck[1]}) to honor abort signal. Handler may be ignoring ctx.signal.`
1337
1472
  );
1338
1473
  }
1339
1474
  await new Promise((r) => setTimeout(r, ABORT_SETTLE_POLL_MS));
@@ -1420,25 +1555,36 @@ function makeRunLifecycle(deps) {
1420
1555
  switch (boundary.kind) {
1421
1556
  case "own":
1422
1557
  return {
1423
- tryStart: (runId, fact, concurrency) => store.tryStartRun(runId, fact, concurrency),
1424
- seed: async (_runId, _flowId, t) => t.skip.length > 0 ? ADVANCE : { kind: "enqueue", steps: t.runnable }
1558
+ tryStart: (runId, fact, concurrency, steps) => store.tryStartRun(
1559
+ runId,
1560
+ fact,
1561
+ concurrency,
1562
+ steps.length > 0 ? { queue, flowId: fact.flowId, steps } : void 0
1563
+ )
1425
1564
  };
1426
1565
  case "caller":
1427
1566
  return {
1428
- tryStart: (runId, fact, concurrency) => store.tryStartRunOnTx(boundary.tx, runId, fact, concurrency),
1429
- seed: async (runId, flowId, t) => {
1430
- const txQueue = deps.queueForTx(boundary.tx);
1431
- for (const stepId of t.runnable) {
1432
- await txQueue.enqueue(runId, stepId, { flowId });
1567
+ tryStart: async (runId, fact, concurrency, steps) => {
1568
+ const result = await store.tryStartRunOnTx(
1569
+ boundary.tx,
1570
+ runId,
1571
+ fact,
1572
+ concurrency
1573
+ );
1574
+ if (result.started && steps.length > 0) {
1575
+ const txQueue = deps.queueForTx(boundary.tx);
1576
+ for (const stepId of steps) {
1577
+ await txQueue.enqueue(runId, stepId, { flowId: fact.flowId });
1578
+ }
1433
1579
  }
1434
- return { kind: "enqueued", steps: t.runnable, skip: t.skip };
1580
+ return result;
1435
1581
  }
1436
1582
  };
1437
1583
  }
1438
1584
  }
1439
1585
  async function stage(args) {
1440
1586
  const { flow: flow2, validatedInput, runId, parent } = args;
1441
- const { tryStart, seed } = resolveBoundary(args.boundary);
1587
+ const { tryStart } = resolveBoundary(args.boundary);
1442
1588
  const startedAt = clock.now();
1443
1589
  const fact = Facts.flowStarted({
1444
1590
  runId,
@@ -1452,10 +1598,16 @@ function makeRunLifecycle(deps) {
1452
1598
  })
1453
1599
  });
1454
1600
  const concurrency = concurrencyOf(flow2, validatedInput);
1455
- const { started, canceled } = await tryStart(runId, fact, concurrency);
1456
- if (!started) return EXISTS;
1457
1601
  const t = nextTransition(flow2, foldRun(runId, [fact]));
1458
- const dispatch = t.kind === "dispatch" ? await seed(runId, flow2.id, t) : ADVANCE;
1602
+ const steps = t.kind === "dispatch" ? t.runnable : [];
1603
+ const { started, canceled } = await tryStart(
1604
+ runId,
1605
+ fact,
1606
+ concurrency,
1607
+ steps
1608
+ );
1609
+ if (!started) return EXISTS;
1610
+ const dispatch = t.kind === "dispatch" ? { kind: "enqueued", steps: t.runnable, skip: t.skip } : ADVANCE;
1459
1611
  return {
1460
1612
  kind: "started",
1461
1613
  effects: {
@@ -1483,13 +1635,9 @@ function makeRunLifecycle(deps) {
1483
1635
  await hooks.fireHook(flow2.onStart, started, "flow.onStart");
1484
1636
  await hooks.fireHook(flowHooks?.onFlowStart, started, "onFlowStart");
1485
1637
  switch (dispatch.kind) {
1486
- case "enqueue":
1487
- for (const stepId of dispatch.steps) {
1488
- await queue.enqueue(started.runId, stepId, { flowId: flow2.id });
1489
- }
1490
- return;
1491
1638
  case "enqueued":
1492
1639
  await recordSkips(started.runId, dispatch.skip);
1640
+ if (dispatch.skip.length > 0) await dispatcher.advance(started.runId);
1493
1641
  return;
1494
1642
  case "advance":
1495
1643
  await dispatcher.advance(started.runId);
@@ -1540,7 +1688,11 @@ function makeRunLifecycle(deps) {
1540
1688
  parent,
1541
1689
  boundary: { kind: "own" }
1542
1690
  });
1543
- if (staged.kind === "started") await applyEffects(staged.effects);
1691
+ if (staged.kind === "started") {
1692
+ await applyEffects(staged.effects);
1693
+ } else {
1694
+ await dispatcher.advance(runId);
1695
+ }
1544
1696
  return runId;
1545
1697
  }
1546
1698
  return { start, stage, applyEffects, startChildRun };
@@ -1689,9 +1841,10 @@ var WorkerImpl = class {
1689
1841
  });
1690
1842
  }
1691
1843
  async runUntilEmpty(opts) {
1692
- const deadline = opts?.deadline;
1844
+ const timeoutMs = opts?.timeoutMs;
1845
+ const endAt = timeoutMs === void 0 ? void 0 : this.deps.clock.now().getTime() + timeoutMs;
1693
1846
  return this.pump({
1694
- shouldContinue: () => deadline === void 0 || this.deps.clock.now().getTime() < deadline,
1847
+ shouldContinue: () => endAt === void 0 || this.deps.clock.now().getTime() < endAt,
1695
1848
  batchSize: () => this.concurrency
1696
1849
  });
1697
1850
  }
@@ -1740,13 +1893,20 @@ var WorkerImpl = class {
1740
1893
  try {
1741
1894
  result = await this.dispatcher.dispatchMessage(msg);
1742
1895
  } catch (err) {
1896
+ const delayMs = this.dequeueBackoffMs(msg.readCount);
1743
1897
  this.deps.emitLog({
1744
1898
  level: "error",
1745
1899
  msg: "worker.dispatch threw uncaught",
1746
- attrs: { error: String(err) }
1900
+ attrs: {
1901
+ runId: msg.runId,
1902
+ stepId: msg.stepId,
1903
+ readCount: msg.readCount,
1904
+ delayMs,
1905
+ error: String(err)
1906
+ }
1747
1907
  });
1748
1908
  try {
1749
- await this.deps.queue.nack(msg.receipt);
1909
+ await this.deps.queue.nack(msg.receipt, { delayMs });
1750
1910
  } catch {
1751
1911
  }
1752
1912
  return;