@workflow/world-testing 5.0.5 → 5.0.6

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.
@@ -21819,6 +21819,16 @@ function getMaxEventsPerRun() {
21819
21819
  const maxEvents = envNumber2("WORKFLOW_MAX_EVENTS", DEFAULT_MAX_EVENTS_PER_RUN, { integer: true });
21820
21820
  return maxEvents > 0 ? maxEvents : DEFAULT_MAX_EVENTS_PER_RUN;
21821
21821
  }
21822
+ function isEventLimitExemptRun(run3) {
21823
+ const context2 = run3?.executionContext;
21824
+ if (context2 === null || typeof context2 !== "object")
21825
+ return false;
21826
+ const { workflowVm, snapshotThreshold } = context2;
21827
+ return workflowVm === "quickjs" && typeof snapshotThreshold === "number" && Number.isSafeInteger(snapshotThreshold) && snapshotThreshold > 0;
21828
+ }
21829
+ function getMaxEventsForRun(run3) {
21830
+ return isEventLimitExemptRun(run3) ? Number.MAX_SAFE_INTEGER : getMaxEventsPerRun();
21831
+ }
21822
21832
  function _resetEnvWarnCacheForTests() {
21823
21833
  warnedEnvValues2.clear();
21824
21834
  }
@@ -21834,6 +21844,8 @@ var init_env_config2 = __esm({
21834
21844
  __name(envFlag, "envFlag");
21835
21845
  DEFAULT_MAX_EVENTS_PER_RUN = 25e3;
21836
21846
  __name(getMaxEventsPerRun, "getMaxEventsPerRun");
21847
+ __name(isEventLimitExemptRun, "isEventLimitExemptRun");
21848
+ __name(getMaxEventsForRun, "getMaxEventsForRun");
21837
21849
  __name(_resetEnvWarnCacheForTests, "_resetEnvWarnCacheForTests");
21838
21850
  }
21839
21851
  });
@@ -22148,6 +22160,19 @@ var init_queue2 = __esm({
22148
22160
  * probe response. That lets the caller seal the workflow arguments without
22149
22161
  * a separate key lookup. Absent for probes issued for other reasons (CLI
22150
22162
  * health command, dashboard), in which case no key is returned.
22163
+ *
22164
+ * Deliberately not named `runId`: `runId` is the only required field of
22165
+ * `WorkflowInvokePayloadSchema`, and 4.x deployments parse queue payloads
22166
+ * with a union that tries the invoke schema before the health check. A
22167
+ * probe carrying `runId` is read there as "replay this run", which POSTs
22168
+ * `run_started` for a run that does not exist yet (404) and retries the
22169
+ * delivery, so the probe never answers.
22170
+ */
22171
+ probeRunId: external_exports2.string().optional(),
22172
+ /**
22173
+ * Legacy spelling of {@link probeRunId}, sent by 5.x callers released
22174
+ * before the rename. Accepted so those callers still get a public key
22175
+ * back from this deployment; never sent.
22151
22176
  */
22152
22177
  runId: external_exports2.string().optional()
22153
22178
  }));
