@nagi-js/core 0.1.1-rc.16 → 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;
@@ -856,6 +866,24 @@ var NagiCanceledError = class extends Error {
856
866
  };
857
867
  }
858
868
  };
869
+ var NagiSignalTimeoutError = class extends Error {
870
+ runId;
871
+ stepId;
872
+ fireAt;
873
+ constructor({
874
+ runId,
875
+ stepId,
876
+ fireAt
877
+ }) {
878
+ super(
879
+ `Signal step "${stepId}" (run ${runId}) timed out \u2014 no signal arrived before its deadline ${fireAt.toISOString()}.`
880
+ );
881
+ this.name = "NagiSignalTimeoutError";
882
+ this.runId = runId;
883
+ this.stepId = stepId;
884
+ this.fireAt = fireAt;
885
+ }
886
+ };
859
887
  var NagiFlowSnapshotGoneError = class extends Error {
860
888
  runId;
861
889
  flowId;
@@ -1149,6 +1177,19 @@ function decideSignal(args) {
1149
1177
  result: { tag: "buffered" }
1150
1178
  };
1151
1179
  }
1180
+ function decideTimeout(args) {
1181
+ const { runState, stepId, fireAt, at } = args;
1182
+ const step = stepStateOf(runState, stepId);
1183
+ if (step.tag !== "awaitingSignal") return { kind: "noop" };
1184
+ const error = serializeError(
1185
+ new NagiSignalTimeoutError({ runId: runState.runId, stepId, fireAt })
1186
+ );
1187
+ return {
1188
+ kind: "fail",
1189
+ attempt: step.attempt,
1190
+ fact: Facts.stepFailed(runState.runId, stepId, step.attempt, error, at)
1191
+ };
1192
+ }
1152
1193
  function makeSignals(deps) {
1153
1194
  const { dispatcher, store, clock, registry, hooks, flowHooks, emitLog } = deps;
1154
1195
  async function signal(runId, signalName, payload) {
@@ -1402,15 +1443,39 @@ var InMemoryStore = class {
1402
1443
  globalFacts = [];
1403
1444
  activeByKey = /* @__PURE__ */ new Map();
1404
1445
  keyByActiveRun = /* @__PURE__ */ new Map();
1446
+ // Kept past terminal facts so a reopened run can re-take its slot.
1447
+ slotByRun = /* @__PURE__ */ new Map();
1405
1448
  childrenByParent = /* @__PURE__ */ new Map();
1406
1449
  summaries = /* @__PURE__ */ new Map();
1407
1450
  streamHub = new InMemoryStreamHub();
1451
+ // Durable signal-timeout deadlines, keyed `${runId}::${stepId}` → fire_at.
1452
+ // The Postgres analogue is the nagi.timer table; this is its in-memory twin
1453
+ // (distinct from the InMemoryClock's setTimeout-based scheduler timers).
1454
+ signalTimers = /* @__PURE__ */ new Map();
1408
1455
  leaseMs;
1409
1456
  constructor(opts = {}) {
1410
1457
  this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
1411
1458
  }
1412
1459
  async appendFact(runId, fact) {
1413
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
+ }
1414
1479
  list.push(fact);
1415
1480
  this.facts.set(runId, list);
1416
1481
  switch (fact.kind) {
@@ -1447,6 +1512,7 @@ var InMemoryStore = class {
1447
1512
  for (const key of this.leases.keys()) {
1448
1513
  if (key.startsWith(leasePrefix)) this.leases.delete(key);
1449
1514
  }
1515
+ this.signalTimers.delete(`${runId}::${fact.stepId}`);
1450
1516
  }
1451
1517
  }
1452
1518
  async tryStartRun(runId, fact, concurrency) {
@@ -1469,6 +1535,7 @@ var InMemoryStore = class {
1469
1535
  }
1470
1536
  this.activeByKey.set(slot, runId);
1471
1537
  this.keyByActiveRun.set(runId, slot);
1538
+ this.slotByRun.set(runId, slot);
1472
1539
  }
1473
1540
  this.facts.set(runId, [fact]);
1474
1541
  const parentRunId = fact.parent?.runId;
@@ -1577,7 +1644,8 @@ var InMemoryStore = class {
1577
1644
  );
1578
1645
  await queue.enqueue(c.runId, c.stepId, {
1579
1646
  attempt: decision.nextAttempt,
1580
- delayMs: decision.backoffMs
1647
+ delayMs: decision.backoffMs,
1648
+ ...state?.flowId !== void 0 ? { flowId: state.flowId } : {}
1581
1649
  });
1582
1650
  reaped.push({
1583
1651
  runId: c.runId,
@@ -1604,9 +1672,44 @@ var InMemoryStore = class {
1604
1672
  case "deliver":
1605
1673
  await this.appendFact(runId, decision.received);
1606
1674
  await this.appendFact(runId, decision.completed);
1675
+ this.signalTimers.delete(`${runId}::${stepId}`);
1607
1676
  return decision.result;
1608
1677
  }
1609
1678
  }
1679
+ async upsertTimer(runId, stepId, fireAt) {
1680
+ const key = `${runId}::${stepId}`;
1681
+ if (!this.signalTimers.has(key)) this.signalTimers.set(key, fireAt);
1682
+ }
1683
+ async sweepSignalTimeouts(args) {
1684
+ const { now, limit = 100 } = args;
1685
+ const timedOut = [];
1686
+ const due = [];
1687
+ for (const [key, fireAt] of this.signalTimers) {
1688
+ if (due.length >= limit) break;
1689
+ if (fireAt > now) continue;
1690
+ const sep = key.indexOf("::");
1691
+ due.push({
1692
+ key,
1693
+ runId: key.slice(0, sep),
1694
+ stepId: key.slice(sep + 2)
1695
+ });
1696
+ }
1697
+ for (const { key, runId, stepId } of due) {
1698
+ const fireAt = this.signalTimers.get(key);
1699
+ if (fireAt === void 0) continue;
1700
+ const runState = foldRun(runId, this.facts.get(runId) ?? []);
1701
+ const decision = decideTimeout({ runState, stepId, fireAt, at: now });
1702
+ this.signalTimers.delete(key);
1703
+ if (decision.kind === "noop") continue;
1704
+ await this.appendFact(runId, decision.fact);
1705
+ const leasePrefix = `${runId}::${stepId}::`;
1706
+ for (const k of this.leases.keys()) {
1707
+ if (k.startsWith(leasePrefix)) this.leases.delete(k);
1708
+ }
1709
+ timedOut.push({ runId, stepId, attempt: decision.attempt, fireAt });
1710
+ }
1711
+ return timedOut;
1712
+ }
1610
1713
  async recordOnce(runId, stepId, scope, value) {
1611
1714
  this.onces.set(`${runId}::${stepId}::${scope}`, value);
1612
1715
  }
@@ -1685,7 +1788,7 @@ var InMemoryStore = class {
1685
1788
  let error;
1686
1789
  let canceledByRunId;
1687
1790
  let concurrencyKey;
1688
- for (let i = factList.length - 1; i >= 0; i--) {
1791
+ for (let i = isTerminalRun(state) ? factList.length - 1 : -1; i >= 0; i--) {
1689
1792
  const f = factList[i];
1690
1793
  if (f === void 0) continue;
1691
1794
  if (f.kind === "flow.completed") {
@@ -1856,7 +1959,7 @@ function summarize(runId, facts) {
1856
1959
  if (first === void 0 || first.kind !== "flow.started") return null;
1857
1960
  const projected = foldRun(runId, facts);
1858
1961
  let completedAt = null;
1859
- for (let i = facts.length - 1; i >= 0; i--) {
1962
+ for (let i = isTerminalRun(projected) ? facts.length - 1 : -1; i >= 0; i--) {
1860
1963
  const f = facts[i];
1861
1964
  if (f === void 0) continue;
1862
1965
  if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
@@ -1935,8 +2038,10 @@ var InMemoryQueue = class {
1935
2038
  stepId,
1936
2039
  payload: opts?.payload ?? null,
1937
2040
  attempt: opts?.attempt ?? 1,
2041
+ readCount: 0,
1938
2042
  enqueuedAt: now,
1939
- visibleAt: now + (opts?.delayMs ?? 0)
2043
+ visibleAt: now + (opts?.delayMs ?? 0),
2044
+ ...opts?.flowId !== void 0 ? { flowId: opts.flowId } : {}
1940
2045
  };
1941
2046
  this.pending.push(item);
1942
2047
  }
@@ -1947,11 +2052,15 @@ var InMemoryQueue = class {
1947
2052
  const item = this.pending[i];
1948
2053
  if (item === void 0) continue;
1949
2054
  if (item.visibleAt > now) continue;
1950
- const next = { ...item, visibleAt: now + this.leaseMs };
2055
+ const delivered = {
2056
+ ...item,
2057
+ readCount: item.readCount + 1,
2058
+ visibleAt: now + this.leaseMs
2059
+ };
1951
2060
  this.pending.splice(i, 1);
1952
2061
  i--;
1953
- this.leased.set(item.receipt, next);
1954
- claimed.push(item);
2062
+ this.leased.set(item.receipt, delivered);
2063
+ claimed.push(delivered);
1955
2064
  }
1956
2065
  return claimed;
1957
2066
  }
@@ -1973,6 +2082,15 @@ var InMemoryQueue = class {
1973
2082
  if (!item) return;
1974
2083
  this.leased.set(receipt, { ...item, visibleAt: Date.now() + leaseMs });
1975
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
+ }
1976
2094
  };
1977
2095
  var InMemoryClock = class {
1978
2096
  timers = /* @__PURE__ */ new Map();
@@ -2360,6 +2478,7 @@ function startCancelWatcher(args) {
2360
2478
  }
2361
2479
  var DEFAULT_HEARTBEAT_LEASE_MS = 12e4;
2362
2480
  var DEFAULT_HEARTBEAT_INTERVAL_MS = 4e4;
2481
+ var DEFAULT_LEASE_HOLD_WARN_MS = 3e5;
2363
2482
  function startHeartbeat(args) {
2364
2483
  const {
2365
2484
  queue,
@@ -2370,13 +2489,28 @@ function startHeartbeat(args) {
2370
2489
  receipt,
2371
2490
  intervalMs,
2372
2491
  leaseMs,
2492
+ holdWarnMs,
2373
2493
  emitLog
2374
2494
  } = args;
2375
2495
  let stopped = false;
2376
2496
  let timer;
2497
+ const startedAtMs = Date.now();
2498
+ let warnedCrossings = 0;
2377
2499
  const schedule = () => {
2378
2500
  timer = setTimeout(() => {
2379
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
+ }
2380
2514
  await Promise.all([
2381
2515
  queue.extend(receipt, leaseMs).catch((err) => {
2382
2516
  emitLog({
@@ -2418,7 +2552,7 @@ function classifyFailure(args) {
2418
2552
  includeError: isAbort
2419
2553
  };
2420
2554
  }
2421
- const cancel = findNagiCanceledError(err);
2555
+ const cancel = findInCauseChain(err, NagiCanceledError);
2422
2556
  if (cancel !== void 0) {
2423
2557
  return {
2424
2558
  tag: "flowCanceled",
@@ -2426,16 +2560,19 @@ function classifyFailure(args) {
2426
2560
  concurrencyKey: cancel.concurrencyKey
2427
2561
  };
2428
2562
  }
2563
+ if (findInCauseChain(err, NagiNonRetryableError) !== void 0) {
2564
+ return { tag: "failed" };
2565
+ }
2429
2566
  if (attempt < policy.maxAttempts && retryAllows(policy, err)) {
2430
2567
  return { tag: "retry", delayMs: computeBackoff(policy, attempt) };
2431
2568
  }
2432
2569
  return { tag: "failed" };
2433
2570
  }
2434
- function findNagiCanceledError(err) {
2571
+ function findInCauseChain(err, ctor) {
2435
2572
  let cursor = err;
2436
2573
  const seen = /* @__PURE__ */ new Set();
2437
2574
  while (cursor instanceof Error && !seen.has(cursor)) {
2438
- if (cursor instanceof NagiCanceledError) return cursor;
2575
+ if (cursor instanceof ctor) return cursor;
2439
2576
  seen.add(cursor);
2440
2577
  cursor = cursor.cause;
2441
2578
  }
@@ -2506,12 +2643,26 @@ function makeMessage(deps, hooks, progression) {
2506
2643
  const { advance } = progression;
2507
2644
  async function dispatchMessage(message) {
2508
2645
  const { queue } = deps;
2509
- 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
+ }
2510
2656
  const admission = await admit({ flow: flow2, message });
2511
2657
  if (admission.tag === "skip") {
2512
2658
  await queue.ack(message.receipt);
2513
2659
  return;
2514
2660
  }
2661
+ if (admission.tag === "recover") {
2662
+ await advance(message.runId);
2663
+ await queue.ack(message.receipt);
2664
+ return;
2665
+ }
2515
2666
  const { def, state } = admission;
2516
2667
  await recordStarted({ flow: flow2, message, def, state });
2517
2668
  const startedAt = Date.now();
@@ -2524,6 +2675,7 @@ function makeMessage(deps, hooks, progression) {
2524
2675
  receipt: message.receipt,
2525
2676
  intervalMs: deps.heartbeat.intervalMs,
2526
2677
  leaseMs: deps.heartbeat.leaseMs,
2678
+ holdWarnMs: deps.heartbeat.holdWarnMs,
2527
2679
  emitLog: deps.emitLog
2528
2680
  });
2529
2681
  let outcome;
@@ -2534,8 +2686,8 @@ function makeMessage(deps, hooks, progression) {
2534
2686
  } finally {
2535
2687
  heartbeat.stop();
2536
2688
  }
2537
- await queue.ack(message.receipt);
2538
2689
  await interpret({ flow: flow2, message, def, startedAt, outcome });
2690
+ await queue.ack(message.receipt);
2539
2691
  }
2540
2692
  async function admit(args) {
2541
2693
  const { flow: flow2, message } = args;
@@ -2553,7 +2705,7 @@ function makeMessage(deps, hooks, progression) {
2553
2705
  if (preState.phase.tag === "canceled") return { tag: "skip" };
2554
2706
  const preStep = stepStateOf(preState, stepId);
2555
2707
  if (preStep.tag === "completed" || preStep.tag === "failed" || preStep.tag === "skipped") {
2556
- return { tag: "skip" };
2708
+ return isTerminalRun(preState) ? { tag: "skip" } : { tag: "recover" };
2557
2709
  }
2558
2710
  const claim = await store.claimStep(runId, stepId, attempt);
2559
2711
  if (claim === null) return { tag: "skip" };
@@ -2564,10 +2716,18 @@ function makeMessage(deps, hooks, progression) {
2564
2716
  const { store, clock } = deps;
2565
2717
  const { runId, stepId, attempt } = message;
2566
2718
  const handler = handlerDef(def);
2719
+ const startedAt = clock.now();
2567
2720
  await store.appendFact(
2568
2721
  runId,
2569
- Facts.stepStarted(runId, stepId, attempt, def.kind, clock.now())
2722
+ Facts.stepStarted(runId, stepId, attempt, def.kind, startedAt)
2570
2723
  );
2724
+ if (def.kind === "signal" && typeof def.timeoutMs === "number") {
2725
+ await store.upsertTimer(
2726
+ runId,
2727
+ stepId,
2728
+ new Date(startedAt.getTime() + def.timeoutMs)
2729
+ );
2730
+ }
2571
2731
  const startCarriesInput = def.kind === "task" || def.kind === "activity" || def.kind === "streaming" || def.kind === "subflow";
2572
2732
  const input = startCarriesInput ? state.input : null;
2573
2733
  await fireStepLifecycle(
@@ -2882,7 +3042,8 @@ function makeMessage(deps, hooks, progression) {
2882
3042
  );
2883
3043
  await queue.enqueue(runId, stepId, {
2884
3044
  attempt: attempt + 1,
2885
- delayMs: outcome.delayMs
3045
+ delayMs: outcome.delayMs,
3046
+ flowId: flow2.id
2886
3047
  });
2887
3048
  return { tag: "parked" };
2888
3049
  }
@@ -2983,7 +3144,8 @@ function makeProgression(deps, hooks) {
2983
3144
  return;
2984
3145
  case "dispatch":
2985
3146
  await recordSkips(runId, t.skip);
2986
- 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 });
2987
3149
  return;
2988
3150
  case "skip":
2989
3151
  await recordSkips(runId, t.skip);
@@ -3140,10 +3302,44 @@ function makeDispatcher(deps) {
3140
3302
  const hooks = makeHooks(deps);
3141
3303
  const progression = makeProgression(deps, hooks);
3142
3304
  const message = makeMessage(deps, hooks, progression);
3305
+ async function sweepTimers(now) {
3306
+ const timedOut = await deps.store.sweepSignalTimeouts({ now });
3307
+ for (const { runId, stepId, attempt, fireAt } of timedOut) {
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
+ });
3334
+ }
3335
+ }
3336
+ return timedOut.length;
3337
+ }
3143
3338
  return {
3144
3339
  dispatchMessage: message.dispatchMessage,
3145
3340
  advance: progression.advance,
3146
- propagateToParent: progression.propagateToParent
3341
+ propagateToParent: progression.propagateToParent,
3342
+ sweepTimers
3147
3343
  };
3148
3344
  }
3149
3345
 
@@ -3444,6 +3640,17 @@ async function drainInline(dispatcher, queue) {
3444
3640
  // src/worker.ts
3445
3641
  var DEFAULT_CONCURRENCY = 4;
3446
3642
  var DEFAULT_POLL_INTERVAL_MS = 1e3;
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
+ };
3447
3654
  function makeWorker(deps, config) {
3448
3655
  return new WorkerImpl(deps, config);
3449
3656
  }
@@ -3454,6 +3661,10 @@ var WorkerImpl = class {
3454
3661
  this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
3455
3662
  this.signal = config?.signal;
3456
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;
3666
+ this.timerSweepIntervalMs = config?.timerSweepIntervalMs ?? DEFAULT_TIMER_SWEEP_INTERVAL_MS;
3667
+ this.lastTimerSweepAt = this.deps.clock.now().getTime();
3457
3668
  }
3458
3669
  deps;
3459
3670
  inFlight = 0;
@@ -3461,19 +3672,79 @@ var WorkerImpl = class {
3461
3672
  pollIntervalMs;
3462
3673
  signal;
3463
3674
  dispatcher;
3675
+ timerSweepIntervalMs;
3676
+ snapshotGonePolicy;
3677
+ maxPerFlow;
3678
+ inFlightByFlow = /* @__PURE__ */ new Map();
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.
3464
3713
  async run() {
3714
+ let dequeueFailures = 0;
3465
3715
  while (!this.aborted()) {
3716
+ await this.maybeSweepTimers();
3466
3717
  const slots = this.concurrency - this.inFlight;
3467
3718
  if (slots <= 0) {
3468
3719
  await this.sleep(50);
3469
3720
  continue;
3470
3721
  }
3471
- 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;
3472
3740
  if (messages.length === 0) {
3473
3741
  await this.sleep(this.pollIntervalMs);
3474
3742
  continue;
3475
3743
  }
3476
- 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
+ }
3477
3748
  }
3478
3749
  await this.drain();
3479
3750
  }
@@ -3491,22 +3762,55 @@ var WorkerImpl = class {
3491
3762
  batchSize: () => this.concurrency
3492
3763
  });
3493
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.
3494
3771
  async pump(opts) {
3495
3772
  let processed = 0;
3496
3773
  while (!this.aborted() && opts.shouldContinue(processed)) {
3497
3774
  const messages = await this.dequeue(opts.batchSize(processed));
3498
3775
  if (messages.length === 0) break;
3499
- await Promise.all(messages.map((m) => this.dispatchSafely(m)));
3500
- 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;
3501
3791
  }
3502
3792
  return { processed };
3503
3793
  }
3504
3794
  async dequeue(count) {
3505
3795
  return this.deps.queue.dequeue({ count: Math.max(1, count) });
3506
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
+ }
3507
3809
  fire(msg) {
3508
3810
  this.inFlight++;
3811
+ const release = this.trackFlow(msg);
3509
3812
  void this.dispatchSafely(msg).finally(() => {
3813
+ release();
3510
3814
  this.inFlight = Math.max(0, this.inFlight - 1);
3511
3815
  });
3512
3816
  }
@@ -3515,19 +3819,20 @@ var WorkerImpl = class {
3515
3819
  await this.dispatcher.dispatchMessage(msg);
3516
3820
  } catch (err) {
3517
3821
  if (err instanceof NagiFlowSnapshotGoneError) {
3518
- this.deps.emitLog({
3519
- level: "warn",
3520
- msg: "worker.dispatch: flow snapshot gone \u2014 nacking",
3521
- attrs: {
3522
- runId: err.runId,
3523
- flowId: err.flowId,
3524
- pinnedHash: err.pinnedHash,
3525
- currentHash: err.currentHash
3526
- }
3527
- });
3528
3822
  try {
3529
- await this.deps.queue.nack(msg.receipt);
3530
- } 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
+ }
3531
3836
  }
3532
3837
  return;
3533
3838
  }
@@ -3542,11 +3847,83 @@ var WorkerImpl = class {
3542
3847
  }
3543
3848
  }
3544
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
+ }
3545
3902
  async drain() {
3546
3903
  while (this.inFlight > 0) {
3547
3904
  await this.deps.clock.sleep(50);
3548
3905
  }
3549
3906
  }
3907
+ // Sweep elapsed signal timeouts on cadence. Runs inline in the dispatch loop
3908
+ // (not fired concurrently) so two sweeps never overlap; at 30s with a handful
3909
+ // of timers the cost is negligible. Errors are logged, never thrown — a failed
3910
+ // sweep must not kill the worker; the next tick retries.
3911
+ async maybeSweepTimers() {
3912
+ if (this.timerSweepIntervalMs <= 0) return;
3913
+ const now = this.deps.clock.now();
3914
+ if (now.getTime() - this.lastTimerSweepAt < this.timerSweepIntervalMs)
3915
+ return;
3916
+ this.lastTimerSweepAt = now.getTime();
3917
+ try {
3918
+ await this.dispatcher.sweepTimers(now);
3919
+ } catch (err) {
3920
+ this.deps.emitLog({
3921
+ level: "warn",
3922
+ msg: "worker: signal-timeout sweep failed",
3923
+ attrs: { error: String(err) }
3924
+ });
3925
+ }
3926
+ }
3550
3927
  aborted() {
3551
3928
  return this.signal?.aborted === true;
3552
3929
  }
@@ -3767,7 +4144,8 @@ async function nagiImpl(config) {
3767
4144
  // a single required config here so the dispatch internals never re-check it.
3768
4145
  heartbeat: {
3769
4146
  intervalMs: config.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
3770
- leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS
4147
+ leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS,
4148
+ holdWarnMs: config.leaseHoldWarnMs ?? DEFAULT_LEASE_HOLD_WARN_MS
3771
4149
  },
3772
4150
  ...compact({
3773
4151
  hooks: config.hooks,
@@ -3868,7 +4246,7 @@ async function nagiImpl(config) {
3868
4246
  if (transition.kind === "dispatch") {
3869
4247
  const txQueue = bindQueueToTx(config.queue, opts.tx);
3870
4248
  for (const stepId of transition.runnable) {
3871
- await txQueue.enqueue(runId, stepId);
4249
+ await txQueue.enqueue(runId, stepId, { flowId: flow2.id });
3872
4250
  }
3873
4251
  }
3874
4252
  }
@@ -3956,6 +4334,14 @@ async function nagiImpl(config) {
3956
4334
  async describe(runId) {
3957
4335
  return config.store.describe(runId);
3958
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
+ },
3959
4345
  async queryRuns(opts = {}) {
3960
4346
  if (opts.latest === true) {
3961
4347
  if (opts.limit !== void 0 || opts.cursor !== void 0) {
@@ -4095,6 +4481,6 @@ function bindQueueToTx(queue, tx) {
4095
4481
  return queue;
4096
4482
  }
4097
4483
 
4098
- export { DEFAULT_REAPER_INTERVAL_MS, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, RunId, attemptOf, canonicalize, decideExpiredLeaseAction, decideSignal, 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 };
4099
4485
  //# sourceMappingURL=index.js.map
4100
4486
  //# sourceMappingURL=index.js.map