@nagi-js/core 0.1.1-rc.17 → 0.1.1-rc.18

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
@@ -205,6 +205,10 @@ function foldRun(runId, facts) {
205
205
  case "step.reset":
206
206
  steps[fact.stepId] = PENDING;
207
207
  delete selectedArms[fact.stepId];
208
+ delete bufferedSignals[fact.stepId];
209
+ if (phase.tag === "completed" || phase.tag === "failed") {
210
+ phase = { tag: "running" };
211
+ }
208
212
  break;
209
213
  case "step.started":
210
214
  case "step.completed":
@@ -234,6 +238,9 @@ function foldRun(runId, facts) {
234
238
  };
235
239
  }
236
240
  break;
241
+ case "signal.received":
242
+ delete bufferedSignals[fact.stepId];
243
+ break;
237
244
  }
238
245
  }
239
246
  return {
@@ -328,7 +335,6 @@ function makeBuilder() {
328
335
  run: config.run,
329
336
  ...compact({
330
337
  retry: config.retry,
331
- timeoutMs: config.timeoutMs,
332
338
  when: config.when,
333
339
  onStart: config.onStart,
334
340
  onComplete: config.onComplete,
@@ -345,7 +351,6 @@ function makeBuilder() {
345
351
  run: config.run,
346
352
  ...compact({
347
353
  retry: config.retry,
348
- timeoutMs: config.timeoutMs,
349
354
  when: config.when,
350
355
  onStart: config.onStart,
351
356
  onComplete: config.onComplete,
@@ -362,7 +367,6 @@ function makeBuilder() {
362
367
  run: config.run,
363
368
  ...compact({
364
369
  retry: config.retry,
365
- timeoutMs: config.timeoutMs,
366
370
  when: config.when,
367
371
  onStart: config.onStart,
368
372
  onComplete: config.onComplete,
@@ -377,9 +381,9 @@ function makeBuilder() {
377
381
  kind: "signal",
378
382
  needs: normalizeNeeds(config.needs),
379
383
  schema: config.schema,
384
+ timeoutMs: config.timeoutMs,
380
385
  ...compact({
381
386
  names: config.names,
382
- timeoutMs: config.timeoutMs,
383
387
  when: config.when
384
388
  })
385
389
  };
@@ -392,7 +396,6 @@ function makeBuilder() {
392
396
  childFlowId: child.id,
393
397
  buildInput: config.input,
394
398
  ...compact({
395
- timeoutMs: config.timeoutMs,
396
399
  when: config.when
397
400
  })
398
401
  };
@@ -612,7 +615,8 @@ async function canonicalizeStep(id, def) {
612
615
  }
613
616
  async function applyGuardAndTimeout(out, def) {
614
617
  if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
615
- if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
618
+ if (def.timeoutMs !== void 0 && def.timeoutMs !== "unbounded")
619
+ out.timeoutMs = def.timeoutMs;
616
620
  }
617
621
  async function canonicalizeTask(base, def) {
618
622
  const out = { ...base };
@@ -834,6 +838,12 @@ var NagiRuntimeError = class extends Error {
834
838
  this.name = "NagiRuntimeError";
835
839
  }
836
840
  };
841
+ var NagiNonRetryableError = class extends Error {
842
+ constructor(message, opts) {
843
+ super(message, opts);
844
+ this.name = "NagiNonRetryableError";
845
+ }
846
+ };
837
847
  var NagiCanceledError = class extends Error {
838
848
  runId;
839
849
  canceledByRunId;
@@ -1433,6 +1443,8 @@ var InMemoryStore = class {
1433
1443
  globalFacts = [];
1434
1444
  activeByKey = /* @__PURE__ */ new Map();
1435
1445
  keyByActiveRun = /* @__PURE__ */ new Map();
1446
+ // Kept past terminal facts so a reopened run can re-take its slot.
1447
+ slotByRun = /* @__PURE__ */ new Map();
1436
1448
  childrenByParent = /* @__PURE__ */ new Map();
1437
1449
  summaries = /* @__PURE__ */ new Map();
1438
1450
  streamHub = new InMemoryStreamHub();
@@ -1446,6 +1458,24 @@ var InMemoryStore = class {
1446
1458
  }
1447
1459
  async appendFact(runId, fact) {
1448
1460
  const list = this.facts.get(runId) ?? [];
1461
+ if (fact.kind === "step.reset") {
1462
+ const prior = foldRun(runId, list);
1463
+ if (prior.phase.tag === "completed" || prior.phase.tag === "failed") {
1464
+ const slot = this.slotByRun.get(runId);
1465
+ if (slot !== void 0) {
1466
+ const holder = this.activeByKey.get(slot);
1467
+ if (holder !== void 0 && holder !== runId) {
1468
+ throw new NagiConcurrencyConflictError({
1469
+ runId,
1470
+ flowId: prior.flowId,
1471
+ concurrencyKey: slot.slice(slot.indexOf("::") + 2)
1472
+ });
1473
+ }
1474
+ this.activeByKey.set(slot, runId);
1475
+ this.keyByActiveRun.set(runId, slot);
1476
+ }
1477
+ }
1478
+ }
1449
1479
  list.push(fact);
1450
1480
  this.facts.set(runId, list);
1451
1481
  switch (fact.kind) {
@@ -1505,6 +1535,7 @@ var InMemoryStore = class {
1505
1535
  }
1506
1536
  this.activeByKey.set(slot, runId);
1507
1537
  this.keyByActiveRun.set(runId, slot);
1538
+ this.slotByRun.set(runId, slot);
1508
1539
  }
1509
1540
  this.facts.set(runId, [fact]);
1510
1541
  const parentRunId = fact.parent?.runId;
@@ -1613,7 +1644,8 @@ var InMemoryStore = class {
1613
1644
  );
1614
1645
  await queue.enqueue(c.runId, c.stepId, {
1615
1646
  attempt: decision.nextAttempt,
1616
- delayMs: decision.backoffMs
1647
+ delayMs: decision.backoffMs,
1648
+ ...state?.flowId !== void 0 ? { flowId: state.flowId } : {}
1617
1649
  });
1618
1650
  reaped.push({
1619
1651
  runId: c.runId,
@@ -1756,7 +1788,7 @@ var InMemoryStore = class {
1756
1788
  let error;
1757
1789
  let canceledByRunId;
1758
1790
  let concurrencyKey;
1759
- for (let i = factList.length - 1; i >= 0; i--) {
1791
+ for (let i = isTerminalRun(state) ? factList.length - 1 : -1; i >= 0; i--) {
1760
1792
  const f = factList[i];
1761
1793
  if (f === void 0) continue;
1762
1794
  if (f.kind === "flow.completed") {
@@ -1927,7 +1959,7 @@ function summarize(runId, facts) {
1927
1959
  if (first === void 0 || first.kind !== "flow.started") return null;
1928
1960
  const projected = foldRun(runId, facts);
1929
1961
  let completedAt = null;
1930
- for (let i = facts.length - 1; i >= 0; i--) {
1962
+ for (let i = isTerminalRun(projected) ? facts.length - 1 : -1; i >= 0; i--) {
1931
1963
  const f = facts[i];
1932
1964
  if (f === void 0) continue;
1933
1965
  if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
@@ -2006,8 +2038,10 @@ var InMemoryQueue = class {
2006
2038
  stepId,
2007
2039
  payload: opts?.payload ?? null,
2008
2040
  attempt: opts?.attempt ?? 1,
2041
+ readCount: 0,
2009
2042
  enqueuedAt: now,
2010
- visibleAt: now + (opts?.delayMs ?? 0)
2043
+ visibleAt: now + (opts?.delayMs ?? 0),
2044
+ ...opts?.flowId !== void 0 ? { flowId: opts.flowId } : {}
2011
2045
  };
2012
2046
  this.pending.push(item);
2013
2047
  }
@@ -2018,11 +2052,15 @@ var InMemoryQueue = class {
2018
2052
  const item = this.pending[i];
2019
2053
  if (item === void 0) continue;
2020
2054
  if (item.visibleAt > now) continue;
2021
- const next = { ...item, visibleAt: now + this.leaseMs };
2055
+ const delivered = {
2056
+ ...item,
2057
+ readCount: item.readCount + 1,
2058
+ visibleAt: now + this.leaseMs
2059
+ };
2022
2060
  this.pending.splice(i, 1);
2023
2061
  i--;
2024
- this.leased.set(item.receipt, next);
2025
- claimed.push(item);
2062
+ this.leased.set(item.receipt, delivered);
2063
+ claimed.push(delivered);
2026
2064
  }
2027
2065
  return claimed;
2028
2066
  }
@@ -2044,6 +2082,15 @@ var InMemoryQueue = class {
2044
2082
  if (!item) return;
2045
2083
  this.leased.set(receipt, { ...item, visibleAt: Date.now() + leaseMs });
2046
2084
  }
2085
+ async inspect(runId) {
2086
+ const all = [...this.pending, ...this.leased.values()];
2087
+ return all.filter((m) => m.runId === runId).map((m) => ({
2088
+ stepId: m.stepId,
2089
+ attempt: m.attempt,
2090
+ readCount: m.readCount,
2091
+ visibleAt: new Date(m.visibleAt)
2092
+ }));
2093
+ }
2047
2094
  };
2048
2095
  var InMemoryClock = class {
2049
2096
  timers = /* @__PURE__ */ new Map();
@@ -2431,6 +2478,7 @@ function startCancelWatcher(args) {
2431
2478
  }
2432
2479
  var DEFAULT_HEARTBEAT_LEASE_MS = 12e4;
2433
2480
  var DEFAULT_HEARTBEAT_INTERVAL_MS = 4e4;
2481
+ var DEFAULT_LEASE_HOLD_WARN_MS = 3e5;
2434
2482
  function startHeartbeat(args) {
2435
2483
  const {
2436
2484
  queue,
@@ -2441,13 +2489,28 @@ function startHeartbeat(args) {
2441
2489
  receipt,
2442
2490
  intervalMs,
2443
2491
  leaseMs,
2492
+ holdWarnMs,
2444
2493
  emitLog
2445
2494
  } = args;
2446
2495
  let stopped = false;
2447
2496
  let timer;
2497
+ const startedAtMs = Date.now();
2498
+ let warnedCrossings = 0;
2448
2499
  const schedule = () => {
2449
2500
  timer = setTimeout(() => {
2450
2501
  void (async () => {
2502
+ if (holdWarnMs > 0) {
2503
+ const heldMs = Date.now() - startedAtMs;
2504
+ const crossings = Math.floor(heldMs / holdWarnMs);
2505
+ if (crossings > warnedCrossings) {
2506
+ warnedCrossings = crossings;
2507
+ emitLog({
2508
+ level: "warn",
2509
+ msg: "heartbeat: step is holding a worker slot unusually long \u2014 slow handler, or an in-step wait that should be a b.signal step?",
2510
+ attrs: { runId, stepId, attempt, heldMs }
2511
+ });
2512
+ }
2513
+ }
2451
2514
  await Promise.all([
2452
2515
  queue.extend(receipt, leaseMs).catch((err) => {
2453
2516
  emitLog({
@@ -2489,7 +2552,7 @@ function classifyFailure(args) {
2489
2552
  includeError: isAbort
2490
2553
  };
2491
2554
  }
2492
- const cancel = findNagiCanceledError(err);
2555
+ const cancel = findInCauseChain(err, NagiCanceledError);
2493
2556
  if (cancel !== void 0) {
2494
2557
  return {
2495
2558
  tag: "flowCanceled",
@@ -2497,16 +2560,19 @@ function classifyFailure(args) {
2497
2560
  concurrencyKey: cancel.concurrencyKey
2498
2561
  };
2499
2562
  }
2563
+ if (findInCauseChain(err, NagiNonRetryableError) !== void 0) {
2564
+ return { tag: "failed" };
2565
+ }
2500
2566
  if (attempt < policy.maxAttempts && retryAllows(policy, err)) {
2501
2567
  return { tag: "retry", delayMs: computeBackoff(policy, attempt) };
2502
2568
  }
2503
2569
  return { tag: "failed" };
2504
2570
  }
2505
- function findNagiCanceledError(err) {
2571
+ function findInCauseChain(err, ctor) {
2506
2572
  let cursor = err;
2507
2573
  const seen = /* @__PURE__ */ new Set();
2508
2574
  while (cursor instanceof Error && !seen.has(cursor)) {
2509
- if (cursor instanceof NagiCanceledError) return cursor;
2575
+ if (cursor instanceof ctor) return cursor;
2510
2576
  seen.add(cursor);
2511
2577
  cursor = cursor.cause;
2512
2578
  }
@@ -2577,12 +2643,26 @@ function makeMessage(deps, hooks, progression) {
2577
2643
  const { advance } = progression;
2578
2644
  async function dispatchMessage(message) {
2579
2645
  const { queue } = deps;
2580
- const flow2 = await deps.flowFor(message.runId);
2646
+ let flow2;
2647
+ try {
2648
+ flow2 = await deps.flowFor(message.runId);
2649
+ } catch (err) {
2650
+ if (err instanceof NagiFlowSnapshotGoneError && isTerminalRun(await deps.store.loadRunState(message.runId))) {
2651
+ await queue.ack(message.receipt);
2652
+ return;
2653
+ }
2654
+ throw err;
2655
+ }
2581
2656
  const admission = await admit({ flow: flow2, message });
2582
2657
  if (admission.tag === "skip") {
2583
2658
  await queue.ack(message.receipt);
2584
2659
  return;
2585
2660
  }
2661
+ if (admission.tag === "recover") {
2662
+ await advance(message.runId);
2663
+ await queue.ack(message.receipt);
2664
+ return;
2665
+ }
2586
2666
  const { def, state } = admission;
2587
2667
  await recordStarted({ flow: flow2, message, def, state });
2588
2668
  const startedAt = Date.now();
@@ -2595,6 +2675,7 @@ function makeMessage(deps, hooks, progression) {
2595
2675
  receipt: message.receipt,
2596
2676
  intervalMs: deps.heartbeat.intervalMs,
2597
2677
  leaseMs: deps.heartbeat.leaseMs,
2678
+ holdWarnMs: deps.heartbeat.holdWarnMs,
2598
2679
  emitLog: deps.emitLog
2599
2680
  });
2600
2681
  let outcome;
@@ -2605,8 +2686,8 @@ function makeMessage(deps, hooks, progression) {
2605
2686
  } finally {
2606
2687
  heartbeat.stop();
2607
2688
  }
2608
- await queue.ack(message.receipt);
2609
2689
  await interpret({ flow: flow2, message, def, startedAt, outcome });
2690
+ await queue.ack(message.receipt);
2610
2691
  }
2611
2692
  async function admit(args) {
2612
2693
  const { flow: flow2, message } = args;
@@ -2624,7 +2705,7 @@ function makeMessage(deps, hooks, progression) {
2624
2705
  if (preState.phase.tag === "canceled") return { tag: "skip" };
2625
2706
  const preStep = stepStateOf(preState, stepId);
2626
2707
  if (preStep.tag === "completed" || preStep.tag === "failed" || preStep.tag === "skipped") {
2627
- return { tag: "skip" };
2708
+ return isTerminalRun(preState) ? { tag: "skip" } : { tag: "recover" };
2628
2709
  }
2629
2710
  const claim = await store.claimStep(runId, stepId, attempt);
2630
2711
  if (claim === null) return { tag: "skip" };
@@ -2640,7 +2721,7 @@ function makeMessage(deps, hooks, progression) {
2640
2721
  runId,
2641
2722
  Facts.stepStarted(runId, stepId, attempt, def.kind, startedAt)
2642
2723
  );
2643
- if (def.kind === "signal" && def.timeoutMs != null) {
2724
+ if (def.kind === "signal" && typeof def.timeoutMs === "number") {
2644
2725
  await store.upsertTimer(
2645
2726
  runId,
2646
2727
  stepId,
@@ -2961,7 +3042,8 @@ function makeMessage(deps, hooks, progression) {
2961
3042
  );
2962
3043
  await queue.enqueue(runId, stepId, {
2963
3044
  attempt: attempt + 1,
2964
- delayMs: outcome.delayMs
3045
+ delayMs: outcome.delayMs,
3046
+ flowId: flow2.id
2965
3047
  });
2966
3048
  return { tag: "parked" };
2967
3049
  }
@@ -3062,7 +3144,8 @@ function makeProgression(deps, hooks) {
3062
3144
  return;
3063
3145
  case "dispatch":
3064
3146
  await recordSkips(runId, t.skip);
3065
- for (const stepId of t.runnable) await queue.enqueue(runId, stepId);
3147
+ for (const stepId of t.runnable)
3148
+ await queue.enqueue(runId, stepId, { flowId: flow2.id });
3066
3149
  return;
3067
3150
  case "skip":
3068
3151
  await recordSkips(runId, t.skip);
@@ -3222,25 +3305,33 @@ function makeDispatcher(deps) {
3222
3305
  async function sweepTimers(now) {
3223
3306
  const timedOut = await deps.store.sweepSignalTimeouts({ now });
3224
3307
  for (const { runId, stepId, attempt, fireAt } of timedOut) {
3225
- if (deps.hooks?.onStepError) {
3226
- const flow2 = await deps.flowFor(runId);
3227
- await hooks.fireHook(
3228
- deps.hooks.onStepError,
3229
- {
3230
- runId,
3231
- flowId: flow2.id,
3232
- stepId,
3233
- attempt,
3234
- kind: "signal",
3235
- error: serializeError(
3236
- new NagiSignalTimeoutError({ runId, stepId, fireAt })
3237
- ),
3238
- at: now
3239
- },
3240
- "onStepError"
3241
- );
3308
+ try {
3309
+ if (deps.hooks?.onStepError) {
3310
+ const flow2 = await deps.flowFor(runId);
3311
+ await hooks.fireHook(
3312
+ deps.hooks.onStepError,
3313
+ {
3314
+ runId,
3315
+ flowId: flow2.id,
3316
+ stepId,
3317
+ attempt,
3318
+ kind: "signal",
3319
+ error: serializeError(
3320
+ new NagiSignalTimeoutError({ runId, stepId, fireAt })
3321
+ ),
3322
+ at: now
3323
+ },
3324
+ "onStepError"
3325
+ );
3326
+ }
3327
+ await progression.advance(runId);
3328
+ } catch (err) {
3329
+ deps.emitLog({
3330
+ level: "error",
3331
+ msg: "nagi: signal timeout fired but the run could not be advanced \u2014 re-drive with operator.retry",
3332
+ attrs: { runId, stepId, attempt, error: String(err) }
3333
+ });
3242
3334
  }
3243
- await progression.advance(runId);
3244
3335
  }
3245
3336
  return timedOut.length;
3246
3337
  }
@@ -3550,6 +3641,16 @@ async function drainInline(dispatcher, queue) {
3550
3641
  var DEFAULT_CONCURRENCY = 4;
3551
3642
  var DEFAULT_POLL_INTERVAL_MS = 1e3;
3552
3643
  var DEFAULT_TIMER_SWEEP_INTERVAL_MS = 3e4;
3644
+ var SNAPSHOT_GONE_FALLBACK_NACK_DELAY_MS = 3e4;
3645
+ var MAX_DEQUEUE_BACKOFF_MS = 3e4;
3646
+ var MIN_DEQUEUE_BACKOFF_MS = 50;
3647
+ var defaultSnapshotGonePolicy = (readCount) => {
3648
+ if (readCount > 60) return { action: "fail" };
3649
+ return {
3650
+ action: "retry",
3651
+ delayMs: Math.min(readCount * readCount * 1e3, 3e5)
3652
+ };
3653
+ };
3553
3654
  function makeWorker(deps, config) {
3554
3655
  return new WorkerImpl(deps, config);
3555
3656
  }
@@ -3560,6 +3661,8 @@ var WorkerImpl = class {
3560
3661
  this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
3561
3662
  this.signal = config?.signal;
3562
3663
  this.dispatcher = makeDispatcher(deps);
3664
+ this.snapshotGonePolicy = config?.snapshotGonePolicy ?? defaultSnapshotGonePolicy;
3665
+ this.maxPerFlow = config?.maxConcurrencyPerFlow !== void 0 ? Math.max(1, config.maxConcurrencyPerFlow) : void 0;
3563
3666
  this.timerSweepIntervalMs = config?.timerSweepIntervalMs ?? DEFAULT_TIMER_SWEEP_INTERVAL_MS;
3564
3667
  this.lastTimerSweepAt = this.deps.clock.now().getTime();
3565
3668
  }
@@ -3570,8 +3673,45 @@ var WorkerImpl = class {
3570
3673
  signal;
3571
3674
  dispatcher;
3572
3675
  timerSweepIntervalMs;
3676
+ snapshotGonePolicy;
3677
+ maxPerFlow;
3678
+ inFlightByFlow = /* @__PURE__ */ new Map();
3573
3679
  lastTimerSweepAt;
3680
+ // Per-flow blast-radius bound (maxConcurrencyPerFlow). A message over its
3681
+ // flow's cap is DEFERRED — delayed nack, redelivered after ~pollIntervalMs —
3682
+ // not dropped. Messages without flowId (enqueued pre-upgrade) are exempt.
3683
+ // Deferral does raise pgmq read_ct, which the snapshot-gone policy reads;
3684
+ // that only matters if the same flow later goes snapshot-gone, where an
3685
+ // earlier fail is acceptable.
3686
+ admitFlow(msg) {
3687
+ if (this.maxPerFlow === void 0 || msg.flowId === void 0) return true;
3688
+ return (this.inFlightByFlow.get(msg.flowId) ?? 0) < this.maxPerFlow;
3689
+ }
3690
+ // Returns the release fn; caller must invoke it exactly once when done.
3691
+ trackFlow(msg) {
3692
+ const { flowId } = msg;
3693
+ if (flowId === void 0) return () => {
3694
+ };
3695
+ this.inFlightByFlow.set(flowId, (this.inFlightByFlow.get(flowId) ?? 0) + 1);
3696
+ return () => {
3697
+ const n = (this.inFlightByFlow.get(flowId) ?? 1) - 1;
3698
+ if (n <= 0) this.inFlightByFlow.delete(flowId);
3699
+ else this.inFlightByFlow.set(flowId, n);
3700
+ };
3701
+ }
3702
+ async defer(msg) {
3703
+ try {
3704
+ await this.deps.queue.nack(msg.receipt, { delayMs: this.pollIntervalMs });
3705
+ } catch {
3706
+ }
3707
+ }
3708
+ // MUST settle only via the abort signal. A rejection escaping this loop
3709
+ // silently ends ALL flow processing in a process that otherwise looks
3710
+ // healthy — observed in prod as one transient `pgmq.read` connection
3711
+ // timeout killing the loop, then 37h of fleet-wide stuck runs because
3712
+ // nothing restarts it. Every await below is therefore guarded.
3574
3713
  async run() {
3714
+ let dequeueFailures = 0;
3575
3715
  while (!this.aborted()) {
3576
3716
  await this.maybeSweepTimers();
3577
3717
  const slots = this.concurrency - this.inFlight;
@@ -3579,12 +3719,32 @@ var WorkerImpl = class {
3579
3719
  await this.sleep(50);
3580
3720
  continue;
3581
3721
  }
3582
- const messages = await this.dequeue(slots);
3722
+ let messages;
3723
+ try {
3724
+ messages = await this.dequeue(slots);
3725
+ } catch (err) {
3726
+ dequeueFailures++;
3727
+ this.deps.emitLog({
3728
+ level: "error",
3729
+ msg: "worker.dequeue failed; backing off",
3730
+ attrs: {
3731
+ error: String(err),
3732
+ consecutiveFailures: dequeueFailures,
3733
+ backoffMs: this.dequeueBackoffMs(dequeueFailures)
3734
+ }
3735
+ });
3736
+ await this.sleep(this.dequeueBackoffMs(dequeueFailures));
3737
+ continue;
3738
+ }
3739
+ dequeueFailures = 0;
3583
3740
  if (messages.length === 0) {
3584
3741
  await this.sleep(this.pollIntervalMs);
3585
3742
  continue;
3586
3743
  }
3587
- for (const msg of messages) this.fire(msg);
3744
+ for (const msg of messages) {
3745
+ if (this.admitFlow(msg)) this.fire(msg);
3746
+ else await this.defer(msg);
3747
+ }
3588
3748
  }
3589
3749
  await this.drain();
3590
3750
  }
@@ -3602,22 +3762,55 @@ var WorkerImpl = class {
3602
3762
  batchSize: () => this.concurrency
3603
3763
  });
3604
3764
  }
3765
+ // Unlike run(), a dequeue failure here PROPAGATES. These are bounded calls
3766
+ // that hand a result back to an awaiting caller, so a rejection is observed,
3767
+ // not silent — the outage shape run() guards against cannot happen. The
3768
+ // alternatives are both worse: retrying would let runUntilEmpty() hang for
3769
+ // the length of a database outage, and swallowing would report an
3770
+ // unreachable queue as a drained one.
3605
3771
  async pump(opts) {
3606
3772
  let processed = 0;
3607
3773
  while (!this.aborted() && opts.shouldContinue(processed)) {
3608
3774
  const messages = await this.dequeue(opts.batchSize(processed));
3609
3775
  if (messages.length === 0) break;
3610
- await Promise.all(messages.map((m) => this.dispatchSafely(m)));
3611
- processed += messages.length;
3776
+ const admitted = [];
3777
+ for (const m of messages) {
3778
+ if (this.admitFlow(m)) {
3779
+ admitted.push({ m, release: this.trackFlow(m) });
3780
+ } else {
3781
+ await this.defer(m);
3782
+ }
3783
+ }
3784
+ await Promise.all(
3785
+ admitted.map(({ m }) => this.dispatchSafely(m))
3786
+ ).finally(() => {
3787
+ for (const { release } of admitted) release();
3788
+ });
3789
+ processed += admitted.length;
3790
+ if (admitted.length === 0) break;
3612
3791
  }
3613
3792
  return { processed };
3614
3793
  }
3615
3794
  async dequeue(count) {
3616
3795
  return this.deps.queue.dequeue({ count: Math.max(1, count) });
3617
3796
  }
3797
+ // Exponential, capped, reset on the first success: a one-off blip costs one
3798
+ // poll interval, a real outage settles to a 30s cadence instead of hammering
3799
+ // a down database and flooding logs. Anchored on pollIntervalMs (default 1s,
3800
+ // so the default curve is 1s -> 30s) and floored so a 0/near-0 poll interval
3801
+ // cannot turn a persistent failure into a tight loop.
3802
+ dequeueBackoffMs(consecutiveFailures) {
3803
+ const base = Math.max(this.pollIntervalMs, MIN_DEQUEUE_BACKOFF_MS);
3804
+ return Math.min(
3805
+ base * 2 ** (consecutiveFailures - 1),
3806
+ MAX_DEQUEUE_BACKOFF_MS
3807
+ );
3808
+ }
3618
3809
  fire(msg) {
3619
3810
  this.inFlight++;
3811
+ const release = this.trackFlow(msg);
3620
3812
  void this.dispatchSafely(msg).finally(() => {
3813
+ release();
3621
3814
  this.inFlight = Math.max(0, this.inFlight - 1);
3622
3815
  });
3623
3816
  }
@@ -3626,19 +3819,20 @@ var WorkerImpl = class {
3626
3819
  await this.dispatcher.dispatchMessage(msg);
3627
3820
  } catch (err) {
3628
3821
  if (err instanceof NagiFlowSnapshotGoneError) {
3629
- this.deps.emitLog({
3630
- level: "warn",
3631
- msg: "worker.dispatch: flow snapshot gone \u2014 nacking",
3632
- attrs: {
3633
- runId: err.runId,
3634
- flowId: err.flowId,
3635
- pinnedHash: err.pinnedHash,
3636
- currentHash: err.currentHash
3637
- }
3638
- });
3639
3822
  try {
3640
- await this.deps.queue.nack(msg.receipt);
3641
- } catch {
3823
+ await this.handleSnapshotGone(msg, err);
3824
+ } catch (handleErr) {
3825
+ this.deps.emitLog({
3826
+ level: "error",
3827
+ msg: "worker.dispatch: snapshot-gone handling failed",
3828
+ attrs: { runId: err.runId, error: String(handleErr) }
3829
+ });
3830
+ try {
3831
+ await this.deps.queue.nack(msg.receipt, {
3832
+ delayMs: SNAPSHOT_GONE_FALLBACK_NACK_DELAY_MS
3833
+ });
3834
+ } catch {
3835
+ }
3642
3836
  }
3643
3837
  return;
3644
3838
  }
@@ -3653,6 +3847,58 @@ var WorkerImpl = class {
3653
3847
  }
3654
3848
  }
3655
3849
  }
3850
+ // A snapshot-gone message is retried (nack, delayed) only while the policy
3851
+ // says a frozen-version worker might still claim it; past that budget the
3852
+ // run is terminally failed with the snapshot-gone error and the message
3853
+ // acked, so poison messages cannot outlive the deploy that orphaned them.
3854
+ // (Terminal runs never reach here — dispatchMessage acks them itself.)
3855
+ async handleSnapshotGone(msg, err) {
3856
+ const attrs = {
3857
+ runId: err.runId,
3858
+ flowId: err.flowId,
3859
+ pinnedHash: err.pinnedHash,
3860
+ currentHash: err.currentHash,
3861
+ readCount: msg.readCount
3862
+ };
3863
+ const disposition = this.snapshotGonePolicy(msg.readCount);
3864
+ if (disposition.action === "retry") {
3865
+ this.deps.emitLog({
3866
+ level: "warn",
3867
+ msg: "worker.dispatch: flow snapshot gone \u2014 nacking for a frozen-version worker",
3868
+ attrs
3869
+ });
3870
+ try {
3871
+ await this.deps.queue.nack(msg.receipt, {
3872
+ delayMs: disposition.delayMs
3873
+ });
3874
+ } catch {
3875
+ }
3876
+ return;
3877
+ }
3878
+ this.deps.emitLog({
3879
+ level: "error",
3880
+ msg: "worker.dispatch: flow snapshot gone \u2014 redelivery budget exhausted, failing run",
3881
+ attrs
3882
+ });
3883
+ const serialized = serializeError(err);
3884
+ await this.deps.store.appendFact(
3885
+ msg.runId,
3886
+ Facts.flowFailed(msg.runId, serialized, this.deps.clock.now())
3887
+ );
3888
+ try {
3889
+ await this.dispatcher.propagateToParent(msg.runId, {
3890
+ kind: "failed",
3891
+ error: serialized
3892
+ });
3893
+ } catch (propagateErr) {
3894
+ this.deps.emitLog({
3895
+ level: "warn",
3896
+ msg: "worker.dispatch: snapshot-gone fail could not propagate to parent",
3897
+ attrs: { ...attrs, error: String(propagateErr) }
3898
+ });
3899
+ }
3900
+ await this.deps.queue.ack(msg.receipt);
3901
+ }
3656
3902
  async drain() {
3657
3903
  while (this.inFlight > 0) {
3658
3904
  await this.deps.clock.sleep(50);
@@ -3898,7 +4144,8 @@ async function nagiImpl(config) {
3898
4144
  // a single required config here so the dispatch internals never re-check it.
3899
4145
  heartbeat: {
3900
4146
  intervalMs: config.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
3901
- leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS
4147
+ leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS,
4148
+ holdWarnMs: config.leaseHoldWarnMs ?? DEFAULT_LEASE_HOLD_WARN_MS
3902
4149
  },
3903
4150
  ...compact({
3904
4151
  hooks: config.hooks,
@@ -3999,7 +4246,7 @@ async function nagiImpl(config) {
3999
4246
  if (transition.kind === "dispatch") {
4000
4247
  const txQueue = bindQueueToTx(config.queue, opts.tx);
4001
4248
  for (const stepId of transition.runnable) {
4002
- await txQueue.enqueue(runId, stepId);
4249
+ await txQueue.enqueue(runId, stepId, { flowId: flow2.id });
4003
4250
  }
4004
4251
  }
4005
4252
  }
@@ -4087,6 +4334,14 @@ async function nagiImpl(config) {
4087
4334
  async describe(runId) {
4088
4335
  return config.store.describe(runId);
4089
4336
  },
4337
+ async inspectQueue(runId) {
4338
+ if (config.queue.inspect === void 0) {
4339
+ throw new NagiRuntimeError(
4340
+ "inspectQueue: the configured queue adapter does not implement inspect()."
4341
+ );
4342
+ }
4343
+ return config.queue.inspect(runId);
4344
+ },
4090
4345
  async queryRuns(opts = {}) {
4091
4346
  if (opts.latest === true) {
4092
4347
  if (opts.limit !== void 0 || opts.cursor !== void 0) {
@@ -4226,6 +4481,6 @@ function bindQueueToTx(queue, tx) {
4226
4481
  return queue;
4227
4482
  }
4228
4483
 
4229
- export { DEFAULT_REAPER_INTERVAL_MS, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, RunId, attemptOf, canonicalize, decideExpiredLeaseAction, decideSignal, decideTimeout, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
4484
+ export { DEFAULT_REAPER_INTERVAL_MS, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, RunId, attemptOf, canonicalize, decideExpiredLeaseAction, decideSignal, decideTimeout, defaultSnapshotGonePolicy, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
4230
4485
  //# sourceMappingURL=index.js.map
4231
4486
  //# sourceMappingURL=index.js.map