@@ -22926,11 +22951,13 @@ __export(dist_exports, {
22926
22951
  eventIdToSlot: () => eventIdToSlot,
22927
22952
  getEventDataPayloadField: () => getEventDataPayloadField,
22928
22953
  getEventDataRefFields: () => getEventDataRefFields,
22954
+ getMaxEventsForRun: () => getMaxEventsForRun,
22929
22955
  getMaxEventsPerRun: () => getMaxEventsPerRun,
22930
22956
  getQueueTopicPrefix: () => getQueueTopicPrefix2,
22931
22957
  getRunQueueNamespace: () => getRunQueueNamespace,
22932
22958
  isChildEntityCreationEvent: () => isChildEntityCreationEvent,
22933
22959
  isChildEntityCreationEventType: () => isChildEntityCreationEventType,
22960
+ isEventLimitExemptRun: () => isEventLimitExemptRun,
22934
22961
  isHookEventRequiringExistence: () => isHookEventRequiringExistence,
22935
22962
  isHookLifecycleEventType: () => isHookLifecycleEventType,
22936
22963
  isLegacySpecVersion: () => isLegacySpecVersion2,
@@ -23042,7 +23069,10 @@ function buildFramedDetails2(hint3, slug) {
23042
23069
  out.push({ label: "docs", value: `${BASE_URL2}/${slug}` });
23043
23070
  return out;
23044
23071
  }
23045
- var BASE_URL2, ERROR_SLUGS2, WorkflowError2, WorkflowWorldError2, WorkflowRunFailedError2, WorkflowRunNotCompletedError2, WorkflowRuntimeError2, CorruptedEventLogError, ReplayDivergenceError, MaxEventsExceededError, RuntimeDecryptionError2, SerializationError2, StepNotRegisteredError2, WorkflowNotRegisteredError2, WorkflowDeploymentMismatchError, WorkflowRunNotFoundError2, HookConflictError2, HookForceClaimedError2, HookNotFoundError2, EntityConflictError2, RunExpiredError2, StreamError2, StreamExpiredError2, TooEarlyError, ThrottleError2, PreconditionFailedError, IN_BAND_SUPERSEDED_CODE, InBandSupersededError, WorkflowRunCancelledError2, RunNotSupportedError, FatalError2, RetryableError2, FATAL_ERROR_KEY2, RETRYABLE_ERROR_KEY2, HOOK_CONFLICT_ERROR_KEY2, HOOK_FORCE_CLAIMED_ERROR_KEY2, RUNTIME_DECRYPTION_ERROR_KEY2, STREAM_ERROR_KEY2;
23072
+ function formatErrorMessageWithDetails(title, details) {
23073
+ return appendFramedDetails2(title, buildFramedDetails2(details.hint, details.slug));
23074
+ }
23075
+ var BASE_URL2, QUICKJS_SNAPSHOT_REMEDIATION, ERROR_SLUGS2, WorkflowError2, WorkflowWorldError2, WorkflowRunFailedError2, WorkflowRunNotCompletedError2, WorkflowRuntimeError2, CorruptedEventLogError, ReplayDivergenceError, MaxEventsExceededError, RuntimeDecryptionError2, SerializationError2, StepNotRegisteredError2, WorkflowNotRegisteredError2, WorkflowDeploymentMismatchError, WorkflowRunNotFoundError2, HookConflictError2, HookForceClaimedError2, HookNotFoundError2, EntityConflictError2, RunExpiredError2, StreamError2, StreamExpiredError2, TooEarlyError, ThrottleError2, PreconditionFailedError, IN_BAND_SUPERSEDED_CODE, InBandSupersededError, WorkflowRunCancelledError2, RunNotSupportedError, FatalError2, RetryableError2, FATAL_ERROR_KEY2, RETRYABLE_ERROR_KEY2, HOOK_CONFLICT_ERROR_KEY2, HOOK_FORCE_CLAIMED_ERROR_KEY2, RUNTIME_DECRYPTION_ERROR_KEY2, STREAM_ERROR_KEY2;
23046
23076
  var init_dist7 = __esm({
23047
23077
  "../errors/dist/index.js"() {
23048
23078
  "use strict";
@@ -23053,6 +23083,8 @@ var init_dist7 = __esm({
23053
23083
  __name(isError2, "isError");
23054
23084
  __name(appendFramedDetails2, "appendFramedDetails");
23055
23085
  __name(buildFramedDetails2, "buildFramedDetails");
23086
+ __name(formatErrorMessageWithDetails, "formatErrorMessageWithDetails");
23087
+ QUICKJS_SNAPSHOT_REMEDIATION = "Run long-running workflows on the QuickJS VM with snapshotting by setting WORKFLOW_VM=quickjs in the environment that starts runs. Snapshotted QuickJS runs resume without replaying the full event log and are exempt from the default per-run event limit. Runs keep the VM they started with.";
23056
23088
  ERROR_SLUGS2 = {
23057
23089
  NODE_JS_MODULE_IN_WORKFLOW: "node-js-module-in-workflow",
23058
23090
  START_INVALID_WORKFLOW_FUNCTION: "start-invalid-workflow-function",
@@ -23068,7 +23100,9 @@ var init_dist7 = __esm({
23068
23100
  STEP_NOT_REGISTERED: "step-not-registered",
23069
23101
  WORKFLOW_NOT_REGISTERED: "workflow-not-registered",
23070
23102
  RUNTIME_DECRYPTION_FAILED: "runtime-decryption-failed",
23071
- DEPLOYMENT_MISMATCH: "deployment-mismatch"
23103
+ DEPLOYMENT_MISMATCH: "deployment-mismatch",
23104
+ MAX_EVENTS_EXCEEDED: "max-events-exceeded",
23105
+ REPLAY_TIMEOUT: "replay-timeout"
23072
23106
  };
23073
23107
  WorkflowError2 = class extends Error {
23074
23108
  static {
@@ -23225,7 +23259,10 @@ Caused by: ${options.cause.stack}`;
23225
23259
  eventCount;
23226
23260
  limit;
23227
23261
  constructor(eventCount, limit, options) {
23228
- super(`Workflow exceeded the maximum of ${limit} events per run`, options);
23262
+ super(formatErrorMessageWithDetails(`Workflow exceeded the maximum of ${limit} events per run`, {
23263
+ hint: `${QUICKJS_SNAPSHOT_REMEDIATION} Alternatively, split the work into child workflows.`,
23264
+ slug: options?.slug ?? ERROR_SLUGS2.MAX_EVENTS_EXCEEDED
23265
+ }), { cause: options?.cause });
23229
23266
  this.name = "MaxEventsExceededError";
23230
23267
  this.eventCount = eventCount;
23231
23268
  this.limit = limit;
@@ -58053,8 +58090,64 @@ function createEventsStorage(basedir, tag) {
58053
58090
  getSortKey: eventSortKey,
58054
58091
  getSortKeyFromFileId: /* @__PURE__ */ __name((fileId) => eventSortKeyFromFileId(runId, fileId), "getSortKeyFromFileId")
58055
58092
  }), "queryRunEvents");
58093
+ const missingRunCreatedError = /* @__PURE__ */ __name((runId, reason) => new WorkflowWorldError2(`Cannot restore missing run_created for workflow run "${runId}": ${reason}`), "missingRunCreatedError");
58094
+ async function publishRunCreatedAtFirstSlot(event) {
58095
+ const eventId = slotToEventId(FIRST_EVENT_SLOT);
58096
+ const firstSlotEvent = event.eventId === eventId ? event : { ...event, eventId };
58097
+ const eventPath = taggedPath(basedir, runEntityDir("events", event.runId), `${event.runId}-${eventId}`, tag);
58098
+ const serializedEvent = JSON.stringify(firstSlotEvent, jsonReplacer, 2);
58099
+ if (await writeExclusive(eventPath, serializedEvent)) {
58100
+ notePublishedSlot(event.runId, eventId);
58101
+ rememberStoredEvent(firstSlotEvent, eventPath, serializedEvent);
58102
+ return true;
58103
+ }
58104
+ const occupant = await readJSONWithFallback(basedir, runEntityDir("events", event.runId), `${event.runId}-${eventId}`, ReadEventSchema, tag);
58105
+ if (occupant?.eventType === "run_created" && occupant.runId === event.runId) {
58106
+ notePublishedSlot(event.runId, eventId);
58107
+ return false;
58108
+ }
58109
+ throw missingRunCreatedError(event.runId, `event slot ${FIRST_EVENT_SLOT} is occupied by ${occupant ? `"${occupant.eventType}"` : "an unreadable event"}`);
58110
+ }
58111
+ __name(publishRunCreatedAtFirstSlot, "publishRunCreatedAtFirstSlot");
58112
+ async function restoreMissingRunCreated(run3) {
58113
+ const firstPage = await queryRunEvents(run3.runId, {
58114
+ limit: 1,
58115
+ sortOrder: "asc"
58116
+ });
58117
+ const first = firstPage.data[0];
58118
+ if (first) {
58119
+ if (first.eventType === "run_created" && first.runId === run3.runId) {
58120
+ return;
58121
+ }
58122
+ throw missingRunCreatedError(run3.runId, `the event log is not empty (its first event is "${first.eventType}")`);
58123
+ }
58124
+ if (run3.input === void 0) {
58125
+ throw missingRunCreatedError(run3.runId, "the original input is missing");
58126
+ }
58127
+ const eventId = slotToEventId(FIRST_EVENT_SLOT);
58128
+ const event = {
58129
+ eventType: "run_created",
58130
+ runId: run3.runId,
58131
+ eventId,
58132
+ createdAt: run3.createdAt,
58133
+ specVersion: run3.specVersion,
58134
+ eventData: {
58135
+ deploymentId: run3.deploymentId,
58136
+ workflowName: run3.workflowName,
58137
+ input: run3.input,
58138
+ executionContext: run3.executionContext,
58139
+ attributes: run3.attributes,
58140
+ encryptionPublicKey: run3.encryptionPublicKey
58141
+ }
58142
+ };
58143
+ if (await publishRunCreatedAtFirstSlot(event)) {
58144
+ console.warn(`[world-local] restored missing run_created for ${run3.runId} (creation was interrupted or is still in flight)`);
58145
+ }
58146
+ }
58147
+ __name(restoreMissingRunCreated, "restoreMissingRunCreated");
58056
58148
  const stepLocks = /* @__PURE__ */ new Map();
58057
58149
  const hookLocks = /* @__PURE__ */ new Map();
58150
+ const hookLockKey = /* @__PURE__ */ __name((runId, hookId) => tag ? `${runId}-${hookId}.hook.${tag}` : `${runId}-${hookId}.hook`, "hookLockKey");
58058
58151
  const storage = {
58059
58152
  clearCache,
58060
58153
  async create(runId, data3, params) {
@@ -58072,8 +58165,7 @@ function createEventsStorage(basedir, tag) {
58072
58165
  return withInProcessLock(stepLocks, lockKey, createImpl);
58073
58166
  }
58074
58167
  if (isHookLifecycleEventType(data3.eventType) && runId && data3.correlationId) {
58075
- const lockKey = tag ? `${runId}-${data3.correlationId}.hook.${tag}` : `${runId}-${data3.correlationId}.hook`;
58076
- return withInProcessLock(hookLocks, lockKey, createImpl);
58168
+ return withInProcessLock(hookLocks, hookLockKey(runId, data3.correlationId), createImpl);
58077
58169
  }
58078
58170
  return createImpl();
58079
58171
  async function createImpl() {
@@ -58097,6 +58189,7 @@ function createEventsStorage(basedir, tag) {
58097
58189
  }
58098
58190
  const effectiveSpecVersion = data3.specVersion ?? SPEC_VERSION_CURRENT2;
58099
58191
  let currentRun = null;
58192
+ let createdByResilientStart = false;
58100
58193
  const skipRunValidationEvents = ["step_completed", "step_retrying"];
58101
58194
  if (data3.eventType !== "run_created" && !skipRunValidationEvents.includes(data3.eventType)) {
58102
58195
  currentRun = await readJSONWithFallback(basedir, "runs", effectiveRunId, WorkflowRunSchema2, tag);
@@ -58149,14 +58242,27 @@ function createEventsStorage(basedir, tag) {
58149
58242
  encryptionPublicKey: runInputData.encryptionPublicKey
58150
58243
  }
58151
58244
  };
58152
- await storeEvent(runCreatedEvent);
58153
- currentRun = createdRun;
58245
+ const published = await publishRunCreatedAtFirstSlot(runCreatedEvent);
58246
+ currentRun = published ? createdRun : await readJSONWithFallback(basedir, "runs", effectiveRunId, WorkflowRunSchema2, tag);
58247
+ createdByResilientStart = true;
58154
58248
  } else {
58155
58249
  currentRun = await readJSONWithFallback(basedir, "runs", effectiveRunId, WorkflowRunSchema2, tag);
58156
58250
  }
58157
58251
  }
58158
58252
  }
58159
58253
  }
58254
+ if (currentRun?.status === "pending" && !createdByResilientStart && !requiresNewerWorld(currentRun.specVersion) && !isLegacySpecVersion2(currentRun.specVersion) && (data3.eventType === "run_started" || data3.eventType === "attr_set" || data3.eventType === "run_cancelled" || data3.eventType === "run_failed")) {
58255
+ if (data3.eventType === "run_cancelled" || data3.eventType === "run_failed") {
58256
+ try {
58257
+ await restoreMissingRunCreated(currentRun);
58258
+ } catch (error121) {
58259
+ const reason = error121 instanceof Error ? error121.message : String(error121);
58260
+ console.warn(`[world-local] could not restore missing run_created for ${currentRun.runId}: ${reason}`);
58261
+ }
58262
+ } else {
58263
+ await restoreMissingRunCreated(currentRun);
58264
+ }
58265
+ }
58160
58266
  eventId = await mintEventId(effectiveRunId);
58161
58267
  if (!currentRun && (data3.eventType === "run_failed" || data3.eventType === "attr_set" || data3.eventType === "run_started")) {
58162
58268
  throw new WorkflowRunNotFoundError2(effectiveRunId);
@@ -58184,7 +58290,7 @@ function createEventsStorage(basedir, tag) {
58184
58290
  return {
58185
58291
  event: stripEventDataRefs(stored, resolveData2),
58186
58292
  run: currentRun,
58187
- ...currentRun ? { maxEvents: getMaxEventsPerRun() } : {}
58293
+ ...currentRun ? { maxEvents: getMaxEventsForRun(currentRun) } : {}
58188
58294
  };
58189
58295
  }
58190
58296
  if (data3.eventType === "run_started") {
@@ -58378,7 +58484,7 @@ function createEventsStorage(basedir, tag) {
58378
58484
  if (params?.skipPreload) {
58379
58485
  return {
58380
58486
  run: currentRun,
58381
- maxEvents: getMaxEventsPerRun()
58487
+ maxEvents: getMaxEventsForRun(currentRun)
58382
58488
  };
58383
58489
  }
58384
58490
  const preloaded = await queryRunEvents(effectiveRunId, {
@@ -58389,7 +58495,7 @@ function createEventsStorage(basedir, tag) {
58389
58495
  events: preloaded.data,
58390
58496
  cursor: preloaded.cursor,
58391
58497
  hasMore: preloaded.hasMore,
58392
- maxEvents: getMaxEventsPerRun()
58498
+ maxEvents: getMaxEventsForRun(currentRun)
58393
58499
  };
58394
58500
  }
58395
58501
  const written = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
@@ -58709,7 +58815,7 @@ function createEventsStorage(basedir, tag) {
58709
58815
  tokenRetentionUntil: hookData.tokenRetentionUntil,
58710
58816
  ...claimedFrom && { claimedFrom }
58711
58817
  }), "claimContent");
58712
- const claimResult = await withHookTokenClaimLock(basedir, hookData.token, async (signal) => {
58818
+ const claimToken = /* @__PURE__ */ __name((lockedVictim) => withHookTokenClaimLock(basedir, hookData.token, async (signal) => {
58713
58819
  let existingClaim = await readHookTokenClaim(constraintPath);
58714
58820
  if (!existingClaim) {
58715
58821
  signal.throwIfAborted();
@@ -58729,6 +58835,9 @@ function createEventsStorage(basedir, tag) {
58729
58835
  if (hookData.force !== true || !existingClaim.hookId) {
58730
58836
  return { status: "conflict", claim: existingClaim };
58731
58837
  }
58838
+ if (existingClaim.runId !== lockedVictim?.runId || existingClaim.hookId !== lockedVictim?.hookId) {
58839
+ return { status: "victim-changed" };
58840
+ }
58732
58841
  signal.throwIfAborted();
58733
58842
  const victimRun = await readJSONWithFallback(basedir, "runs", existingClaim.runId, WorkflowRunSchema2, tag);
58734
58843
  const victimRunning = victimRun !== null && !isTerminalWorkflowRunStatus2(victimRun.status);
@@ -58823,7 +58932,18 @@ function createEventsStorage(basedir, tag) {
58823
58932
  assert3(await writeExclusive(constraintPath, claimContent()));
58824
58933
  }
58825
58934
  return { status: "claimed" };
58826
- });
58935
+ }), "claimToken");
58936
+ let claimResult;
58937
+ for (let attempt = 0; ; attempt++) {
58938
+ if (attempt === MAX_FORCE_CLAIM_VICTIM_RETRIES) {
58939
+ throw new WorkflowWorldError2(`Hook token holder kept changing during a forced claim of "${data3.correlationId}"`);
58940
+ }
58941
+ const holder = hookData.force === true ? await readHookTokenClaim(constraintPath) : null;
58942
+ const victim = holder?.hookId && !(holder.runId === effectiveRunId && holder.hookId === data3.correlationId) ? { runId: holder.runId, hookId: holder.hookId } : void 0;
58943
+ claimResult = victim ? await withInProcessLock(hookLocks, hookLockKey(victim.runId, victim.hookId), () => claimToken(victim)) : await claimToken();
58944
+ if (claimResult.status !== "victim-changed")
58945
+ break;
58946
+ }
58827
58947
  if (claimResult.status === "owned" && claimResult.claim.claimedFrom) {
58828
58948
  claimedFrom = claimResult.claim.claimedFrom;
58829
58949
  }
@@ -59054,6 +59174,14 @@ function createEventsStorage(basedir, tag) {
59054
59174
  notePublishedSlot(effectiveRunId, eventId);
59055
59175
  break;
59056
59176
  }
59177
+ if (data3.eventType === "run_created") {
59178
+ const slot = eventIdToSlot(eventId);
59179
+ const occupant = await readJSONWithFallback(basedir, runEntityDir("events", effectiveRunId), `${effectiveRunId}-${eventId}`, ReadEventSchema, tag);
59180
+ if (slot === FIRST_EVENT_SLOT && occupant?.eventType === "run_created" && occupant.runId === effectiveRunId) {
59181
+ break;
59182
+ }
59183
+ throw new WorkflowWorldError2(`Cannot publish run_created for workflow run "${effectiveRunId}": event slot ${slot ?? eventId} is occupied by ${occupant ? `"${occupant.eventType}"` : "an unreadable event"}`);
59184
+ }
59057
59185
  if (data3.eventType === "hook_received" && params?.resumeId) {
59058
59186
  const occupant = await readJSONWithFallback(basedir, runEntityDir("events", effectiveRunId), `${effectiveRunId}-${eventId}`, ReadEventSchema, tag);
59059
59187
  if (occupant && isResumeEvent(occupant, {
@@ -59124,8 +59252,9 @@ function createEventsStorage(basedir, tag) {
59124
59252
  hook,
59125
59253
  wait,
59126
59254
  ...stepCreatedLazily ? { stepCreated: true } : {},
59127
- // Per-run event ceiling (mirrors the Vercel World).
59128
- ...run3 ? { maxEvents: getMaxEventsPerRun() } : {}
59255
+ // Per-run event ceiling (mirrors the Vercel World, including the
59256
+ // QuickJS-snapshot exemption).
59257
+ ...run3 ? { maxEvents: getMaxEventsForRun(run3) } : {}
59129
59258
  };
59130
59259
  if (!eventPage)
59131
59260
  return result2;
@@ -59363,7 +59492,7 @@ function createEventsStorage(basedir, tag) {
59363
59492
  }), "list");
59364
59493
  return { ...storage, create: fencedCreate, list: list3 };
59365
59494
  }
59366
- var import_proper_lockfile3, DAY_MS, MAX_CACHED_EVENT_ENTRIES, HookRecoveryMarkerSchema, HookResumeClaimSchema, InBandCountSchema;
59495
+ var import_proper_lockfile3, DAY_MS, MAX_CACHED_EVENT_ENTRIES, MAX_FORCE_CLAIM_VICTIM_RETRIES, HookRecoveryMarkerSchema, HookResumeClaimSchema, InBandCountSchema;
59367
59496
  var init_events_storage = __esm({
59368
59497
  "../world-local/dist/storage/events-storage.js"() {
59369
59498
  "use strict";
@@ -59385,6 +59514,7 @@ var init_events_storage = __esm({
59385
59514
  init_runs_storage();
59386
59515
  DAY_MS = 24 * 60 * 60 * 1e3;
59387
59516
  MAX_CACHED_EVENT_ENTRIES = 1e3;
59517
+ MAX_FORCE_CLAIM_VICTIM_RETRIES = 100;
59388
59518
  __name(getHookRetentionLimitMs, "getHookRetentionLimitMs");
59389
59519
  HookRecoveryMarkerSchema = external_exports2.compile(external_exports2.object({
59390
59520
  eventId: external_exports2.string()
@@ -63440,7 +63570,7 @@ var version5;
63440
63570
  var init_version3 = __esm({
63441
63571
  "../world-vercel/dist/version.js"() {
63442
63572
  "use strict";
63443
- version5 = "5.2.2";
63573
+ version5 = "5.2.3";
63444
63574
  }
63445
63575
  });
63446
63576
 
@@ -79387,7 +79517,10 @@ async function createWorkflowRunEventInner(id, data3, params, config4) {
79387
79517
  throw new WorkflowWorldError2(validationError, { status: 400 });
79388
79518
  }
79389
79519
  }
79390
- const remoteRefBehavior = eventsNeedingResolve.has(data3.eventType) ? "resolve" : "lazy";
79520
+ const remoteRefBehavior = eventsNeedingResolve.has(data3.eventType) || // Concurrent hook reconciliation consumes the committed event directly.
79521
+ // Honor its explicit request for replay-ready metadata; other mutation
79522
+ // responses keep their existing lightweight entity-only behavior.
79523
+ data3.eventType === "hook_created" && params?.resolveData === "all" ? "resolve" : "lazy";
79391
79524
  const { payload, meta: meta5 } = splitEventDataForV4(data3);
79392
79525
  const input3 = {
79393
79526
  runId: id,
@@ -79432,18 +79565,18 @@ async function createWorkflowRunEventInner(id, data3, params, config4) {
79432
79565
  ...meta5
79433
79566
  };
79434
79567
  if (data3.eventType === "run_started" && !params?.skipPreload) {
79435
- const result2 = await createWorkflowRunStartedEventV4(input3, config4, params?.replayEventObserver);
79436
- const replayRun = reconstructRunFromReplayEvents(result2.events);
79568
+ const result3 = await createWorkflowRunStartedEventV4(input3, config4, params?.replayEventObserver);
79569
+ const replayRun = reconstructRunFromReplayEvents(result3.events);
79437
79570
  if (!replayRun) {
79438
79571
  throw new WorkflowWorldError2("v4 createEvent: run_started stream is missing lifecycle events", { code: "SCHEMA_VALIDATION" });
79439
79572
  }
79440
79573
  return {
79441
79574
  event: replayRun.event,
79442
79575
  run: replayRun.run,
79443
- events: result2.events,
79444
- cursor: result2.cursor,
79445
- hasMore: result2.hasMore,
79446
- maxEvents: result2.maxEvents
79576
+ events: result3.events,
79577
+ cursor: result3.cursor,
79578
+ hasMore: result3.hasMore,
79579
+ maxEvents: result3.maxEvents
79447
79580
  };
79448
79581
  }
79449
79582
  if (data3.eventType === "hook_received" && params?.preloadEvents === true && params.resumeId !== void 0 && params.resumePayloadDigest !== void 0) {
@@ -79463,7 +79596,8 @@ async function createWorkflowRunEventInner(id, data3, params, config4) {
79463
79596
  ...maxEvents !== void 0 ? { maxEvents } : {}
79464
79597
  };
79465
79598
  }
79466
- return createWorkflowRunEventV4(data3.eventType === "run_started" ? { ...input3, eventType: "run_started", skipPreload: true } : { ...input3, eventType: data3.eventType }, config4);
79599
+ const result2 = await createWorkflowRunEventV4(data3.eventType === "run_started" ? { ...input3, eventType: "run_started", skipPreload: true } : { ...input3, eventType: data3.eventType }, config4);
79600
+ return result2.event ? { ...result2, eventCursor: `eid:${result2.event.eventId}` } : result2;
79467
79601
  }
79468
79602
  function reconstructRunFromReplayEvents(events) {
79469
79603
  const runCreated = events.find((event) => event.eventType === "run_created");
@@ -81156,6 +81290,7 @@ function createWorld2(config4) {
81156
81290
  analytics: process.env.WORKFLOW_DISABLE_ANALYTICS_READS === "1" ? void 0 : createAnalytics(config4),
81157
81291
  ...instrumentObject2("world.streams", createStreamer2(config4)),
81158
81292
  createRunId,
81293
+ regionForRunId,
81159
81294
  describeRun,
81160
81295
  // Reports the environment this client's writes land in, so `start()` can
81161
81296
  // stamp it into the queue message and the consuming deployment can detect
@@ -81829,9 +81964,9 @@ var init_describe_error = __esm({
81829
81964
  CONTEXT_ERROR_HINT = "A workflow-only or step-only API was called from the wrong context. The error message includes the exact API and how to move the call.";
81830
81965
  RUNTIME_ERROR_HINT = "This is an internal workflow SDK error, not a bug in your code. If it keeps happening, please report it with the stack trace and the runId.";
81831
81966
  CORRUPTED_EVENT_LOG_HINT = "The workflow event log contains orphaned or mismatched events and cannot be replayed. This is an internal workflow SDK error; please report it with the runId.";
81832
- REPLAY_TIMEOUT_HINT = 'The workflow replay between step boundaries took too long. This bounds workflow-VM and event-log replay time only \u2014 step bodies (`"use step"` functions) are excluded. This usually means the event log is unusually large or the workflow function is doing heavy synchronous work in workflow code outside of step bodies. Override the default budget via the WORKFLOW_REPLAY_TIMEOUT_MS env var if needed.';
81967
+ REPLAY_TIMEOUT_HINT = `The workflow replay between step boundaries took too long. This bounds workflow-VM and event-log replay time only \u2014 step bodies (\`"use step"\` functions) are excluded. This usually means the event log is unusually large or the workflow function is doing heavy synchronous work in workflow code outside of step bodies. ${QUICKJS_SNAPSHOT_REMEDIATION} You can also override the default budget via the WORKFLOW_REPLAY_TIMEOUT_MS env var.`;
81833
81968
  MAX_DELIVERIES_HINT = "The workflow queue exceeded its max-delivery budget. This usually indicates a persistent runtime failure \u2014 check the most recent stack traces for the underlying cause.";
81834
- MAX_EVENTS_HINT = "The workflow exceeded the maximum number of events per run. This usually means unbounded work in the workflow function \u2014 e.g. a loop that keeps creating steps without terminating. Break long-running workflows into child workflows to stay under the limit.";
81969
+ MAX_EVENTS_HINT = `The workflow exceeded the maximum number of events per run. If the run is expected to be long-running: ${QUICKJS_SNAPSHOT_REMEDIATION} Otherwise, check for unbounded work in the workflow function (e.g. a loop that keeps creating steps without terminating), or split the work into child workflows.`;
81835
81970
  STREAM_ERROR_HINT = "Workflow stream infrastructure failed while reading or writing data. This is an SDK or backend failure, not an error in your workflow code; please retry the run and report persistent failures with the runId.";
81836
81971
  WORLD_CONTRACT_HINT = "The workflow backend returned data that violated the SDK contract. This is not retryable; please report it with the stack trace and runId.";
81837
81972
  DEPLOYMENT_MISMATCH_HINT = "The run was delivered to a deployment other than the deployment it is pinned to, and was stopped to protect against code-skew errors after the runtime failed to re-route it there. Verify that the run's deployment is still available and that queue callbacks route to it.";
@@ -89159,7 +89294,7 @@ var version6;
89159
89294
  var init_version4 = __esm({
89160
89295
  "../core/dist/version.js"() {
89161
89296
  "use strict";
89162
- version6 = "5.2.2";
89297
+ version6 = "5.2.3";
89163
89298
  }
89164
89299
  });
89165
89300
 
@@ -89398,9 +89533,10 @@ async function handleHealthCheckMessage(healthCheck3, worldSpecVersion) {
89398
89533
  const world = await getWorldLazy2();
89399
89534
  const streamName = getHealthCheckStreamName2(healthCheck3.correlationId);
89400
89535
  let encryptionPublicKey;
89401
- if (healthCheck3.runId) {
89536
+ const probeRunId = healthCheck3.probeRunId ?? healthCheck3.runId;
89537
+ if (probeRunId) {
89402
89538
  try {
89403
- const rawKey = await world.getEncryptionKeyForRun?.(healthCheck3.runId);
89539
+ const rawKey = await world.getEncryptionKeyForRun?.(probeRunId);
89404
89540
  if (rawKey) {
89405
89541
  encryptionPublicKey = bytesToBase642((await deriveRunKeyPair2(rawKey)).publicKey);
89406
89542
  }
@@ -90219,7 +90355,9 @@ async function resolveHookResumeInfo2(hook) {
90219
90355
  if (hook.resumeContext) {
90220
90356
  return { resumeContext: hook.resumeContext, source: "hook" };
90221
90357
  }
90222
- const run3 = await (await getWorldLazy2()).runs.get(hook.runId);
90358
+ const run3 = await (await getWorldLazy2()).runs.get(hook.runId, {
90359
+ resolveData: "none"
90360
+ });
90223
90361
  return {
90224
90362
  resumeContext: resumeContextFromRun2(run3),
90225
90363
  source: "run_fallback",
@@ -90228,7 +90366,7 @@ async function resolveHookResumeInfo2(hook) {
90228
90366
  }
90229
90367
  async function resolveHookEncryptionKey2(hook, info) {
90230
90368
  const world = await getWorldLazy2();
90231
- const rawKey = info.run ? await world.getEncryptionKeyForRun?.(info.run) : await world.getEncryptionKeyForRun?.(hook.runId, {
90369
+ const rawKey = await world.getEncryptionKeyForRun?.(hook.runId, {
90232
90370
  deploymentId: info.resumeContext.deploymentId
90233
90371
  });
90234
90372
  return rawKey ? await importKey2(rawKey) : void 0;
@@ -90244,7 +90382,7 @@ function withLazyMetadata2(raw) {
90244
90382
  const hydrate = /* @__PURE__ */ __name(async () => {
90245
90383
  const world = await getWorldLazy2();
90246
90384
  const info = await resolveHookResumeInfo2(raw);
90247
- const rawKey = info.run ? await world.getEncryptionKeyForRun?.(info.run) : await world.getEncryptionKeyForRun?.(raw.runId, {
90385
+ const rawKey = await world.getEncryptionKeyForRun?.(raw.runId, {
90248
90386
  deploymentId: info.resumeContext.deploymentId
90249
90387
  });
90250
90388
  encryptionKey = rawKey ? await deriveRunPayloadKeys2(rawKey) : void 0;
@@ -91628,7 +91766,10 @@ async function getForwardedWritableEncryptionKey2(runId, deploymentId, encryptio
91628
91766
  const world = await getWorldLazy2();
91629
91767
  if (!world.getEncryptionKeyForRun)
91630
91768
  return void 0;
91631
- const rawKey = deploymentId ? await world.getEncryptionKeyForRun(runId, { deploymentId }) : await world.getEncryptionKeyForRun(await world.runs.get(runId));
91769
+ const ownerDeploymentId = deploymentId ?? (await world.runs.get(runId, { resolveData: "none" })).deploymentId;
91770
+ const rawKey = await world.getEncryptionKeyForRun(runId, {
91771
+ deploymentId: ownerDeploymentId
91772
+ });
91632
91773
  return rawKey ? await importKey2(rawKey, ["encrypt"]) : void 0;
91633
91774
  }
91634
91775
  function lazyForwardedWritableEncryptionKey2(runId, deploymentId, encryptionPublicKey) {
@@ -98650,7 +98791,7 @@ function getSnapshotThresholdFromEnv2(env = process.env) {
98650
98791
  return parsed;
98651
98792
  }
98652
98793
  function getSnapshotThreshold(workflowRun) {
98653
- return getConfiguredSnapshotThreshold(workflowRun) ?? DEFAULT_QUICKJS_SNAPSHOT_THRESHOLD;
98794
+ return getConfiguredSnapshotThreshold(workflowRun) ?? DEFAULT_QUICKJS_SNAPSHOT_THRESHOLD2;
98654
98795
  }
98655
98796
  function getConfiguredSnapshotThreshold(workflowRun) {
98656
98797
  const fromRun = workflowRun.executionContext?.snapshotThreshold;
@@ -98664,7 +98805,12 @@ function getConfiguredSnapshotThreshold(workflowRun) {
98664
98805
  }
98665
98806
  function isSnapshotThresholdConfigured(workflowRun) {
98666
98807
  try {
98667
- return getConfiguredSnapshotThreshold(workflowRun) !== void 0;
98808
+ const configured = getConfiguredSnapshotThreshold(workflowRun);
98809
+ if (configured === void 0)
98810
+ return false;
98811
+ if (configured !== DEFAULT_QUICKJS_SNAPSHOT_THRESHOLD2)
98812
+ return true;
98813
+ return getSnapshotThresholdFromEnv2() !== void 0;
98668
98814
  } catch {
98669
98815
  return true;
98670
98816
  }
@@ -98681,7 +98827,7 @@ function isUnencryptedSnapshottingAllowed(env = process.env) {
98681
98827
  const raw = env.WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED;
98682
98828
  return raw === "1" || raw === "true";
98683
98829
  }
98684
- var WORKFLOW_VMS2, DEFAULT_QUICKJS_SNAPSHOT_THRESHOLD;
98830
+ var WORKFLOW_VMS2, DEFAULT_QUICKJS_SNAPSHOT_THRESHOLD2;
98685
98831
  var init_vm_mode = __esm({
98686
98832
  "../core/dist/runtime/vm-mode.js"() {
98687
98833
  "use strict";
@@ -98689,7 +98835,7 @@ var init_vm_mode = __esm({
98689
98835
  WORKFLOW_VMS2 = ["node", "quickjs"];
98690
98836
  __name(getWorkflowVmFromEnv2, "getWorkflowVmFromEnv");
98691
98837
  __name(useQuickJSVm, "useQuickJSVm");
98692
- DEFAULT_QUICKJS_SNAPSHOT_THRESHOLD = 1e3;
98838
+ DEFAULT_QUICKJS_SNAPSHOT_THRESHOLD2 = 1e3;
98693
98839
  __name(getSnapshotThresholdFromEnv2, "getSnapshotThresholdFromEnv");
98694
98840
  __name(getSnapshotThreshold, "getSnapshotThreshold");
98695
98841
  __name(getConfiguredSnapshotThreshold, "getConfiguredSnapshotThreshold");
@@ -98912,8 +99058,19 @@ var init_run = __esm({
98912
99058
  if (!this.#encryptionKeyPromise) {
98913
99059
  this.#encryptionKeyPromise = (async () => {
98914
99060
  const world = await this.#lazyWorldPromise;
98915
- const runData = run3 ?? await world.runs.get(this.runId);
98916
- const rawKey = await world.getEncryptionKeyForRun?.(runData);
99061
+ if (!world.getEncryptionKeyForRun)
99062
+ return void 0;
99063
+ let rawKey;
99064
+ if (run3) {
99065
+ rawKey = await world.getEncryptionKeyForRun(run3);
99066
+ } else {
99067
+ const { deploymentId } = await world.runs.get(this.runId, {
99068
+ resolveData: "none"
99069
+ });
99070
+ rawKey = await world.getEncryptionKeyForRun(this.runId, {
99071
+ deploymentId
99072
+ });
99073
+ }
98917
99074
  return rawKey ? await deriveRunPayloadKeys2(rawKey) : void 0;
98918
99075
  })();
98919
99076
  }
@@ -99326,6 +99483,52 @@ var init_lifecycle_hooks = __esm({
99326
99483
  }
99327
99484
  });
99328
99485
 
99486
+ // ../core/dist/runtime/event-limit-warning.js
99487
+ function getEventLimitMilestone(eventCount, limit) {
99488
+ if (limit === void 0 || limit <= 0 || limit >= Number.MAX_SAFE_INTEGER) {
99489
+ return void 0;
99490
+ }
99491
+ let reached;
99492
+ for (const fraction of EVENT_LIMIT_WARNING_FRACTIONS) {
99493
+ if (eventCount >= Math.ceil(limit * fraction))
99494
+ reached = fraction;
99495
+ }
99496
+ return reached;
99497
+ }
99498
+ function maybeWarnApproachingEventLimit(args) {
99499
+ const { runId, workflowName, eventCount, limit, isQuickJS } = args;
99500
+ const milestone = getEventLimitMilestone(eventCount, limit);
99501
+ if (milestone === void 0)
99502
+ return;
99503
+ const key = `${runId}:${milestone}`;
99504
+ if (warnedKeys.has(key))
99505
+ return;
99506
+ if (warnedKeys.size >= MAX_WARNED_KEYS)
99507
+ warnedKeys.clear();
99508
+ warnedKeys.add(key);
99509
+ const hint3 = isQuickJS ? "This QuickJS run is still subject to the limit because it was not started with a positive snapshot threshold (WORKFLOW_SNAPSHOT_THRESHOLD=0, or WORKFLOW_VM=quickjs was not set where the run was started). Runs started with WORKFLOW_VM=quickjs and snapshotting enabled are exempt." : QUICKJS_SNAPSHOT_REMEDIATION;
99510
+ runtimeLogger2.forRun(runId, workflowName).warn(`Workflow run is approaching the per-run event limit (${eventCount} of ${limit} events, ${Math.round(milestone * 100)}%). The run will fail with MAX_EVENTS_EXCEEDED when it reaches the limit. ${hint3}`, {
99511
+ eventCount,
99512
+ maxEvents: limit,
99513
+ milestone,
99514
+ docs: "https://workflow-sdk.dev/err/max-events-exceeded"
99515
+ });
99516
+ }
99517
+ var EVENT_LIMIT_WARNING_FRACTIONS, MAX_WARNED_KEYS, warnedKeys;
99518
+ var init_event_limit_warning = __esm({
99519
+ "../core/dist/runtime/event-limit-warning.js"() {
99520
+ "use strict";
99521
+ init_dist7();
99522
+ init_dist5();
99523
+ init_logger2();
99524
+ EVENT_LIMIT_WARNING_FRACTIONS = [0.5, 0.8, 0.95];
99525
+ MAX_WARNED_KEYS = 1e4;
99526
+ warnedKeys = globalSingleton2("@workflow/core//eventLimitWarnings", 1, () => /* @__PURE__ */ new Set());
99527
+ __name(getEventLimitMilestone, "getEventLimitMilestone");
99528
+ __name(maybeWarnApproachingEventLimit, "maybeWarnApproachingEventLimit");
99529
+ }
99530
+ });
99531
+
99329
99532
  // ../core/dist/runtime/replay-budget.js
99330
99533
  async function handleReplayBudgetExhausted(args) {
99331
99534
  const { runId, workflowName, requestId, attempt, limitMs, slotSnapshot } = args;
@@ -99349,7 +99552,10 @@ async function handleReplayBudgetExhausted(args) {
99349
99552
  errorAttribution: replayTimeoutDescription.attribution
99350
99553
  });
99351
99554
  const getEncryptionKey = memoizeEncryptionKey(world, runId);
99352
- const timeoutErr = new FatalError2(`Workflow replay exceeded maximum duration (${limitMs / 1e3}s) after ${attempt} attempts`);
99555
+ const timeoutErr = new FatalError2(formatErrorMessageWithDetails(`Workflow replay exceeded maximum duration (${limitMs / 1e3}s) after ${attempt} attempts`, {
99556
+ hint: `Replay time grows with the size of the event log. ${QUICKJS_SNAPSHOT_REMEDIATION}`,
99557
+ slug: ERROR_SLUGS2.REPLAY_TIMEOUT
99558
+ }));
99353
99559
  const encryptionKey = await getEncryptionKey();
99354
99560
  const dehydratedError = await dehydrateRunError(timeoutErr, runId, encryptionKey);
99355
99561
  await world.events.create(runId, {
@@ -101396,35 +101602,25 @@ var init_source_map = __esm({
101396
101602
  }
101397
101603
  });
101398
101604
 
101399
- // ../../node_modules/.pnpm/nanoid@5.1.6/node_modules/nanoid/url-alphabet/index.js
101400
- var urlAlphabet;
101401
- var init_url_alphabet = __esm({
101402
- "../../node_modules/.pnpm/nanoid@5.1.6/node_modules/nanoid/url-alphabet/index.js"() {
101403
- urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
101404
- }
101405
- });
101406
-
101407
- // ../../node_modules/.pnpm/nanoid@5.1.6/node_modules/nanoid/index.js
101408
- function customRandom(alphabet, defaultSize, getRandom) {
101409
- let mask = (2 << 31 - Math.clz32(alphabet.length - 1 | 1)) - 1;
101410
- let step = Math.ceil(1.6 * mask * defaultSize / alphabet.length);
101411
- return (size = defaultSize) => {
101412
- if (!size) return "";
101605
+ // ../core/dist/seeded-nanoid.js
101606
+ function createSeededNanoid(random) {
101607
+ return () => {
101608
+ const bytes = new Uint8Array(BYTES_PER_ID).map(() => 256 * random());
101413
101609
  let id = "";
101414
- while (true) {
101415
- let bytes = getRandom(step);
101416
- let i3 = step;
101417
- while (i3--) {
101418
- id += alphabet[bytes[i3] & mask] || "";
101419
- if (id.length >= size) return id;
101420
- }
101610
+ for (let i3 = BYTES_PER_ID - 1; id.length < ID_SIZE; i3--) {
101611
+ id += URL_ALPHABET[bytes[i3] & 63];
101421
101612
  }
101613
+ return id;
101422
101614
  };
101423
101615
  }
101424
- var init_nanoid = __esm({
101425
- "../../node_modules/.pnpm/nanoid@5.1.6/node_modules/nanoid/index.js"() {
101426
- init_url_alphabet();
101427
- __name(customRandom, "customRandom");
101616
+ var URL_ALPHABET, ID_SIZE, BYTES_PER_ID;
101617
+ var init_seeded_nanoid = __esm({
101618
+ "../core/dist/seeded-nanoid.js"() {
101619
+ "use strict";
101620
+ URL_ALPHABET = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
101621
+ ID_SIZE = 21;
101622
+ BYTES_PER_ID = 34;
101623
+ __name(createSeededNanoid, "createSeededNanoid");
101428
101624
  }
101429
101625
  });
101430
101626
 
@@ -107378,7 +107574,7 @@ async function startQuickJSWorkflow(options) {
107378
107574
  rngDraws++;
107379
107575
  return baseRng();
107380
107576
  }, "rng");
107381
- const generateNanoid = customRandom(urlAlphabet, 21, (size) => new Uint8Array(size).map(() => 256 * rng()));
107577
+ const generateNanoid = createSeededNanoid(rng);
107382
107578
  let vmNowMs = runIdCreatedAt(workflowRun.runId) ?? (+workflowRun.createdAt || startedAt);
107383
107579
  const advanceClock = /* @__PURE__ */ __name((ms3) => {
107384
107580
  if (Number.isFinite(ms3))
@@ -108405,11 +108601,11 @@ var init_quickjs_runtime = __esm({
108405
108601
  init_dist5();
108406
108602
  init_dist6();
108407
108603
  init_attributes_validation2();
108408
- init_nanoid();
108409
108604
  init_dist13();
108410
108605
  import_seedrandom2 = __toESM(require_seedrandom2(), 1);
108411
108606
  init_node2();
108412
108607
  init_logger2();
108608
+ init_seeded_nanoid();
108413
108609
  init_compression2();
108414
108610
  init_encryption5();
108415
108611
  init_errors6();
@@ -109928,6 +110124,13 @@ async function runWorkflowWithQuickJS(params) {
109928
110124
  if (maxEventsLimit !== void 0 && restoredEventCount + events.length >= maxEventsLimit) {
109929
110125
  throw new MaxEventsExceededError(restoredEventCount + events.length, maxEventsLimit);
109930
110126
  }
110127
+ maybeWarnApproachingEventLimit({
110128
+ runId,
110129
+ workflowName,
110130
+ eventCount: restoredEventCount + events.length,
110131
+ limit: maxEventsLimit,
110132
+ isQuickJS: true
110133
+ });
109931
110134
  parentSpan?.setAttributes({
109932
110135
  ...QuickJSEventsPreloaded2(usePreloaded),
109933
110136
  ...QuickJSEventsFetchedCount2(events.length),
@@ -110804,6 +111007,7 @@ var init_quickjs_entrypoint = __esm({
110804
111007
  init_semantic_conventions2();
110805
111008
  init_telemetry4();
110806
111009
  init_constants4();
111010
+ init_event_limit_warning();
110807
111011
  init_get_port_lazy();
110808
111012
  init_helpers3();
110809
111013
  init_hook_wake2();
@@ -111319,7 +111523,9 @@ var init_dist2 = __esm2({
111319
111523
  STEP_NOT_REGISTERED: "step-not-registered",
111320
111524
  WORKFLOW_NOT_REGISTERED: "workflow-not-registered",
111321
111525
  RUNTIME_DECRYPTION_FAILED: "runtime-decryption-failed",
111322
- DEPLOYMENT_MISMATCH: "deployment-mismatch"
111526
+ DEPLOYMENT_MISMATCH: "deployment-mismatch",
111527
+ MAX_EVENTS_EXCEEDED: "max-events-exceeded",
111528
+ REPLAY_TIMEOUT: "replay-timeout"
111323
111529
  };
111324
111530
  WorkflowError = class extends Error {
111325
111531
  static {
@@ -137925,6 +138131,19 @@ var init_queue = __esm2({
137925
138131
  * probe response. That lets the caller seal the workflow arguments without
137926
138132
  * a separate key lookup. Absent for probes issued for other reasons (CLI
137927
138133
  * health command, dashboard), in which case no key is returned.
138134
+ *
138135
+ * Deliberately not named `runId`: `runId` is the only required field of
138136
+ * `WorkflowInvokePayloadSchema`, and 4.x deployments parse queue payloads
138137
+ * with a union that tries the invoke schema before the health check. A
138138
+ * probe carrying `runId` is read there as "replay this run", which POSTs
138139
+ * `run_started` for a run that does not exist yet (404) and retries the
138140
+ * delivery, so the probe never answers.
138141
+ */
138142
+ probeRunId: external_exports.string().optional(),
138143
+ /**
138144
+ * Legacy spelling of {@link probeRunId}, sent by 5.x callers released
138145
+ * before the rename. Accepted so those callers still get a public key
138146
+ * back from this deployment; never sent.
137928
138147
  */
137929
138148
  runId: external_exports.string().optional()
137930
138149
  }));
@@ -144812,7 +145031,7 @@ var version2;
144812
145031
  var init_version = __esm2({
144813
145032
  "../core/dist/version.js"() {
144814
145033
  "use strict";
144815
- version2 = "5.2.2";
145034
+ version2 = "5.2.3";
144816
145035
  }
144817
145036
  });
144818
145037
  function isDynamicWorkflowsEnabled() {
@@ -144951,8 +145170,11 @@ async function healthCheck(world, options) {
144951
145170
  await world.queue(queueName, {
144952
145171
  __healthCheck: true,
144953
145172
  correlationId,
145173
+ // Sent as `probeRunId`, never `runId`: a 4.x responder would parse a
145174
+ // `runId`-bearing probe as a run invocation (see
145175
+ // `HealthCheckPayloadSchema`).
144954
145176
  ...options?.runId ? {
144955
- runId: options.runId
145177
+ probeRunId: options.runId
144956
145178
  } : {}
144957
145179
  }, {
144958
145180
  // Use JSON transport so the health check works against both
@@ -150168,7 +150390,9 @@ async function resolveHookResumeInfo(hook) {
150168
150390
  source: "hook"
150169
150391
  };
150170
150392
  }
150171
- const run22 = await (await getWorldLazy()).runs.get(hook.runId);
150393
+ const run22 = await (await getWorldLazy()).runs.get(hook.runId, {
150394
+ resolveData: "none"
150395
+ });
150172
150396
  return {
150173
150397
  resumeContext: resumeContextFromRun(run22),
150174
150398
  source: "run_fallback",
@@ -150178,7 +150402,7 @@ async function resolveHookResumeInfo(hook) {
150178
150402
  __name(resolveHookResumeInfo, "resolveHookResumeInfo");
150179
150403
  async function resolveHookEncryptionKey(hook, info) {
150180
150404
  const world = await getWorldLazy();
150181
- const rawKey = info.run ? await world.getEncryptionKeyForRun?.(info.run) : await world.getEncryptionKeyForRun?.(hook.runId, {
150405
+ const rawKey = await world.getEncryptionKeyForRun?.(hook.runId, {
150182
150406
  deploymentId: info.resumeContext.deploymentId
150183
150407
  });
150184
150408
  return rawKey ? await importKey(rawKey) : void 0;
@@ -150196,7 +150420,7 @@ function withLazyMetadata(raw) {
150196
150420
  const hydrate = /* @__PURE__ */ __name2(async () => {
150197
150421
  const world = await getWorldLazy();
150198
150422
  const info = await resolveHookResumeInfo(raw);
150199
- const rawKey = info.run ? await world.getEncryptionKeyForRun?.(info.run) : await world.getEncryptionKeyForRun?.(raw.runId, {
150423
+ const rawKey = await world.getEncryptionKeyForRun?.(raw.runId, {
150200
150424
  deploymentId: info.resumeContext.deploymentId
150201
150425
  });
150202
150426
  encryptionKey = rawKey ? await deriveRunPayloadKeys(rawKey) : void 0;
@@ -151581,9 +151805,12 @@ async function getForwardedWritableEncryptionKey(runId, deploymentId, encryption
151581
151805
  if (ownerPublicKey) return sealTo(ownerPublicKey);
151582
151806
  const world = await getWorldLazy();
151583
151807
  if (!world.getEncryptionKeyForRun) return void 0;
151584
- const rawKey = deploymentId ? await world.getEncryptionKeyForRun(runId, {
151585
- deploymentId
151586
- }) : await world.getEncryptionKeyForRun(await world.runs.get(runId));
151808
+ const ownerDeploymentId = deploymentId ?? (await world.runs.get(runId, {
151809
+ resolveData: "none"
151810
+ })).deploymentId;
151811
+ const rawKey = await world.getEncryptionKeyForRun(runId, {
151812
+ deploymentId: ownerDeploymentId
151813
+ });
151587
151814
  return rawKey ? await importKey(rawKey, [
151588
151815
  "encrypt"
151589
151816
  ]) : void 0;
@@ -159708,6 +159935,7 @@ function getWorkflowVmFromEnv(env = process.env) {
159708
159935
  }
159709
159936
  __name(getWorkflowVmFromEnv, "getWorkflowVmFromEnv");
159710
159937
  __name2(getWorkflowVmFromEnv, "getWorkflowVmFromEnv");
159938
+ var DEFAULT_QUICKJS_SNAPSHOT_THRESHOLD = 1e3;
159711
159939
  function getSnapshotThresholdFromEnv(env = process.env) {
159712
159940
  const raw = env.WORKFLOW_SNAPSHOT_THRESHOLD;
159713
159941
  if (raw === void 0 || raw === "") return void 0;
@@ -159719,6 +159947,13 @@ function getSnapshotThresholdFromEnv(env = process.env) {
159719
159947
  }
159720
159948
  __name(getSnapshotThresholdFromEnv, "getSnapshotThresholdFromEnv");
159721
159949
  __name2(getSnapshotThresholdFromEnv, "getSnapshotThresholdFromEnv");
159950
+ function getSnapshotThresholdForStart(workflowVm, env = process.env) {
159951
+ const fromEnv = getSnapshotThresholdFromEnv(env);
159952
+ if (fromEnv !== void 0) return fromEnv;
159953
+ return workflowVm === "quickjs" ? DEFAULT_QUICKJS_SNAPSHOT_THRESHOLD : void 0;
159954
+ }
159955
+ __name(getSnapshotThresholdForStart, "getSnapshotThresholdForStart");
159956
+ __name2(getSnapshotThresholdForStart, "getSnapshotThresholdForStart");
159722
159957
  init_wait_until();
159723
159958
  init_world_compatibility();
159724
159959
  var CROSS_DEPLOYMENT_CAPABILITY_PROBE_TIMEOUT_MS = 1e4;
@@ -160021,7 +160256,7 @@ async function start(workflow, argsOrOptions, options) {
160021
160256
  encryptionPublicKey = rawKey ? bytesToBase64((await deriveRunKeyPair(rawKey)).publicKey) : void 0;
160022
160257
  }
160023
160258
  const workflowVm = getWorkflowVmFromEnv();
160024
- const snapshotThreshold = getSnapshotThresholdFromEnv();
160259
+ const snapshotThreshold = getSnapshotThresholdForStart(workflowVm);
160025
160260
  const queueNamespace = resolveQueueNamespace(opts.namespace);
160026
160261
  const executionContext = {
160027
160262
  traceCarrier,
@@ -160195,7 +160430,7 @@ __name2(start, "start");
160195
160430
  value: "start",
160196
160431
  configurable: true
160197
160432
  });
160198
- })(start, "step//@workflow/core/runtime/start@5.2.2//start");
160433
+ })(start, "step//@workflow/core/runtime/start@5.2.3//start");
160199
160434
  async function wakeUpRun(world, runId, options) {
160200
160435
  try {
160201
160436
  const run22 = await world.runs.get(runId, {
@@ -160380,8 +160615,18 @@ var Run = class _Run {
160380
160615
  if (!this.#encryptionKeyPromise) {
160381
160616
  this.#encryptionKeyPromise = (async () => {
160382
160617
  const world = await this.#lazyWorldPromise;
160383
- const runData = run22 ?? await world.runs.get(this.runId);
160384
- const rawKey = await world.getEncryptionKeyForRun?.(runData);
160618
+ if (!world.getEncryptionKeyForRun) return void 0;
160619
+ let rawKey;
160620
+ if (run22) {
160621
+ rawKey = await world.getEncryptionKeyForRun(run22);
160622
+ } else {
160623
+ const { deploymentId } = await world.runs.get(this.runId, {
160624
+ resolveData: "none"
160625
+ });
160626
+ rawKey = await world.getEncryptionKeyForRun(this.runId, {
160627
+ deploymentId
160628
+ });
160629
+ }
160385
160630
  return rawKey ? await deriveRunPayloadKeys(rawKey) : void 0;
160386
160631
  })();
160387
160632
  }
@@ -160673,7 +160918,7 @@ var Run = class _Run {
160673
160918
  value: "wakeUp",
160674
160919
  configurable: true
160675
160920
  });
160676
- })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.2.2//Run#wakeUp");
160921
+ })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.2.3//Run#wakeUp");
160677
160922
  (function(__wf_fn, __wf_id) {
160678
160923
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160679
160924
  __wf_reg.set(__wf_id, __wf_fn);
@@ -160682,7 +160927,7 @@ var Run = class _Run {
160682
160927
  value: "cancel",
160683
160928
  configurable: true
160684
160929
  });
160685
- })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.2.2//Run#cancel");
160930
+ })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.2.3//Run#cancel");
160686
160931
  (function(__wf_fn, __wf_id) {
160687
160932
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160688
160933
  __wf_reg.set(__wf_id, __wf_fn);
@@ -160691,7 +160936,7 @@ var Run = class _Run {
160691
160936
  value: "getReadable",
160692
160937
  configurable: true
160693
160938
  });
160694
- })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.2.2//Run#getReadable");
160939
+ })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.2.3//Run#getReadable");
160695
160940
  (function(__wf_fn, __wf_id) {
160696
160941
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160697
160942
  __wf_reg.set(__wf_id, __wf_fn);
@@ -160700,7 +160945,7 @@ var Run = class _Run {
160700
160945
  value: "getWritable",
160701
160946
  configurable: true
160702
160947
  });
160703
- })(Run.prototype["getWritable"], "step//@workflow/core/runtime/run@5.2.2//Run#getWritable");
160948
+ })(Run.prototype["getWritable"], "step//@workflow/core/runtime/run@5.2.3//Run#getWritable");
160704
160949
  (function(__wf_fn, __wf_id) {
160705
160950
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160706
160951
  __wf_reg.set(__wf_id, __wf_fn);
@@ -160709,7 +160954,7 @@ var Run = class _Run {
160709
160954
  value: "exists",
160710
160955
  configurable: true
160711
160956
  });
160712
- })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.2.2//Run#exists");
160957
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.2.3//Run#exists");
160713
160958
  (function(__wf_fn, __wf_id) {
160714
160959
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160715
160960
  __wf_reg.set(__wf_id, __wf_fn);
@@ -160718,7 +160963,7 @@ var Run = class _Run {
160718
160963
  value: "status",
160719
160964
  configurable: true
160720
160965
  });
160721
- })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.2.2//Run#status");
160966
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.2.3//Run#status");
160722
160967
  (function(__wf_fn, __wf_id) {
160723
160968
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160724
160969
  __wf_reg.set(__wf_id, __wf_fn);
@@ -160727,7 +160972,7 @@ var Run = class _Run {
160727
160972
  value: "returnValue",
160728
160973
  configurable: true
160729
160974
  });
160730
- })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.2.2//Run#returnValue");
160975
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.2.3//Run#returnValue");
160731
160976
  (function(__wf_fn, __wf_id) {
160732
160977
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160733
160978
  __wf_reg.set(__wf_id, __wf_fn);
@@ -160736,7 +160981,7 @@ var Run = class _Run {
160736
160981
  value: "workflowName",
160737
160982
  configurable: true
160738
160983
  });
160739
- })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.2.2//Run#workflowName");
160984
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.2.3//Run#workflowName");
160740
160985
  (function(__wf_fn, __wf_id) {
160741
160986
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160742
160987
  __wf_reg.set(__wf_id, __wf_fn);
@@ -160745,7 +160990,7 @@ var Run = class _Run {
160745
160990
  value: "createdAt",
160746
160991
  configurable: true
160747
160992
  });
160748
- })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.2.2//Run#createdAt");
160993
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.2.3//Run#createdAt");
160749
160994
  (function(__wf_fn, __wf_id) {
160750
160995
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160751
160996
  __wf_reg.set(__wf_id, __wf_fn);
@@ -160754,7 +160999,7 @@ var Run = class _Run {
160754
160999
  value: "startedAt",
160755
161000
  configurable: true
160756
161001
  });
160757
- })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.2.2//Run#startedAt");
161002
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.2.3//Run#startedAt");
160758
161003
  (function(__wf_fn, __wf_id) {
160759
161004
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160760
161005
  __wf_reg.set(__wf_id, __wf_fn);
@@ -160763,7 +161008,7 @@ var Run = class _Run {
160763
161008
  value: "completedAt",
160764
161009
  configurable: true
160765
161010
  });
160766
- })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.2.2//Run#completedAt");
161011
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.2.3//Run#completedAt");
160767
161012
  (function(__wf_cls, __wf_id) {
160768
161013
  var __wf_sym = /* @__PURE__ */ Symbol.for("workflow-class-registry"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
160769
161014
  __wf_reg.set(__wf_id, __wf_cls);
@@ -160773,7 +161018,7 @@ var Run = class _Run {
160773
161018
  enumerable: false,
160774
161019
  configurable: false
160775
161020
  });
160776
- })(Run, "class//@workflow/core/runtime/run@5.2.2//Run");
161021
+ })(Run, "class//@workflow/core/runtime/run@5.2.3//Run");
160777
161022
  async function fetch2(...args) {
160778
161023
  return globalThis.fetch(...args);
160779
161024
  }
@@ -161615,6 +161860,7 @@ __name(guardDeploymentAffinity, "guardDeploymentAffinity");
161615
161860
 
161616
161861
  // ../core/dist/runtime.js
161617
161862
  init_dynamic_workflow();
161863
+ init_event_limit_warning();
161618
161864
  init_helpers3();
161619
161865
  init_invocations2();
161620
161866
  init_lifecycle_hooks();
@@ -161962,6 +162208,19 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
161962
162208
  const awaitedHookCorrelationIds = [];
161963
162209
  let hookCreationMs = 0;
161964
162210
  const hookDeltaCursor = hooksNeedingCreation.length === 1 && typeof eventLog?.cursor === "string" ? eventLog.cursor : void 0;
162211
+ const hasOtherSuspensionWrites = stepItems.some((item) => !item.hasCreatedEvent) || waitItems.some((item) => !item.hasCreatedEvent) || attributeItems.length > 0 || allHookItems.some((item) => item.disposed || item.abortRequested);
162212
+ const concurrentHookIneligibility = !eventLog ? "no_event_log" : (run3.specVersion ?? 0) < SPEC_VERSION_SUPPORTS_SLOT_IDENTITY2 ? "unsupported_spec" : hasOtherSuspensionWrites ? "other_suspension_writes" : hooksNeedingCreation.some((item) => item.force || hookItemsByToken.get(item.token)?.length !== 1) ? "dependent_hooks" : void 0;
162213
+ const concurrentHooks = concurrentHookIneligibility ? [] : hooksNeedingCreation;
162214
+ const hookFrontier = concurrentHooks.length > 1 && eventLog ? maxEventSlot(eventLog.events) : void 0;
162215
+ const concurrentHookIds = new Set(hookFrontier === void 0 ? [] : concurrentHooks.map((item) => item.correlationId));
162216
+ const hookResults = /* @__PURE__ */ new Map();
162217
+ const createConcurrentHook = /* @__PURE__ */ __name(async (data3, params) => {
162218
+ eventWrites++;
162219
+ const result2 = await createEvent(data3, { ...params, resolveData: "all" });
162220
+ if (data3.correlationId)
162221
+ hookResults.set(data3.correlationId, result2);
162222
+ return result2;
162223
+ }, "createConcurrentHook");
161965
162224
  const processHookGroup = /* @__PURE__ */ __name(async (items) => {
161966
162225
  for (const queueItem of items) {
161967
162226
  let creationConflicted = false;
@@ -161989,7 +162248,7 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
161989
162248
  queueItem,
161990
162249
  requestId,
161991
162250
  sinceCursor: hookDeltaCursor,
161992
- createEvent: createGuarded,
162251
+ createEvent: concurrentHookIds.has(queueItem.correlationId) ? createConcurrentHook : createGuarded,
161993
162252
  world,
161994
162253
  forceClaimVictimWakes
161995
162254
  });
@@ -162552,6 +162811,67 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
162552
162811
  } finally {
162553
162812
  await owedVictimWakes;
162554
162813
  }
162814
+ const reconcileConcurrentHooks = /* @__PURE__ */ __name(() => {
162815
+ if (concurrentHookIneligibility)
162816
+ return concurrentHookIneligibility;
162817
+ if (!eventLog || hookFrontier === void 0)
162818
+ return "missing_frontier";
162819
+ if (hookResults.size !== concurrentHookIds.size)
162820
+ return "missing_response";
162821
+ if (eventWrites !== hookResults.size)
162822
+ return "other_suspension_writes";
162823
+ if (maxEventSlot(eventLog.events) !== hookFrontier)
162824
+ return "prefix_changed";
162825
+ if (findEventSlotGap(eventLog.events) !== void 0)
162826
+ return "prefix_gap";
162827
+ const committed = [];
162828
+ for (const item of concurrentHooks) {
162829
+ const result2 = hookResults.get(item.correlationId);
162830
+ const event = result2.event;
162831
+ if (!event)
162832
+ return "missing_event";
162833
+ if (result2.hasMore === true)
162834
+ return "incomplete_response";
162835
+ if (event.runId !== runId || event.correlationId !== item.correlationId || event.eventType !== "hook_created" && event.eventType !== "hook_conflict" || event.eventData.token !== item.token) {
162836
+ return "event_mismatch";
162837
+ }
162838
+ if (event.eventType === "hook_created" && (event.eventData.metadata !== void 0 && !(event.eventData.metadata instanceof Uint8Array) || item.metadata !== void 0 && event.eventData.metadata === void 0)) {
162839
+ return "unresolved_metadata";
162840
+ }
162841
+ const slot = eventIdToSlot(event.eventId);
162842
+ if (slot === null)
162843
+ return "non_slot_event";
162844
+ committed.push({ event, slot, cursor: result2.eventCursor });
162845
+ }
162846
+ committed.sort((a, b) => a.slot - b.slot);
162847
+ if (!committed.every(({ slot }, index) => slot === hookFrontier + index + 1)) {
162848
+ return "nonconsecutive_slots";
162849
+ }
162850
+ const last = committed.at(-1);
162851
+ if (!last?.cursor)
162852
+ return "missing_event_cursor";
162853
+ eventLog.events.push(...committed.map(({ event }) => event));
162854
+ eventLog.cursor = last.cursor;
162855
+ return void 0;
162856
+ }, "reconcileConcurrentHooks");
162857
+ let concurrentHooksCarriedForward = false;
162858
+ if (hooksNeedingCreation.length > 1) {
162859
+ const fallbackReason = reconcileConcurrentHooks();
162860
+ concurrentHooksCarriedForward = fallbackReason === void 0;
162861
+ span?.setAttributes({
162862
+ "workflow.concurrent_hooks.count": hooksNeedingCreation.length,
162863
+ "workflow.concurrent_hooks.carried_forward": concurrentHooksCarriedForward,
162864
+ // A span can cover several suspensions; clear a previous fallback when
162865
+ // this registration set succeeds instead of leaving a stale reason.
162866
+ "workflow.concurrent_hooks.fallback_reason": fallbackReason ?? "none"
162867
+ });
162868
+ runtimeLogger2.debug("Reconciled concurrent hook registrations", {
162869
+ workflowRunId: runId,
162870
+ hookCount: hooksNeedingCreation.length,
162871
+ carriedForward: concurrentHooksCarriedForward,
162872
+ ...fallbackReason ? { fallbackReason } : {}
162873
+ });
162874
+ }
162555
162875
  if (hookGroupsWindow?.endMs !== void 0) {
162556
162876
  const blockedFromMs = Math.max(hookGroupsWindow.startMs, await nonHookOpsSettled);
162557
162877
  hookCreationMs += Math.max(0, hookGroupsWindow.endMs - blockedFromMs);
@@ -162599,10 +162919,9 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
162599
162919
  hookConflictCorrelationIds,
162600
162920
  hasAwaitedHookCreation: awaitedHookCorrelationIds.length > 0,
162601
162921
  awaitedHookCorrelationIds,
162602
- // The delta accounts for the whole log only if the write that returned it
162603
- // was this suspension's only one — any other write may have landed above
162604
- // the delta and be missing from the caller's log.
162605
- eventLogCarriedForward: deltaAbsorbed && eventWrites === 1,
162922
+ // A lone delta or a proven consecutive suffix must account for every
162923
+ // suspension write; otherwise the caller reloads before continuing.
162924
+ eventLogCarriedForward: deltaAbsorbed && eventWrites === 1 || concurrentHooksCarriedForward,
162606
162925
  hasAttributeEvents: attributeItems.length > 0,
162607
162926
  hasHookEvents: hooksNeedingCreation.length > 0,
162608
162927
  hookCreationMs,
@@ -162640,7 +162959,6 @@ init_dist5();
162640
162959
  init_parse_name2();
162641
162960
  init_event_metadata2();
162642
162961
  init_spec_version2();
162643
- init_nanoid();
162644
162962
  init_node2();
162645
162963
  init_events_consumer2();
162646
162964
  init_global2();
@@ -162697,6 +163015,7 @@ __name(describeDivergenceContext, "describeDivergenceContext");
162697
163015
  init_get_port_lazy();
162698
163016
  init_run_id_time();
162699
163017
  init_world();
163018
+ init_seeded_nanoid();
162700
163019
  init_serialization4();
162701
163020
 
162702
163021
  // ../core/dist/step.js
@@ -162768,6 +163087,7 @@ function createUseStep(ctx) {
162768
163087
  if (event.eventType === "step_started") {
162769
163088
  const queueItem2 = ctx.invocationsQueue.get(correlationId);
162770
163089
  if (queueItem2 && queueItem2.type === "step") {
163090
+ queueItem2.hasCreatedEvent = true;
162771
163091
  const ownerMessageId = "eventData" in event && event.eventData && "ownerMessageId" in event.eventData && typeof event.eventData.ownerMessageId === "string" ? event.eventData.ownerMessageId : void 0;
162772
163092
  queueItem2.ownerMessageId = ownerMessageId;
162773
163093
  queueItem2.lastStartedAt = +event.createdAt;
@@ -164150,7 +164470,7 @@ async function createWorkflowSessionInner({ workflowCode: workflowCode2, workflo
164150
164470
  mintCount += 1;
164151
164471
  return ulid8(fixedTimestamp);
164152
164472
  }, "generateUlid");
164153
- const generateNanoid = customRandom(urlAlphabet, 21, (size) => new Uint8Array(size).map(() => 256 * vmGlobalThis.Math.random()));
164473
+ const generateNanoid = createSeededNanoid(() => vmGlobalThis.Math.random());
164154
164474
  const promiseQueueHolder = { current: Promise.resolve() };
164155
164475
  const deliveryIdleHolder = { current: /* @__PURE__ */ __name(() => true, "current") };
164156
164476
  let clock = fixedTimestamp;
@@ -165437,7 +165757,7 @@ function workflowEntrypoint(workflowCode2, options) {
165437
165757
  const stepCreatedIds = /* @__PURE__ */ new Set();
165438
165758
  const stepTerminalIds = /* @__PURE__ */ new Set();
165439
165759
  for (const e of loaded.events) {
165440
- if (e.eventType === "step_created") {
165760
+ if (e.eventType === "step_created" || e.eventType === "step_started") {
165441
165761
  stepCreatedIds.add(e.correlationId);
165442
165762
  } else if (e.eventType === "step_completed" || e.eventType === "step_failed") {
165443
165763
  stepTerminalIds.add(e.correlationId);
@@ -166041,6 +166361,13 @@ function workflowEntrypoint(workflowCode2, options) {
166041
166361
  if (workflowEventCount >= maxEventsLimit) {
166042
166362
  throw new MaxEventsExceededError(workflowEventCount, maxEventsLimit);
166043
166363
  }
166364
+ maybeWarnApproachingEventLimit({
166365
+ runId,
166366
+ workflowName,
166367
+ eventCount: workflowEventCount,
166368
+ limit: maxEventsLimit,
166369
+ isQuickJS: false
166370
+ });
166044
166371
  }
166045
166372
  invocationStartedClean ??= eventLog.events.every((e) => e.eventType === "run_created" || e.eventType === "run_started" || e.eventType === "attr_set" || isSealedNoopEvent(e));
166046
166373
  runtimeLogger2.debug("Starting workflow execution", {
@@ -167487,7 +167814,9 @@ var ERROR_SLUGS = {
167487
167814
  STEP_NOT_REGISTERED: "step-not-registered",
167488
167815
  WORKFLOW_NOT_REGISTERED: "workflow-not-registered",
167489
167816
  RUNTIME_DECRYPTION_FAILED: "runtime-decryption-failed",
167490
- DEPLOYMENT_MISMATCH: "deployment-mismatch"
167817
+ DEPLOYMENT_MISMATCH: "deployment-mismatch",
167818
+ MAX_EVENTS_EXCEEDED: "max-events-exceeded",
167819
+ REPLAY_TIMEOUT: "replay-timeout"
167491
167820
  };
167492
167821
  var WorkflowError = class extends Error {
167493
167822
  static {
@@ -167815,11 +168144,11 @@ var Run = class _Run {
167815
168144
  return this.getWritable();
167816
168145
  }
167817
168146
  };
167818
- Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#wakeUp");
167819
- Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#cancel");
167820
- Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#getReadable");
167821
- Run.prototype["getWritable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#getWritable");
167822
- var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#exists");
168147
+ Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#wakeUp");
168148
+ Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#cancel");
168149
+ Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#getReadable");
168150
+ Run.prototype["getWritable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#getWritable");
168151
+ var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#exists");
167823
168152
  Object.defineProperty(Run.prototype, "exists", {
167824
168153
  get() {
167825
168154
  return __step_Run$exists.call(this);
@@ -167827,7 +168156,7 @@ Object.defineProperty(Run.prototype, "exists", {
167827
168156
  configurable: true,
167828
168157
  enumerable: false
167829
168158
  });
167830
- var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#status");
168159
+ var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#status");
167831
168160
  Object.defineProperty(Run.prototype, "status", {
167832
168161
  get() {
167833
168162
  return __step_Run$status.call(this);
@@ -167835,7 +168164,7 @@ Object.defineProperty(Run.prototype, "status", {
167835
168164
  configurable: true,
167836
168165
  enumerable: false
167837
168166
  });
167838
- var __step_Run$returnValue = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#returnValue");
168167
+ var __step_Run$returnValue = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#returnValue");
167839
168168
  Object.defineProperty(Run.prototype, "returnValue", {
167840
168169
  get() {
167841
168170
  return __step_Run$returnValue.call(this);
@@ -167843,7 +168172,7 @@ Object.defineProperty(Run.prototype, "returnValue", {
167843
168172
  configurable: true,
167844
168173
  enumerable: false
167845
168174
  });
167846
- var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#workflowName");
168175
+ var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#workflowName");
167847
168176
  Object.defineProperty(Run.prototype, "workflowName", {
167848
168177
  get() {
167849
168178
  return __step_Run$workflowName.call(this);
@@ -167851,7 +168180,7 @@ Object.defineProperty(Run.prototype, "workflowName", {
167851
168180
  configurable: true,
167852
168181
  enumerable: false
167853
168182
  });
167854
- var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#createdAt");
168183
+ var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#createdAt");
167855
168184
  Object.defineProperty(Run.prototype, "createdAt", {
167856
168185
  get() {
167857
168186
  return __step_Run$createdAt.call(this);
@@ -167859,7 +168188,7 @@ Object.defineProperty(Run.prototype, "createdAt", {
167859
168188
  configurable: true,
167860
168189
  enumerable: false
167861
168190
  });
167862
- var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#startedAt");
168191
+ var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#startedAt");
167863
168192
  Object.defineProperty(Run.prototype, "startedAt", {
167864
168193
  get() {
167865
168194
  return __step_Run$startedAt.call(this);
@@ -167867,7 +168196,7 @@ Object.defineProperty(Run.prototype, "startedAt", {
167867
168196
  configurable: true,
167868
168197
  enumerable: false
167869
168198
  });
167870
- var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.2//Run#completedAt");
168199
+ var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.2.3//Run#completedAt");
167871
168200
  Object.defineProperty(Run.prototype, "completedAt", {
167872
168201
  get() {
167873
168202
  return __step_Run$completedAt.call(this);
@@ -167884,7 +168213,7 @@ Object.defineProperty(Run.prototype, "completedAt", {
167884
168213
  enumerable: false,
167885
168214
  configurable: false
167886
168215
  });
167887
- })(Run, "class//@workflow/core/runtime/run@5.2.2//Run");
168216
+ })(Run, "class//@workflow/core/runtime/run@5.2.3//Run");
167888
168217
 
167889
168218
  // ../core/dist/workflow/create-hook.js
167890
168219
  aliasSerializationClass(RUN_CLASS_ID, Run);
@@ -189976,6 +190305,19 @@ var HealthCheckPayloadSchema = external_exports.compile(external_exports.object(
189976
190305
  * probe response. That lets the caller seal the workflow arguments without
189977
190306
  * a separate key lookup. Absent for probes issued for other reasons (CLI
189978
190307
  * health command, dashboard), in which case no key is returned.
190308
+ *
190309
+ * Deliberately not named \`runId\`: \`runId\` is the only required field of
190310
+ * \`WorkflowInvokePayloadSchema\`, and 4.x deployments parse queue payloads
190311
+ * with a union that tries the invoke schema before the health check. A
190312
+ * probe carrying \`runId\` is read there as "replay this run", which POSTs
190313
+ * \`run_started\` for a run that does not exist yet (404) and retries the
190314
+ * delivery, so the probe never answers.
190315
+ */
190316
+ probeRunId: external_exports.string().optional(),
190317
+ /**
190318
+ * Legacy spelling of {@link probeRunId}, sent by 5.x callers released
190319
+ * before the rename. Accepted so those callers still get a public key
190320
+ * back from this deployment; never sent.
189979
190321
  */
189980
190322
  runId: external_exports.string().optional()
189981
190323
  }));
@@ -190182,7 +190524,7 @@ var latestNoOpWarning = globalSingleton("@workflow/core//latestNoOpWarning", 1,
190182
190524
  var probeMissWarning = globalSingleton("@workflow/core//crossDeploymentProbeMissWarning", 1, () => ({
190183
190525
  warned: false
190184
190526
  }));
190185
- var start = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/start@5.2.2//start");
190527
+ var start = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/start@5.2.3//start");
190186
190528
 
190187
190529
  // workflows/lineage.ts
190188
190530
  var noop = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//./workflows/lineage//noop");