@dudousxd/nestjs-durable-core 0.103.0 → 0.104.0

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.d.cts CHANGED
@@ -187,9 +187,14 @@ interface ConcurrencyQuota {
187
187
  * / `@Workflow({ concurrency })`): the key is derived from each start's input, and the limit may be a
188
188
  * function of the key (per-tenant plans). A `StartOptions.concurrency` on one start overrides it.
189
189
  */
190
- interface ConcurrencyConfig {
191
- /** Derive the quota key from the input. Return `undefined` to leave this start unlimited. */
192
- key: (input: unknown) => string | undefined;
190
+ interface ConcurrencyConfig<TInput = unknown> {
191
+ /**
192
+ * Derive the quota key from the input. Return `undefined` to leave this start unlimited. When the
193
+ * workflow declares an input schema (`@Workflow({ input })`, or `register(..., { parseInput })`),
194
+ * it receives the PARSED input, the same value `run(ctx, input)` gets, and `@Workflow` types
195
+ * `TInput` from the schema.
196
+ */
197
+ key: (input: TInput) => string | undefined;
193
198
  /** Max in-flight runs per key — a number, or resolved per key (e.g. from the tenant's plan). */
194
199
  limit: number | ((key: string) => number | Promise<number>);
195
200
  /** Which statuses occupy a slot. See {@link ConcurrencyQuota.countStatuses}. */
@@ -2356,9 +2361,13 @@ interface StartOptions {
2356
2361
  * admission on a timer until a slot frees. The store atomically reserves durable slots before
2357
2362
  * ordering unadmitted waiters by `(createdAt, id)`, so later starts cannot displace a holder.
2358
2363
  */
2359
- interface SingletonConfig {
2360
- /** Derive the serialization key from the workflow input. */
2361
- key: (input: unknown) => string;
2364
+ interface SingletonConfig<TInput = unknown> {
2365
+ /**
2366
+ * Derive the serialization key from the workflow input. When the workflow declares an input schema
2367
+ * (`@Workflow({ input })`, or `register(..., { parseInput })`), it receives the PARSED input, the
2368
+ * same value `run(ctx, input)` gets, and `@Workflow` types `TInput` from the schema.
2369
+ */
2370
+ key: (input: TInput) => string;
2362
2371
  /** Max concurrent runs sharing the key. Default 1 (a mutex). */
2363
2372
  limit?: number;
2364
2373
  /**
@@ -3041,6 +3050,16 @@ declare class WorkflowEngine {
3041
3050
  concurrency?: ConcurrencyConfig | undefined;
3042
3051
  executionTimeout?: string | number | undefined;
3043
3052
  validateInput?: ((input: unknown) => void | Promise<void>) | undefined;
3053
+ /**
3054
+ * The input as the body sees it: a schema's parsed (coerced/transformed) value, sync or async,
3055
+ * throwing on input that does not parse. When set, `start` parses the input once: a failure
3056
+ * rejects the start like a failed `validateInput`, and `validateInput` and the `singleton` and
3057
+ * `concurrency` keys receive the parsed value instead of the input as sent. Each turn's
3058
+ * singleton admission parses the stored input again for its key; a stored input that no
3059
+ * longer parses fails the run with `invalid_input` (a `SchemaValidationError`) there, before
3060
+ * the body runs or a turn is dispatched. The run still stores the input as sent. `@dudousxd/nestjs-durable` supplies it from `@Workflow({ input })`.
3061
+ */
3062
+ parseInput?: ((input: unknown) => unknown) | undefined;
3044
3063
  /** Typed/validated `searchAttributes` shape — see `RegisteredWorkflow.searchAttributesSchema`. */
3045
3064
  searchAttributesSchema?: SearchAttributesSchema | undefined;
3046
3065
  onEvent?: OnEventEntry[] | undefined;
@@ -10332,6 +10351,13 @@ declare const SINGLETON_TRACKED_TAG = "durable:singleton:tracked";
10332
10351
  /** Tags only the engine/store may write; stripped from user-supplied start tags. */
10333
10352
  declare const SINGLETON_RESERVED_TAGS: readonly string[];
10334
10353
  declare const SINGLETON_ACTIVE_STATUSES: RunStatus[];
10354
+ /**
10355
+ * The `singleton:<key>` tag the ENGINE stamped on a run: the last tag with that prefix. A start
10356
+ * appends it after the caller's tags, and since 0.104.0 a caller's `singleton:` tags are dropped,
10357
+ * but a run started earlier can still carry one ahead of the engine's; reading the last one keeps
10358
+ * such a run under its real key until it settles. Never one of the `durable:singleton:*` markers.
10359
+ */
10360
+ declare function singletonKeyTag(tags: readonly string[] | undefined): string | undefined;
10335
10361
  /** `tags` without the engine's singleton admission metadata. */
10336
10362
  declare function withoutSingletonMarkers(tags: string[] | undefined): string[] | undefined;
10337
10363
  /** `tags` carrying {@link SINGLETON_TRACKED_TAG} (unchanged when admitted or already tracked). */
@@ -10444,4 +10470,4 @@ declare function prevRRuleFireMs(rule: ParsedRRule, atMs: number): number | null
10444
10470
  */
10445
10471
  declare function settleResultsWithPlainCalls(store: Pick<StateStore, 'getRun' | 'getCheckpoint'> & Partial<Pick<StateStore, 'getRuns' | 'getCheckpointsForSettle' | 'getCheckpoints' | 'settleCheckpointsIfPending'>>, results: StepResultSettlement[]): Promise<(StepCheckpoint | null)[]>;
10446
10472
 
10447
- export { ACCUMULATOR_SEEN_MAX, ANNOUNCED_SCHEDULE_TAG, ANY_WAIT_GROUP, type AccumulatorHost, type AccumulatorStartOptions, type Admission, type AdmissionBackend, type AdmissionItem, type AllOptions, type AllSettledOptions, type AllStepsOptions, type AllStepsSettledOptions, type AnnouncedSchedule, type AnnouncedScheduleSync, type AnnouncedWorkflow, type AnnouncedWorkflowOptions, type AnnouncementEvidence, type AttributeFilter, type AttributeOp, type AttributePredicateOperand, type AttributeValue, type AttributedEngineEvent, type BackoffStrategy, type BlockedDispatch, type BlockedResolution, type BufferedSignalRow, CHILD_EDGE_PREFIXES, CONTROL_FLOW_SIGNAL, CORE_ORIGIN, CURRENT_PROTOCOL_VERSION, type CapabilityRequirement, type CheckpointAggregatingStore, type CheckpointNameKind, type CheckpointQuery, type CheckpointStat, type ChildCallOptions, type ChildWait, CodecStateStore, type CodecStateStoreOptions, type ConcurrencyConfig, ConcurrencyLimitError, type ConcurrencyQuota, type ConsoleCapabilities, type ConsoleFederation, ContinueAsNew, type ControlMessage, type ControlPlane, DEFAULT_ANNOUNCED_SCHEDULE_GRACE_MS, DEFAULT_CONCURRENCY_STATUSES, DEFAULT_PARTITION, DEFAULT_STALLED_AFTER_MS, DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL, DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, type Disagreement, type DispatchDiagnostics, type DispatchPlan, DuplicateDurableCopyError, type DurableCopy, type DurableExecution, type DurableExecutionWrapper, type DurableTopology, type DurableWebhook, DurableWorkflow, type DynamicWorkflowCtx, ENGINE_MINTED_TAG_PREFIXES, ENTITY_WORKFLOW, EVENT_BUFFER_SCAN_LIMIT, EVENT_TOKEN_PREFIX, type EngineEvent, type EngineEventType, type EngineListener, type EngineTenancy, Entities, type EntityConfig, type EntityHandler, type EntityHost, type EntityWorkflowHost, EventAccumulators, type EventBatchConfig, type EventSubscription, FAN_SUMMARY_FAILURES, type FanJoin, type FanPage, type FanPageQuery, type FanSummary, type FanWait, FatalError, type FindStalledRunsOptions, GatherError, type GatherItemFailure, type GroupHealth, HANDOFF_SEQ_BASE, type Heartbeat, type HeartbeatSighting, type HeartbeatStatus, type HistoryEvent, InMemoryAdmissionBackend, InMemoryRunQueue, InMemoryStateStore, InMemoryTransport, type InferSearchAttributes, LEGACY_V1_CAPABILITIES, LEGACY_V1_PROTOCOL, LIFECYCLE_COALESCED_TAG_PREFIX, LIFECYCLE_HEAL_WINDOW_MS, LIFECYCLE_ORPHAN_MS, LIFECYCLE_OWED_TAG_PREFIX, LIFECYCLE_PENDING_TAG, LIFECYCLE_REGISTRY_HEARTBEAT_MS, LIFECYCLE_REGISTRY_STALE_MS, LIFECYCLE_REGISTRY_TAG, LIFECYCLE_REGISTRY_TTL_MS, LIFECYCLE_REGISTRY_WORKFLOW, LIFECYCLE_TRACE_TAG_PREFIX, LIFECYCLE_TRIGGERED_TAG_PREFIX, LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX, type LifecycleDelivery, type LifecycleDeliveryState, type LifecycleEventOf, type LifecycleKind, type LifecycleRegistryEntry, type LifecycleSource, type LifecycleSubscriptionLink, type ListStalledRunsOptions, type MetricsCollector, type MetricsSnapshot, NO_LIVE_WORKER, type NamedTransport, type NegotiateOptions, type NegotiationOutcome, type NegotiationReason, type NegotiationResult, NestedWorkflowCallError, NonDeterminismError, type OnErrorInput, type OnErrorRoute, type OnEventEntry, type OwnedLeaseReclaim, PARENT_CLOSE_TAG_PREFIX, type ParentClosePolicy, type ParsedRRule, type PartitionSighting, type PayloadCodec, type QueueConfig, QueueController, REMOTE_EVENT, REMOTE_WORKFLOW_FEATURES, RUN_HISTORY_FIXTURE_VERSION, RUN_VALUE_FACET_LIMIT, RUN_VALUE_FACET_SCAN, RUN_WAIT_TOKEN_PREFIX, type RawWorkerDescriptor, type RemoteCallPolicy, RemoteStepError, RemoteStepTimeout, type RemoteTask, RemoteWorkflowExecutor, type RemoteWorkflowFeature, RemoteWorkflowTimeout, type RepublishLifecycleResult, type RepublishLifecycleTarget, type RetentionPolicy, type RoutableDispatch, type RoutableResolution, type RoutingResolution, type RunAppAttribution, RunAppStamper, type RunAppTopologyOptions, type RunAttributeRow, type RunConsumerOptions, type RunDetail, type RunDetailOptions, type RunDispatch, type RunDispatcher, type RunFacetQuery, type RunFacetRow, RunGateway, type RunListItem, type RunQuery, type RunQueueOptions, type RunReply, type RunReplyResult, type RunRequest, type RunRequestKind, type RunResult, type RunSchedulesOptions, type RunScope, type RunStatus, type RunTenant, type RunValueAxis, type RunValueFacetOptions, type RunValueFacetOrder, type RunValueFacetRow, type RunWaitLink, type RunWaiting, SINGLETON_ACTIVE_STATUSES, SINGLETON_ADMITTED_TAG, SINGLETON_LOCK_CHUNK, SINGLETON_RESERVED_TAGS, SINGLETON_TRACKED_TAG, STATE_STORE, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, type ScalarAttributeFilter, type ScheduleAction, ScheduleAlreadyExistsError, type ScheduleAnnouncement, ScheduleClient, type ScheduleClientOptions, type ScheduleDescription, type ScheduleHost, type ScheduleListQuery, ScheduleNotFoundError, type ScheduleOptions, type ScheduleQuery, type ScheduleRecord, type ScheduleTickEngine, type ScheduledWorkflow, type SchemaIssue, type SchemaValidationCode, SchemaValidationError, type SearchAttributes, type SearchAttributesSchema, type Settled, type SignalOptions, SignalTimeoutError, type SignalWaiter, type SingletonConfig, SingletonQueueFullError, type StalePendingStep, type StalledRunInfo, StandardSchemaV1, type StartOptions, type StartRunMessage, type StartRunSingleton, type StateStore, type StepCheckpoint, type StepConfig, type StepDef, type StepDispatchOpts, type StepError, type StepEvent, type StepHandler, type StepInterceptor, type StepInvocation, type StepKind, type StepLogger, type StepOptions, type StepRef, type StepResult, type StepResultSettlement, type StepScope, type StepSettlement, type StepUndo, type StoreTransaction, type SubProcessHandle, TERMINAL_RUN_STATUSES, TRANSPORT, TRANSPORT_CANONICAL, type TenantEvent, type TenantFilter, type TenantRow, type TenantTokenSource, type TenantVerifier, type Transport, type UndoOf, type UpdateResult, type UpdateValidator, VERSION_UNDECLARED_TAG, type VerifiedTenant, WORKFLOW_NAME_KEY, type WaitAnyCondition, type WaitAnyOutcome, type WaitAnyResult, type WaitCondition, type WaitConditionSpec, type WaitForRunOptions, type WireDates, type WorkerAdjust, type WorkerConcurrencyStatus, type WorkerDescriptor, type WorkerHeartbeat, type WorkerLifecycle, type WorkerStatus, type WorkflowAnnouncement, WorkflowBlocked, type WorkflowClass, type WorkflowCommand, type WorkflowCtx, type WorkflowDecision, type WorkflowDirectory, WorkflowEngine, type WorkflowEngineDeps, type WorkflowExecutor, type WorkflowHandler, type WorkflowInputOf, type WorkflowLifecycleEvent, type WorkflowLifecycleLinks, WorkflowNotRegistered, type WorkflowOutputOf, type WorkflowRef, type WorkflowRegistration, type WorkflowRun, type WorkflowStartClient, type WorkflowStepEvent, WorkflowSuspended, type WorkflowTask, acceptingSubscription, accumulatorRunId, aggregateAnnouncements, aggregatesCheckpoints, announcedScheduleId, announcementsOf, anyCheckpointName, applyAttributeQuery, assertConcurrency, assertRoutes, assertSingleDurableCopy, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, bufferedEventReaches, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneAttribution, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, durableCopies, error, etagMatches, eventMatchOf, eventMatches, eventNameOf, eventPrefix, eventToken, extendEtag, facetOrigin, fanPageBounds, fanPageEtag, findStalledRuns, foldedCount, getRunsByIds, grantsClientTenant, handoffHandlerId, handoffName, hasDurableExecutionWrappers, heartbeatStatus, hmacTenantVerifier, indexWaitersByRun, info, inheritTenant, isAnyCheckpoint, isAnyMember, isEngineMintedTag, isEventToken, isFailedMember, isLegacyDescriptor, isLifecycleTag, isNonEmptyRunScope, isRemoteEvent, isWorkflowControlFlowSignal, legacySingletonHolders, lifecycleDeliveriesOf, lifecycleEventName, lifecycleEventOf, lifecycleKindOf, lifecycleRegistryNamespace, lifecycleRegistryRunId, lifecycleRegistrySubscriptions, lifecycleRunId, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, liveHandoff, log, markRemoteEvent, matchesAttributes, matchesTenantPredicates, mergeRunFacetRows, mergeRunValueFacetRows, missingCapabilities, negotiate, nextCronFireMs, nextRRuleFireMs, nextScheduleFireAt, normalizeAttributeRows, normalizeDescriptor, observedAnnouncements, onErrorRunId, owedSubscribersOf, pageFan, pageFanFromStore, parentRunIdOf, parseDuration, parseLifecycleEvent, parseRRule, parseWebhookToken, partitionOfToken, planDispatch, poolNamespace, prevCronFireMs, prevRRuleFireMs, queryCheckpointsOf, readBufferedEvent, readRunsByIds, readSearchAttributes, remoteCallMaxAttempts, remoteCallPolicyOf, remoteCallRetries, requiredCapabilities, resolveConcurrency, resolveRouting, resolveRunWaiting, resolveTenantToken, resolveWireTenant, retentionKeeps, retiredHandoffName, routeFor, rowTenant, runCompletedEvent, runDetailEtag, runDurableExecution, runFailedEvent, runInStepLogger, runInStepScope, runInWorkflowCtx, runOutsideWorkflowCtx, runSchedules, runStepHandler, runTraceId, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, scopeBufferedEvent, scopeTenantQuery, sealDurableCopies, settleResultsWithPlainCalls, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantAppOf, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
10473
+ export { ACCUMULATOR_SEEN_MAX, ANNOUNCED_SCHEDULE_TAG, ANY_WAIT_GROUP, type AccumulatorHost, type AccumulatorStartOptions, type Admission, type AdmissionBackend, type AdmissionItem, type AllOptions, type AllSettledOptions, type AllStepsOptions, type AllStepsSettledOptions, type AnnouncedSchedule, type AnnouncedScheduleSync, type AnnouncedWorkflow, type AnnouncedWorkflowOptions, type AnnouncementEvidence, type AttributeFilter, type AttributeOp, type AttributePredicateOperand, type AttributeValue, type AttributedEngineEvent, type BackoffStrategy, type BlockedDispatch, type BlockedResolution, type BufferedSignalRow, CHILD_EDGE_PREFIXES, CONTROL_FLOW_SIGNAL, CORE_ORIGIN, CURRENT_PROTOCOL_VERSION, type CapabilityRequirement, type CheckpointAggregatingStore, type CheckpointNameKind, type CheckpointQuery, type CheckpointStat, type ChildCallOptions, type ChildWait, CodecStateStore, type CodecStateStoreOptions, type ConcurrencyConfig, ConcurrencyLimitError, type ConcurrencyQuota, type ConsoleCapabilities, type ConsoleFederation, ContinueAsNew, type ControlMessage, type ControlPlane, DEFAULT_ANNOUNCED_SCHEDULE_GRACE_MS, DEFAULT_CONCURRENCY_STATUSES, DEFAULT_PARTITION, DEFAULT_STALLED_AFTER_MS, DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL, DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, type Disagreement, type DispatchDiagnostics, type DispatchPlan, DuplicateDurableCopyError, type DurableCopy, type DurableExecution, type DurableExecutionWrapper, type DurableTopology, type DurableWebhook, DurableWorkflow, type DynamicWorkflowCtx, ENGINE_MINTED_TAG_PREFIXES, ENTITY_WORKFLOW, EVENT_BUFFER_SCAN_LIMIT, EVENT_TOKEN_PREFIX, type EngineEvent, type EngineEventType, type EngineListener, type EngineTenancy, Entities, type EntityConfig, type EntityHandler, type EntityHost, type EntityWorkflowHost, EventAccumulators, type EventBatchConfig, type EventSubscription, FAN_SUMMARY_FAILURES, type FanJoin, type FanPage, type FanPageQuery, type FanSummary, type FanWait, FatalError, type FindStalledRunsOptions, GatherError, type GatherItemFailure, type GroupHealth, HANDOFF_SEQ_BASE, type Heartbeat, type HeartbeatSighting, type HeartbeatStatus, type HistoryEvent, InMemoryAdmissionBackend, InMemoryRunQueue, InMemoryStateStore, InMemoryTransport, type InferSearchAttributes, LEGACY_V1_CAPABILITIES, LEGACY_V1_PROTOCOL, LIFECYCLE_COALESCED_TAG_PREFIX, LIFECYCLE_HEAL_WINDOW_MS, LIFECYCLE_ORPHAN_MS, LIFECYCLE_OWED_TAG_PREFIX, LIFECYCLE_PENDING_TAG, LIFECYCLE_REGISTRY_HEARTBEAT_MS, LIFECYCLE_REGISTRY_STALE_MS, LIFECYCLE_REGISTRY_TAG, LIFECYCLE_REGISTRY_TTL_MS, LIFECYCLE_REGISTRY_WORKFLOW, LIFECYCLE_TRACE_TAG_PREFIX, LIFECYCLE_TRIGGERED_TAG_PREFIX, LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX, type LifecycleDelivery, type LifecycleDeliveryState, type LifecycleEventOf, type LifecycleKind, type LifecycleRegistryEntry, type LifecycleSource, type LifecycleSubscriptionLink, type ListStalledRunsOptions, type MetricsCollector, type MetricsSnapshot, NO_LIVE_WORKER, type NamedTransport, type NegotiateOptions, type NegotiationOutcome, type NegotiationReason, type NegotiationResult, NestedWorkflowCallError, NonDeterminismError, type OnErrorInput, type OnErrorRoute, type OnEventEntry, type OwnedLeaseReclaim, PARENT_CLOSE_TAG_PREFIX, type ParentClosePolicy, type ParsedRRule, type PartitionSighting, type PayloadCodec, type QueueConfig, QueueController, REMOTE_EVENT, REMOTE_WORKFLOW_FEATURES, RUN_HISTORY_FIXTURE_VERSION, RUN_VALUE_FACET_LIMIT, RUN_VALUE_FACET_SCAN, RUN_WAIT_TOKEN_PREFIX, type RawWorkerDescriptor, type RemoteCallPolicy, RemoteStepError, RemoteStepTimeout, type RemoteTask, RemoteWorkflowExecutor, type RemoteWorkflowFeature, RemoteWorkflowTimeout, type RepublishLifecycleResult, type RepublishLifecycleTarget, type RetentionPolicy, type RoutableDispatch, type RoutableResolution, type RoutingResolution, type RunAppAttribution, RunAppStamper, type RunAppTopologyOptions, type RunAttributeRow, type RunConsumerOptions, type RunDetail, type RunDetailOptions, type RunDispatch, type RunDispatcher, type RunFacetQuery, type RunFacetRow, RunGateway, type RunListItem, type RunQuery, type RunQueueOptions, type RunReply, type RunReplyResult, type RunRequest, type RunRequestKind, type RunResult, type RunSchedulesOptions, type RunScope, type RunStatus, type RunTenant, type RunValueAxis, type RunValueFacetOptions, type RunValueFacetOrder, type RunValueFacetRow, type RunWaitLink, type RunWaiting, SINGLETON_ACTIVE_STATUSES, SINGLETON_ADMITTED_TAG, SINGLETON_LOCK_CHUNK, SINGLETON_RESERVED_TAGS, SINGLETON_TRACKED_TAG, STATE_STORE, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, type ScalarAttributeFilter, type ScheduleAction, ScheduleAlreadyExistsError, type ScheduleAnnouncement, ScheduleClient, type ScheduleClientOptions, type ScheduleDescription, type ScheduleHost, type ScheduleListQuery, ScheduleNotFoundError, type ScheduleOptions, type ScheduleQuery, type ScheduleRecord, type ScheduleTickEngine, type ScheduledWorkflow, type SchemaIssue, type SchemaValidationCode, SchemaValidationError, type SearchAttributes, type SearchAttributesSchema, type Settled, type SignalOptions, SignalTimeoutError, type SignalWaiter, type SingletonConfig, SingletonQueueFullError, type StalePendingStep, type StalledRunInfo, StandardSchemaV1, type StartOptions, type StartRunMessage, type StartRunSingleton, type StateStore, type StepCheckpoint, type StepConfig, type StepDef, type StepDispatchOpts, type StepError, type StepEvent, type StepHandler, type StepInterceptor, type StepInvocation, type StepKind, type StepLogger, type StepOptions, type StepRef, type StepResult, type StepResultSettlement, type StepScope, type StepSettlement, type StepUndo, type StoreTransaction, type SubProcessHandle, TERMINAL_RUN_STATUSES, TRANSPORT, TRANSPORT_CANONICAL, type TenantEvent, type TenantFilter, type TenantRow, type TenantTokenSource, type TenantVerifier, type Transport, type UndoOf, type UpdateResult, type UpdateValidator, VERSION_UNDECLARED_TAG, type VerifiedTenant, WORKFLOW_NAME_KEY, type WaitAnyCondition, type WaitAnyOutcome, type WaitAnyResult, type WaitCondition, type WaitConditionSpec, type WaitForRunOptions, type WireDates, type WorkerAdjust, type WorkerConcurrencyStatus, type WorkerDescriptor, type WorkerHeartbeat, type WorkerLifecycle, type WorkerStatus, type WorkflowAnnouncement, WorkflowBlocked, type WorkflowClass, type WorkflowCommand, type WorkflowCtx, type WorkflowDecision, type WorkflowDirectory, WorkflowEngine, type WorkflowEngineDeps, type WorkflowExecutor, type WorkflowHandler, type WorkflowInputOf, type WorkflowLifecycleEvent, type WorkflowLifecycleLinks, WorkflowNotRegistered, type WorkflowOutputOf, type WorkflowRef, type WorkflowRegistration, type WorkflowRun, type WorkflowStartClient, type WorkflowStepEvent, WorkflowSuspended, type WorkflowTask, acceptingSubscription, accumulatorRunId, aggregateAnnouncements, aggregatesCheckpoints, announcedScheduleId, announcementsOf, anyCheckpointName, applyAttributeQuery, assertConcurrency, assertRoutes, assertSingleDurableCopy, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, bufferedEventReaches, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneAttribution, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, durableCopies, error, etagMatches, eventMatchOf, eventMatches, eventNameOf, eventPrefix, eventToken, extendEtag, facetOrigin, fanPageBounds, fanPageEtag, findStalledRuns, foldedCount, getRunsByIds, grantsClientTenant, handoffHandlerId, handoffName, hasDurableExecutionWrappers, heartbeatStatus, hmacTenantVerifier, indexWaitersByRun, info, inheritTenant, isAnyCheckpoint, isAnyMember, isEngineMintedTag, isEventToken, isFailedMember, isLegacyDescriptor, isLifecycleTag, isNonEmptyRunScope, isRemoteEvent, isWorkflowControlFlowSignal, legacySingletonHolders, lifecycleDeliveriesOf, lifecycleEventName, lifecycleEventOf, lifecycleKindOf, lifecycleRegistryNamespace, lifecycleRegistryRunId, lifecycleRegistrySubscriptions, lifecycleRunId, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, liveHandoff, log, markRemoteEvent, matchesAttributes, matchesTenantPredicates, mergeRunFacetRows, mergeRunValueFacetRows, missingCapabilities, negotiate, nextCronFireMs, nextRRuleFireMs, nextScheduleFireAt, normalizeAttributeRows, normalizeDescriptor, observedAnnouncements, onErrorRunId, owedSubscribersOf, pageFan, pageFanFromStore, parentRunIdOf, parseDuration, parseLifecycleEvent, parseRRule, parseWebhookToken, partitionOfToken, planDispatch, poolNamespace, prevCronFireMs, prevRRuleFireMs, queryCheckpointsOf, readBufferedEvent, readRunsByIds, readSearchAttributes, remoteCallMaxAttempts, remoteCallPolicyOf, remoteCallRetries, requiredCapabilities, resolveConcurrency, resolveRouting, resolveRunWaiting, resolveTenantToken, resolveWireTenant, retentionKeeps, retiredHandoffName, routeFor, rowTenant, runCompletedEvent, runDetailEtag, runDurableExecution, runFailedEvent, runInStepLogger, runInStepScope, runInWorkflowCtx, runOutsideWorkflowCtx, runSchedules, runStepHandler, runTraceId, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, scopeBufferedEvent, scopeTenantQuery, sealDurableCopies, settleResultsWithPlainCalls, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, singletonKeyTag, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantAppOf, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
package/dist/index.d.ts CHANGED
@@ -187,9 +187,14 @@ interface ConcurrencyQuota {
187
187
  * / `@Workflow({ concurrency })`): the key is derived from each start's input, and the limit may be a
188
188
  * function of the key (per-tenant plans). A `StartOptions.concurrency` on one start overrides it.
189
189
  */
190
- interface ConcurrencyConfig {
191
- /** Derive the quota key from the input. Return `undefined` to leave this start unlimited. */
192
- key: (input: unknown) => string | undefined;
190
+ interface ConcurrencyConfig<TInput = unknown> {
191
+ /**
192
+ * Derive the quota key from the input. Return `undefined` to leave this start unlimited. When the
193
+ * workflow declares an input schema (`@Workflow({ input })`, or `register(..., { parseInput })`),
194
+ * it receives the PARSED input, the same value `run(ctx, input)` gets, and `@Workflow` types
195
+ * `TInput` from the schema.
196
+ */
197
+ key: (input: TInput) => string | undefined;
193
198
  /** Max in-flight runs per key — a number, or resolved per key (e.g. from the tenant's plan). */
194
199
  limit: number | ((key: string) => number | Promise<number>);
195
200
  /** Which statuses occupy a slot. See {@link ConcurrencyQuota.countStatuses}. */
@@ -2356,9 +2361,13 @@ interface StartOptions {
2356
2361
  * admission on a timer until a slot frees. The store atomically reserves durable slots before
2357
2362
  * ordering unadmitted waiters by `(createdAt, id)`, so later starts cannot displace a holder.
2358
2363
  */
2359
- interface SingletonConfig {
2360
- /** Derive the serialization key from the workflow input. */
2361
- key: (input: unknown) => string;
2364
+ interface SingletonConfig<TInput = unknown> {
2365
+ /**
2366
+ * Derive the serialization key from the workflow input. When the workflow declares an input schema
2367
+ * (`@Workflow({ input })`, or `register(..., { parseInput })`), it receives the PARSED input, the
2368
+ * same value `run(ctx, input)` gets, and `@Workflow` types `TInput` from the schema.
2369
+ */
2370
+ key: (input: TInput) => string;
2362
2371
  /** Max concurrent runs sharing the key. Default 1 (a mutex). */
2363
2372
  limit?: number;
2364
2373
  /**
@@ -3041,6 +3050,16 @@ declare class WorkflowEngine {
3041
3050
  concurrency?: ConcurrencyConfig | undefined;
3042
3051
  executionTimeout?: string | number | undefined;
3043
3052
  validateInput?: ((input: unknown) => void | Promise<void>) | undefined;
3053
+ /**
3054
+ * The input as the body sees it: a schema's parsed (coerced/transformed) value, sync or async,
3055
+ * throwing on input that does not parse. When set, `start` parses the input once: a failure
3056
+ * rejects the start like a failed `validateInput`, and `validateInput` and the `singleton` and
3057
+ * `concurrency` keys receive the parsed value instead of the input as sent. Each turn's
3058
+ * singleton admission parses the stored input again for its key; a stored input that no
3059
+ * longer parses fails the run with `invalid_input` (a `SchemaValidationError`) there, before
3060
+ * the body runs or a turn is dispatched. The run still stores the input as sent. `@dudousxd/nestjs-durable` supplies it from `@Workflow({ input })`.
3061
+ */
3062
+ parseInput?: ((input: unknown) => unknown) | undefined;
3044
3063
  /** Typed/validated `searchAttributes` shape — see `RegisteredWorkflow.searchAttributesSchema`. */
3045
3064
  searchAttributesSchema?: SearchAttributesSchema | undefined;
3046
3065
  onEvent?: OnEventEntry[] | undefined;
@@ -10332,6 +10351,13 @@ declare const SINGLETON_TRACKED_TAG = "durable:singleton:tracked";
10332
10351
  /** Tags only the engine/store may write; stripped from user-supplied start tags. */
10333
10352
  declare const SINGLETON_RESERVED_TAGS: readonly string[];
10334
10353
  declare const SINGLETON_ACTIVE_STATUSES: RunStatus[];
10354
+ /**
10355
+ * The `singleton:<key>` tag the ENGINE stamped on a run: the last tag with that prefix. A start
10356
+ * appends it after the caller's tags, and since 0.104.0 a caller's `singleton:` tags are dropped,
10357
+ * but a run started earlier can still carry one ahead of the engine's; reading the last one keeps
10358
+ * such a run under its real key until it settles. Never one of the `durable:singleton:*` markers.
10359
+ */
10360
+ declare function singletonKeyTag(tags: readonly string[] | undefined): string | undefined;
10335
10361
  /** `tags` without the engine's singleton admission metadata. */
10336
10362
  declare function withoutSingletonMarkers(tags: string[] | undefined): string[] | undefined;
10337
10363
  /** `tags` carrying {@link SINGLETON_TRACKED_TAG} (unchanged when admitted or already tracked). */
@@ -10444,4 +10470,4 @@ declare function prevRRuleFireMs(rule: ParsedRRule, atMs: number): number | null
10444
10470
  */
10445
10471
  declare function settleResultsWithPlainCalls(store: Pick<StateStore, 'getRun' | 'getCheckpoint'> & Partial<Pick<StateStore, 'getRuns' | 'getCheckpointsForSettle' | 'getCheckpoints' | 'settleCheckpointsIfPending'>>, results: StepResultSettlement[]): Promise<(StepCheckpoint | null)[]>;
10446
10472
 
10447
- export { ACCUMULATOR_SEEN_MAX, ANNOUNCED_SCHEDULE_TAG, ANY_WAIT_GROUP, type AccumulatorHost, type AccumulatorStartOptions, type Admission, type AdmissionBackend, type AdmissionItem, type AllOptions, type AllSettledOptions, type AllStepsOptions, type AllStepsSettledOptions, type AnnouncedSchedule, type AnnouncedScheduleSync, type AnnouncedWorkflow, type AnnouncedWorkflowOptions, type AnnouncementEvidence, type AttributeFilter, type AttributeOp, type AttributePredicateOperand, type AttributeValue, type AttributedEngineEvent, type BackoffStrategy, type BlockedDispatch, type BlockedResolution, type BufferedSignalRow, CHILD_EDGE_PREFIXES, CONTROL_FLOW_SIGNAL, CORE_ORIGIN, CURRENT_PROTOCOL_VERSION, type CapabilityRequirement, type CheckpointAggregatingStore, type CheckpointNameKind, type CheckpointQuery, type CheckpointStat, type ChildCallOptions, type ChildWait, CodecStateStore, type CodecStateStoreOptions, type ConcurrencyConfig, ConcurrencyLimitError, type ConcurrencyQuota, type ConsoleCapabilities, type ConsoleFederation, ContinueAsNew, type ControlMessage, type ControlPlane, DEFAULT_ANNOUNCED_SCHEDULE_GRACE_MS, DEFAULT_CONCURRENCY_STATUSES, DEFAULT_PARTITION, DEFAULT_STALLED_AFTER_MS, DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL, DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, type Disagreement, type DispatchDiagnostics, type DispatchPlan, DuplicateDurableCopyError, type DurableCopy, type DurableExecution, type DurableExecutionWrapper, type DurableTopology, type DurableWebhook, DurableWorkflow, type DynamicWorkflowCtx, ENGINE_MINTED_TAG_PREFIXES, ENTITY_WORKFLOW, EVENT_BUFFER_SCAN_LIMIT, EVENT_TOKEN_PREFIX, type EngineEvent, type EngineEventType, type EngineListener, type EngineTenancy, Entities, type EntityConfig, type EntityHandler, type EntityHost, type EntityWorkflowHost, EventAccumulators, type EventBatchConfig, type EventSubscription, FAN_SUMMARY_FAILURES, type FanJoin, type FanPage, type FanPageQuery, type FanSummary, type FanWait, FatalError, type FindStalledRunsOptions, GatherError, type GatherItemFailure, type GroupHealth, HANDOFF_SEQ_BASE, type Heartbeat, type HeartbeatSighting, type HeartbeatStatus, type HistoryEvent, InMemoryAdmissionBackend, InMemoryRunQueue, InMemoryStateStore, InMemoryTransport, type InferSearchAttributes, LEGACY_V1_CAPABILITIES, LEGACY_V1_PROTOCOL, LIFECYCLE_COALESCED_TAG_PREFIX, LIFECYCLE_HEAL_WINDOW_MS, LIFECYCLE_ORPHAN_MS, LIFECYCLE_OWED_TAG_PREFIX, LIFECYCLE_PENDING_TAG, LIFECYCLE_REGISTRY_HEARTBEAT_MS, LIFECYCLE_REGISTRY_STALE_MS, LIFECYCLE_REGISTRY_TAG, LIFECYCLE_REGISTRY_TTL_MS, LIFECYCLE_REGISTRY_WORKFLOW, LIFECYCLE_TRACE_TAG_PREFIX, LIFECYCLE_TRIGGERED_TAG_PREFIX, LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX, type LifecycleDelivery, type LifecycleDeliveryState, type LifecycleEventOf, type LifecycleKind, type LifecycleRegistryEntry, type LifecycleSource, type LifecycleSubscriptionLink, type ListStalledRunsOptions, type MetricsCollector, type MetricsSnapshot, NO_LIVE_WORKER, type NamedTransport, type NegotiateOptions, type NegotiationOutcome, type NegotiationReason, type NegotiationResult, NestedWorkflowCallError, NonDeterminismError, type OnErrorInput, type OnErrorRoute, type OnEventEntry, type OwnedLeaseReclaim, PARENT_CLOSE_TAG_PREFIX, type ParentClosePolicy, type ParsedRRule, type PartitionSighting, type PayloadCodec, type QueueConfig, QueueController, REMOTE_EVENT, REMOTE_WORKFLOW_FEATURES, RUN_HISTORY_FIXTURE_VERSION, RUN_VALUE_FACET_LIMIT, RUN_VALUE_FACET_SCAN, RUN_WAIT_TOKEN_PREFIX, type RawWorkerDescriptor, type RemoteCallPolicy, RemoteStepError, RemoteStepTimeout, type RemoteTask, RemoteWorkflowExecutor, type RemoteWorkflowFeature, RemoteWorkflowTimeout, type RepublishLifecycleResult, type RepublishLifecycleTarget, type RetentionPolicy, type RoutableDispatch, type RoutableResolution, type RoutingResolution, type RunAppAttribution, RunAppStamper, type RunAppTopologyOptions, type RunAttributeRow, type RunConsumerOptions, type RunDetail, type RunDetailOptions, type RunDispatch, type RunDispatcher, type RunFacetQuery, type RunFacetRow, RunGateway, type RunListItem, type RunQuery, type RunQueueOptions, type RunReply, type RunReplyResult, type RunRequest, type RunRequestKind, type RunResult, type RunSchedulesOptions, type RunScope, type RunStatus, type RunTenant, type RunValueAxis, type RunValueFacetOptions, type RunValueFacetOrder, type RunValueFacetRow, type RunWaitLink, type RunWaiting, SINGLETON_ACTIVE_STATUSES, SINGLETON_ADMITTED_TAG, SINGLETON_LOCK_CHUNK, SINGLETON_RESERVED_TAGS, SINGLETON_TRACKED_TAG, STATE_STORE, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, type ScalarAttributeFilter, type ScheduleAction, ScheduleAlreadyExistsError, type ScheduleAnnouncement, ScheduleClient, type ScheduleClientOptions, type ScheduleDescription, type ScheduleHost, type ScheduleListQuery, ScheduleNotFoundError, type ScheduleOptions, type ScheduleQuery, type ScheduleRecord, type ScheduleTickEngine, type ScheduledWorkflow, type SchemaIssue, type SchemaValidationCode, SchemaValidationError, type SearchAttributes, type SearchAttributesSchema, type Settled, type SignalOptions, SignalTimeoutError, type SignalWaiter, type SingletonConfig, SingletonQueueFullError, type StalePendingStep, type StalledRunInfo, StandardSchemaV1, type StartOptions, type StartRunMessage, type StartRunSingleton, type StateStore, type StepCheckpoint, type StepConfig, type StepDef, type StepDispatchOpts, type StepError, type StepEvent, type StepHandler, type StepInterceptor, type StepInvocation, type StepKind, type StepLogger, type StepOptions, type StepRef, type StepResult, type StepResultSettlement, type StepScope, type StepSettlement, type StepUndo, type StoreTransaction, type SubProcessHandle, TERMINAL_RUN_STATUSES, TRANSPORT, TRANSPORT_CANONICAL, type TenantEvent, type TenantFilter, type TenantRow, type TenantTokenSource, type TenantVerifier, type Transport, type UndoOf, type UpdateResult, type UpdateValidator, VERSION_UNDECLARED_TAG, type VerifiedTenant, WORKFLOW_NAME_KEY, type WaitAnyCondition, type WaitAnyOutcome, type WaitAnyResult, type WaitCondition, type WaitConditionSpec, type WaitForRunOptions, type WireDates, type WorkerAdjust, type WorkerConcurrencyStatus, type WorkerDescriptor, type WorkerHeartbeat, type WorkerLifecycle, type WorkerStatus, type WorkflowAnnouncement, WorkflowBlocked, type WorkflowClass, type WorkflowCommand, type WorkflowCtx, type WorkflowDecision, type WorkflowDirectory, WorkflowEngine, type WorkflowEngineDeps, type WorkflowExecutor, type WorkflowHandler, type WorkflowInputOf, type WorkflowLifecycleEvent, type WorkflowLifecycleLinks, WorkflowNotRegistered, type WorkflowOutputOf, type WorkflowRef, type WorkflowRegistration, type WorkflowRun, type WorkflowStartClient, type WorkflowStepEvent, WorkflowSuspended, type WorkflowTask, acceptingSubscription, accumulatorRunId, aggregateAnnouncements, aggregatesCheckpoints, announcedScheduleId, announcementsOf, anyCheckpointName, applyAttributeQuery, assertConcurrency, assertRoutes, assertSingleDurableCopy, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, bufferedEventReaches, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneAttribution, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, durableCopies, error, etagMatches, eventMatchOf, eventMatches, eventNameOf, eventPrefix, eventToken, extendEtag, facetOrigin, fanPageBounds, fanPageEtag, findStalledRuns, foldedCount, getRunsByIds, grantsClientTenant, handoffHandlerId, handoffName, hasDurableExecutionWrappers, heartbeatStatus, hmacTenantVerifier, indexWaitersByRun, info, inheritTenant, isAnyCheckpoint, isAnyMember, isEngineMintedTag, isEventToken, isFailedMember, isLegacyDescriptor, isLifecycleTag, isNonEmptyRunScope, isRemoteEvent, isWorkflowControlFlowSignal, legacySingletonHolders, lifecycleDeliveriesOf, lifecycleEventName, lifecycleEventOf, lifecycleKindOf, lifecycleRegistryNamespace, lifecycleRegistryRunId, lifecycleRegistrySubscriptions, lifecycleRunId, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, liveHandoff, log, markRemoteEvent, matchesAttributes, matchesTenantPredicates, mergeRunFacetRows, mergeRunValueFacetRows, missingCapabilities, negotiate, nextCronFireMs, nextRRuleFireMs, nextScheduleFireAt, normalizeAttributeRows, normalizeDescriptor, observedAnnouncements, onErrorRunId, owedSubscribersOf, pageFan, pageFanFromStore, parentRunIdOf, parseDuration, parseLifecycleEvent, parseRRule, parseWebhookToken, partitionOfToken, planDispatch, poolNamespace, prevCronFireMs, prevRRuleFireMs, queryCheckpointsOf, readBufferedEvent, readRunsByIds, readSearchAttributes, remoteCallMaxAttempts, remoteCallPolicyOf, remoteCallRetries, requiredCapabilities, resolveConcurrency, resolveRouting, resolveRunWaiting, resolveTenantToken, resolveWireTenant, retentionKeeps, retiredHandoffName, routeFor, rowTenant, runCompletedEvent, runDetailEtag, runDurableExecution, runFailedEvent, runInStepLogger, runInStepScope, runInWorkflowCtx, runOutsideWorkflowCtx, runSchedules, runStepHandler, runTraceId, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, scopeBufferedEvent, scopeTenantQuery, sealDurableCopies, settleResultsWithPlainCalls, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantAppOf, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
10473
+ export { ACCUMULATOR_SEEN_MAX, ANNOUNCED_SCHEDULE_TAG, ANY_WAIT_GROUP, type AccumulatorHost, type AccumulatorStartOptions, type Admission, type AdmissionBackend, type AdmissionItem, type AllOptions, type AllSettledOptions, type AllStepsOptions, type AllStepsSettledOptions, type AnnouncedSchedule, type AnnouncedScheduleSync, type AnnouncedWorkflow, type AnnouncedWorkflowOptions, type AnnouncementEvidence, type AttributeFilter, type AttributeOp, type AttributePredicateOperand, type AttributeValue, type AttributedEngineEvent, type BackoffStrategy, type BlockedDispatch, type BlockedResolution, type BufferedSignalRow, CHILD_EDGE_PREFIXES, CONTROL_FLOW_SIGNAL, CORE_ORIGIN, CURRENT_PROTOCOL_VERSION, type CapabilityRequirement, type CheckpointAggregatingStore, type CheckpointNameKind, type CheckpointQuery, type CheckpointStat, type ChildCallOptions, type ChildWait, CodecStateStore, type CodecStateStoreOptions, type ConcurrencyConfig, ConcurrencyLimitError, type ConcurrencyQuota, type ConsoleCapabilities, type ConsoleFederation, ContinueAsNew, type ControlMessage, type ControlPlane, DEFAULT_ANNOUNCED_SCHEDULE_GRACE_MS, DEFAULT_CONCURRENCY_STATUSES, DEFAULT_PARTITION, DEFAULT_STALLED_AFTER_MS, DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL, DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, type Disagreement, type DispatchDiagnostics, type DispatchPlan, DuplicateDurableCopyError, type DurableCopy, type DurableExecution, type DurableExecutionWrapper, type DurableTopology, type DurableWebhook, DurableWorkflow, type DynamicWorkflowCtx, ENGINE_MINTED_TAG_PREFIXES, ENTITY_WORKFLOW, EVENT_BUFFER_SCAN_LIMIT, EVENT_TOKEN_PREFIX, type EngineEvent, type EngineEventType, type EngineListener, type EngineTenancy, Entities, type EntityConfig, type EntityHandler, type EntityHost, type EntityWorkflowHost, EventAccumulators, type EventBatchConfig, type EventSubscription, FAN_SUMMARY_FAILURES, type FanJoin, type FanPage, type FanPageQuery, type FanSummary, type FanWait, FatalError, type FindStalledRunsOptions, GatherError, type GatherItemFailure, type GroupHealth, HANDOFF_SEQ_BASE, type Heartbeat, type HeartbeatSighting, type HeartbeatStatus, type HistoryEvent, InMemoryAdmissionBackend, InMemoryRunQueue, InMemoryStateStore, InMemoryTransport, type InferSearchAttributes, LEGACY_V1_CAPABILITIES, LEGACY_V1_PROTOCOL, LIFECYCLE_COALESCED_TAG_PREFIX, LIFECYCLE_HEAL_WINDOW_MS, LIFECYCLE_ORPHAN_MS, LIFECYCLE_OWED_TAG_PREFIX, LIFECYCLE_PENDING_TAG, LIFECYCLE_REGISTRY_HEARTBEAT_MS, LIFECYCLE_REGISTRY_STALE_MS, LIFECYCLE_REGISTRY_TAG, LIFECYCLE_REGISTRY_TTL_MS, LIFECYCLE_REGISTRY_WORKFLOW, LIFECYCLE_TRACE_TAG_PREFIX, LIFECYCLE_TRIGGERED_TAG_PREFIX, LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX, type LifecycleDelivery, type LifecycleDeliveryState, type LifecycleEventOf, type LifecycleKind, type LifecycleRegistryEntry, type LifecycleSource, type LifecycleSubscriptionLink, type ListStalledRunsOptions, type MetricsCollector, type MetricsSnapshot, NO_LIVE_WORKER, type NamedTransport, type NegotiateOptions, type NegotiationOutcome, type NegotiationReason, type NegotiationResult, NestedWorkflowCallError, NonDeterminismError, type OnErrorInput, type OnErrorRoute, type OnEventEntry, type OwnedLeaseReclaim, PARENT_CLOSE_TAG_PREFIX, type ParentClosePolicy, type ParsedRRule, type PartitionSighting, type PayloadCodec, type QueueConfig, QueueController, REMOTE_EVENT, REMOTE_WORKFLOW_FEATURES, RUN_HISTORY_FIXTURE_VERSION, RUN_VALUE_FACET_LIMIT, RUN_VALUE_FACET_SCAN, RUN_WAIT_TOKEN_PREFIX, type RawWorkerDescriptor, type RemoteCallPolicy, RemoteStepError, RemoteStepTimeout, type RemoteTask, RemoteWorkflowExecutor, type RemoteWorkflowFeature, RemoteWorkflowTimeout, type RepublishLifecycleResult, type RepublishLifecycleTarget, type RetentionPolicy, type RoutableDispatch, type RoutableResolution, type RoutingResolution, type RunAppAttribution, RunAppStamper, type RunAppTopologyOptions, type RunAttributeRow, type RunConsumerOptions, type RunDetail, type RunDetailOptions, type RunDispatch, type RunDispatcher, type RunFacetQuery, type RunFacetRow, RunGateway, type RunListItem, type RunQuery, type RunQueueOptions, type RunReply, type RunReplyResult, type RunRequest, type RunRequestKind, type RunResult, type RunSchedulesOptions, type RunScope, type RunStatus, type RunTenant, type RunValueAxis, type RunValueFacetOptions, type RunValueFacetOrder, type RunValueFacetRow, type RunWaitLink, type RunWaiting, SINGLETON_ACTIVE_STATUSES, SINGLETON_ADMITTED_TAG, SINGLETON_LOCK_CHUNK, SINGLETON_RESERVED_TAGS, SINGLETON_TRACKED_TAG, STATE_STORE, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, type ScalarAttributeFilter, type ScheduleAction, ScheduleAlreadyExistsError, type ScheduleAnnouncement, ScheduleClient, type ScheduleClientOptions, type ScheduleDescription, type ScheduleHost, type ScheduleListQuery, ScheduleNotFoundError, type ScheduleOptions, type ScheduleQuery, type ScheduleRecord, type ScheduleTickEngine, type ScheduledWorkflow, type SchemaIssue, type SchemaValidationCode, SchemaValidationError, type SearchAttributes, type SearchAttributesSchema, type Settled, type SignalOptions, SignalTimeoutError, type SignalWaiter, type SingletonConfig, SingletonQueueFullError, type StalePendingStep, type StalledRunInfo, StandardSchemaV1, type StartOptions, type StartRunMessage, type StartRunSingleton, type StateStore, type StepCheckpoint, type StepConfig, type StepDef, type StepDispatchOpts, type StepError, type StepEvent, type StepHandler, type StepInterceptor, type StepInvocation, type StepKind, type StepLogger, type StepOptions, type StepRef, type StepResult, type StepResultSettlement, type StepScope, type StepSettlement, type StepUndo, type StoreTransaction, type SubProcessHandle, TERMINAL_RUN_STATUSES, TRANSPORT, TRANSPORT_CANONICAL, type TenantEvent, type TenantFilter, type TenantRow, type TenantTokenSource, type TenantVerifier, type Transport, type UndoOf, type UpdateResult, type UpdateValidator, VERSION_UNDECLARED_TAG, type VerifiedTenant, WORKFLOW_NAME_KEY, type WaitAnyCondition, type WaitAnyOutcome, type WaitAnyResult, type WaitCondition, type WaitConditionSpec, type WaitForRunOptions, type WireDates, type WorkerAdjust, type WorkerConcurrencyStatus, type WorkerDescriptor, type WorkerHeartbeat, type WorkerLifecycle, type WorkerStatus, type WorkflowAnnouncement, WorkflowBlocked, type WorkflowClass, type WorkflowCommand, type WorkflowCtx, type WorkflowDecision, type WorkflowDirectory, WorkflowEngine, type WorkflowEngineDeps, type WorkflowExecutor, type WorkflowHandler, type WorkflowInputOf, type WorkflowLifecycleEvent, type WorkflowLifecycleLinks, WorkflowNotRegistered, type WorkflowOutputOf, type WorkflowRef, type WorkflowRegistration, type WorkflowRun, type WorkflowStartClient, type WorkflowStepEvent, WorkflowSuspended, type WorkflowTask, acceptingSubscription, accumulatorRunId, aggregateAnnouncements, aggregatesCheckpoints, announcedScheduleId, announcementsOf, anyCheckpointName, applyAttributeQuery, assertConcurrency, assertRoutes, assertSingleDurableCopy, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, bufferedEventReaches, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneAttribution, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, durableCopies, error, etagMatches, eventMatchOf, eventMatches, eventNameOf, eventPrefix, eventToken, extendEtag, facetOrigin, fanPageBounds, fanPageEtag, findStalledRuns, foldedCount, getRunsByIds, grantsClientTenant, handoffHandlerId, handoffName, hasDurableExecutionWrappers, heartbeatStatus, hmacTenantVerifier, indexWaitersByRun, info, inheritTenant, isAnyCheckpoint, isAnyMember, isEngineMintedTag, isEventToken, isFailedMember, isLegacyDescriptor, isLifecycleTag, isNonEmptyRunScope, isRemoteEvent, isWorkflowControlFlowSignal, legacySingletonHolders, lifecycleDeliveriesOf, lifecycleEventName, lifecycleEventOf, lifecycleKindOf, lifecycleRegistryNamespace, lifecycleRegistryRunId, lifecycleRegistrySubscriptions, lifecycleRunId, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, liveHandoff, log, markRemoteEvent, matchesAttributes, matchesTenantPredicates, mergeRunFacetRows, mergeRunValueFacetRows, missingCapabilities, negotiate, nextCronFireMs, nextRRuleFireMs, nextScheduleFireAt, normalizeAttributeRows, normalizeDescriptor, observedAnnouncements, onErrorRunId, owedSubscribersOf, pageFan, pageFanFromStore, parentRunIdOf, parseDuration, parseLifecycleEvent, parseRRule, parseWebhookToken, partitionOfToken, planDispatch, poolNamespace, prevCronFireMs, prevRRuleFireMs, queryCheckpointsOf, readBufferedEvent, readRunsByIds, readSearchAttributes, remoteCallMaxAttempts, remoteCallPolicyOf, remoteCallRetries, requiredCapabilities, resolveConcurrency, resolveRouting, resolveRunWaiting, resolveTenantToken, resolveWireTenant, retentionKeeps, retiredHandoffName, routeFor, rowTenant, runCompletedEvent, runDetailEtag, runDurableExecution, runFailedEvent, runInStepLogger, runInStepScope, runInWorkflowCtx, runOutsideWorkflowCtx, runSchedules, runStepHandler, runTraceId, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, scopeBufferedEvent, scopeTenantQuery, sealDurableCopies, settleResultsWithPlainCalls, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, singletonKeyTag, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantAppOf, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
package/dist/index.js CHANGED
@@ -4608,6 +4608,14 @@ var LEGACY_SCAN_STATUSES = [
4608
4608
  "cancelling"
4609
4609
  ];
4610
4610
  var byAdmissionOrder = /* @__PURE__ */ __name((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id), "byAdmissionOrder");
4611
+ function singletonKeyTag(tags) {
4612
+ if (!tags) return void 0;
4613
+ for (let i = tags.length - 1; i >= 0; i -= 1) {
4614
+ if (tags[i].startsWith("singleton:")) return tags[i];
4615
+ }
4616
+ return void 0;
4617
+ }
4618
+ __name(singletonKeyTag, "singletonKeyTag");
4611
4619
  function withoutSingletonMarkers(tags) {
4612
4620
  return tags?.filter((tag) => !SINGLETON_RESERVED_TAGS.includes(tag));
4613
4621
  }
@@ -4636,7 +4644,7 @@ function singletonClaimantIds(rows, tag) {
4636
4644
  __name(singletonClaimantIds, "singletonClaimantIds");
4637
4645
  function singletonAdmissionTags(runs, runId, tag, workflow, limit) {
4638
4646
  if (!Number.isInteger(limit) || limit < 1) throw new Error("singleton limit must be a positive integer");
4639
- const active = runs.filter((run) => run.workflow === workflow && SINGLETON_ACTIVE_STATUSES.includes(run.status) && run.tags?.includes(tag));
4647
+ const active = runs.filter((run) => run.workflow === workflow && SINGLETON_ACTIVE_STATUSES.includes(run.status) && singletonKeyTag(run.tags) === tag);
4640
4648
  const candidate = active.find((run) => run.id === runId);
4641
4649
  if (!candidate) return null;
4642
4650
  if (candidate.tags?.includes(SINGLETON_ADMITTED_TAG)) return candidate.tags;
@@ -4664,7 +4672,7 @@ async function clearTerminalSingletonAdmission(runId, patch, getRun) {
4664
4672
  __name(clearTerminalSingletonAdmission, "clearTerminalSingletonAdmission");
4665
4673
  function singletonAdmissionDenialPatch(runs, runId, tag, workflow, retryWakeAt) {
4666
4674
  if (retryWakeAt === void 0) return void 0;
4667
- const candidate = runs.find((run) => run.id === runId && run.workflow === workflow && run.tags?.includes(tag) && SINGLETON_ACTIVE_STATUSES.includes(run.status));
4675
+ const candidate = runs.find((run) => run.id === runId && run.workflow === workflow && singletonKeyTag(run.tags) === tag && SINGLETON_ACTIVE_STATUSES.includes(run.status));
4668
4676
  if (!candidate || candidate.status === "cancelling") return void 0;
4669
4677
  return {
4670
4678
  status: "suspended",
@@ -4713,6 +4721,28 @@ function isLockConflict(error2) {
4713
4721
  return false;
4714
4722
  }
4715
4723
  __name(isLockConflict, "isLockConflict");
4724
+ var UnparseableStoredInput = class {
4725
+ static {
4726
+ __name(this, "UnparseableStoredInput");
4727
+ }
4728
+ error;
4729
+ constructor(error2) {
4730
+ this.error = error2;
4731
+ }
4732
+ };
4733
+ async function admissionInput(run, parseInput) {
4734
+ if (!parseInput) return run.input;
4735
+ try {
4736
+ return await parseInput(run.input);
4737
+ } catch (err) {
4738
+ return new UnparseableStoredInput(err instanceof SchemaValidationError && err.code === "invalid_input" ? err : new SchemaValidationError(`workflow "${run.workflow}" input`, [
4739
+ {
4740
+ message: err instanceof Error ? err.message : String(err)
4741
+ }
4742
+ ], "invalid_input"));
4743
+ }
4744
+ }
4745
+ __name(admissionInput, "admissionInput");
4716
4746
  var SingletonGate = class {
4717
4747
  static {
4718
4748
  __name(this, "SingletonGate");
@@ -4749,12 +4779,19 @@ var SingletonGate = class {
4749
4779
  throw new SingletonQueueFullError(workflow, cfg.key(input), cfg.maxQueueDepth);
4750
4780
  }
4751
4781
  }
4752
- /** Preserve durable holders and atomically claim one of the remaining slots. */
4753
- async admit(run, cfg) {
4782
+ /**
4783
+ * Preserve durable holders and atomically claim one of the remaining slots. With `parseInput` (the
4784
+ * workflow's input schema), the key reads the parsed input, the value `run(ctx, input)` gets; a
4785
+ * stored input that no longer parses answers {@link UnparseableStoredInput}, which the caller
4786
+ * must fail the turn with (never run it).
4787
+ */
4788
+ async admit(run, cfg, parseInput) {
4754
4789
  if (!this.deps.store.tryAdmitSingleton) {
4755
4790
  throw new Error("Singleton workflows require StateStore.tryAdmitSingleton for atomic durable admission");
4756
4791
  }
4757
- const admitted = await this.claim(run, cfg);
4792
+ const keyInput = await admissionInput(run, parseInput);
4793
+ if (keyInput instanceof UnparseableStoredInput) return keyInput;
4794
+ const admitted = await this.claim(run, cfg, this.admissionTag(run, cfg, keyInput, parseInput));
4758
4795
  if (admitted && !run.tags?.includes(SINGLETON_ADMITTED_TAG)) {
4759
4796
  run.tags = [
4760
4797
  ...(run.tags ?? []).filter((tag) => tag !== SINGLETON_TRACKED_TAG),
@@ -4764,17 +4801,43 @@ var SingletonGate = class {
4764
4801
  return admitted;
4765
4802
  }
4766
4803
  /**
4804
+ * The exact tag a turn claims under: the key of the parsed input, the tag `start` stamps. A run
4805
+ * queued by an engine that predates `parseInput` was stamped with the key of its RAW input
4806
+ * instead; when the run carries that tag and not the parsed one, it claims under it, so an
4807
+ * upgrade does not strand it. Both are computed from this run's own input, never read off a tag.
4808
+ * Only that case calls the key with the raw input (what the older engine always did), and only
4809
+ * for a run that carries a `singleton:` tag at all; a key that throws on it gets the parsed tag.
4810
+ */
4811
+ admissionTag(run, cfg, keyInput, parseInput) {
4812
+ const parsed = this.tag(cfg, keyInput);
4813
+ const stamped = singletonKeyTag(run.tags);
4814
+ if (!parseInput || stamped === void 0 || stamped === parsed) return parsed;
4815
+ let raw;
4816
+ try {
4817
+ raw = this.tag(cfg, run.input);
4818
+ } catch {
4819
+ return parsed;
4820
+ }
4821
+ return stamped === raw ? raw : parsed;
4822
+ }
4823
+ /**
4767
4824
  * One claim, retried when the database aborts it as a lock conflict. A conflict that outlasts the
4768
4825
  * retries answers "not admitted", so the engine releases this turn's lease, instead of stranding
4769
4826
  * the run until the lease lapses. It writes nothing to the run: this turn's lease may have lapsed
4770
4827
  * during the claim, and another instance may now hold the run, its slot and newer tags. A later
4771
4828
  * sweep re-drives the run: recovery once it is unleased, or its timer if it is parked.
4829
+ *
4830
+ * The claim is under the tag the key computes NOW, the one `start` stamped from the same input
4831
+ * (the schema is deterministic). The store admits a run only when it carries that exact tag, so
4832
+ * a run whose stored tags lack it (a caller tag from before callers' `singleton:` tags were
4833
+ * dropped, a run started before the workflow became a singleton) is never admitted under some
4834
+ * other key; it waits instead.
4772
4835
  */
4773
- async claim(run, cfg) {
4836
+ async claim(run, cfg, tag) {
4774
4837
  const admit = this.deps.store.tryAdmitSingleton;
4775
4838
  for (let attempt = 1; ; attempt += 1) {
4776
4839
  try {
4777
- return await admit.call(this.deps.store, run.id, this.tag(cfg, run.input), run.workflow, cfg.limit ?? 1, this.retryWakeAt());
4840
+ return await admit.call(this.deps.store, run.id, tag, run.workflow, cfg.limit ?? 1, this.retryWakeAt());
4778
4841
  } catch (error2) {
4779
4842
  if (!isLockConflict(error2)) throw error2;
4780
4843
  if (attempt >= ADMISSION_ATTEMPTS) return false;
@@ -4792,7 +4855,7 @@ var SingletonGate = class {
4792
4855
  async wakeNext(settled) {
4793
4856
  const cfg = this.deps.configFor(settled);
4794
4857
  if (!cfg) return;
4795
- const tag = settled.tags?.find((t) => t.startsWith("singleton:"));
4858
+ const tag = singletonKeyTag(settled.tags);
4796
4859
  if (!tag) return;
4797
4860
  const gated = (await this.deps.store.listRuns({
4798
4861
  tag,
@@ -6941,9 +7004,30 @@ function tenantScopedKey(namespace, key) {
6941
7004
  return namespace && namespace !== "default" ? `${namespace}/${key}` : key;
6942
7005
  }
6943
7006
  __name(tenantScopedKey, "tenantScopedKey");
7007
+ function failingBody(error2) {
7008
+ return async () => {
7009
+ throw error2;
7010
+ };
7011
+ }
7012
+ __name(failingBody, "failingBody");
7013
+ function storedInputError(invalid) {
7014
+ return {
7015
+ message: invalid.error.message,
7016
+ code: "invalid_input",
7017
+ retryable: false,
7018
+ details: {
7019
+ issues: invalid.error.issues
7020
+ }
7021
+ };
7022
+ }
7023
+ __name(storedInputError, "storedInputError");
7024
+ function callerTags(tags) {
7025
+ return tags?.filter((tag) => !tag.startsWith(SINGLETON_TAG_PREFIX));
7026
+ }
7027
+ __name(callerTags, "callerTags");
7028
+ var SINGLETON_TAG_PREFIX = "singleton:";
6944
7029
  function singletonKeyOf(run) {
6945
- const tag = run.tags?.find((t) => t.startsWith("singleton:"));
6946
- return tag?.slice("singleton:".length);
7030
+ return singletonKeyTag(run.tags)?.slice("singleton:".length);
6947
7031
  }
6948
7032
  __name(singletonKeyOf, "singletonKeyOf");
6949
7033
  function conventionSingleton(run, announced, wire) {
@@ -7963,6 +8047,7 @@ var WorkflowEngine = class _WorkflowEngine {
7963
8047
  concurrency: opts?.concurrency,
7964
8048
  executionTimeoutMs: opts?.executionTimeout != null ? parseDuration(opts.executionTimeout) : void 0,
7965
8049
  validateInput: opts?.validateInput,
8050
+ parseInput: opts?.parseInput,
7966
8051
  searchAttributesSchema: opts?.searchAttributesSchema,
7967
8052
  onEvent: opts?.onEvent,
7968
8053
  eventBatch: opts?.eventBatch,
@@ -9664,24 +9749,31 @@ var WorkflowEngine = class _WorkflowEngine {
9664
9749
  if (!registered) {
9665
9750
  throw new Error(pinned === void 0 ? `workflow ${name} is not registered` : `workflow ${versionKey(name, pinned)} is not registered \u2014 a pinned start never falls back to the newest version (registered: ${this.registeredVersions(name)})`);
9666
9751
  }
9667
- if (parkUnroutable && registered.validateInput) {
9752
+ const check = registered;
9753
+ const parseAndValidate = /* @__PURE__ */ __name(async () => {
9754
+ const parsed = check.parseInput ? await check.parseInput(input) : input;
9755
+ await check.validateInput?.(parsed);
9756
+ return parsed;
9757
+ }, "parseAndValidate");
9758
+ let keyInput;
9759
+ if (parkUnroutable && (registered.validateInput || registered.parseInput)) {
9668
9760
  try {
9669
- await registered.validateInput(input);
9761
+ keyInput = await parseAndValidate();
9670
9762
  } catch (err) {
9671
9763
  throw new TenantStartInvalid(err);
9672
9764
  }
9673
9765
  } else {
9674
- await registered.validateInput?.(input);
9766
+ keyInput = await parseAndValidate();
9675
9767
  }
9676
9768
  const prior = await this.store.getRun(runId);
9677
9769
  if (prior) return this.existingStartResult(prior);
9678
- const quota = await resolveConcurrency(opts?.concurrency, registered.concurrency, input);
9770
+ const quota = await resolveConcurrency(opts?.concurrency, registered.concurrency, keyInput);
9679
9771
  if (quota) await assertConcurrency(this.store, name, quota);
9680
9772
  const now = /* @__PURE__ */ new Date();
9681
9773
  const stampedTags = [
9682
- ...opts?.tags ?? [],
9774
+ ...callerTags(opts?.tags) ?? [],
9683
9775
  ...registered.singleton ? [
9684
- this.singletons.tag(registered.singleton, input)
9776
+ this.singletons.tag(registered.singleton, keyInput)
9685
9777
  ] : [],
9686
9778
  ...quota ? [
9687
9779
  concurrencyTag(quota.key)
@@ -9690,9 +9782,9 @@ var WorkflowEngine = class _WorkflowEngine {
9690
9782
  VERSION_UNDECLARED_TAG
9691
9783
  ] : []
9692
9784
  ];
9693
- const tags = mergeTags(registered.tags, stampedTags)?.filter((tag) => !SINGLETON_RESERVED_TAGS.includes(tag));
9785
+ const tags = mergeTags(callerTags(registered.tags), stampedTags)?.filter((tag) => !SINGLETON_RESERVED_TAGS.includes(tag));
9694
9786
  if (registered.singleton) {
9695
- await this.singletons.assertCapacity(name, registered.singleton, input);
9787
+ await this.singletons.assertCapacity(name, registered.singleton, keyInput);
9696
9788
  }
9697
9789
  const startAtMs = opts?.startAt instanceof Date ? opts.startAt.getTime() : opts?.startAt;
9698
9790
  const delayed = startAtMs !== void 0 && Number.isFinite(startAtMs) && startAtMs > this.clock();
@@ -9781,7 +9873,7 @@ var WorkflowEngine = class _WorkflowEngine {
9781
9873
  };
9782
9874
  const now = /* @__PURE__ */ new Date();
9783
9875
  const tags = mergeTags(void 0, [
9784
- ...opts?.tags ?? [],
9876
+ ...callerTags(opts?.tags) ?? [],
9785
9877
  ...singleton ? [
9786
9878
  this.singletons.tag(singleton, input)
9787
9879
  ] : [],
@@ -9961,7 +10053,7 @@ var WorkflowEngine = class _WorkflowEngine {
9961
10053
  namespace: poolNamespace(opts.namespace) ?? this.namespace,
9962
10054
  input,
9963
10055
  // The same derived tags an admitted or parked start carries, so quota-key queries find it.
9964
- tags: mergeTags(opts.tags, [
10056
+ tags: mergeTags(callerTags(opts.tags), [
9965
10057
  ...opts.concurrency ? [
9966
10058
  concurrencyTag(opts.concurrency.key)
9967
10059
  ] : [],
@@ -13488,8 +13580,17 @@ ${run.workflowVersion}`;
13488
13580
  ...await this.sourceTraceOf(run)
13489
13581
  });
13490
13582
  }
13491
- if (registered.singleton && !await this.singletons.admit(run, registered.singleton)) {
13492
- return this.singletonWaitResult(run);
13583
+ if (registered.singleton) {
13584
+ const admission = await this.singletons.admit(run, registered.singleton, registered.parseInput);
13585
+ if (admission instanceof UnparseableStoredInput) {
13586
+ const result = await this.settleRun(run, {
13587
+ kind: "failed",
13588
+ error: storedInputError(admission)
13589
+ });
13590
+ await this.releaseLeaseBestEffort(run.id);
13591
+ return result;
13592
+ }
13593
+ if (!admission) return this.singletonWaitResult(run);
13493
13594
  }
13494
13595
  const wfToken = tenantGroup(sanitizeQueueToken(remote.group), void 0);
13495
13596
  let wfPlan = await this.planRoute(wfToken, registered.requires);
@@ -14526,7 +14627,8 @@ ${run.workflowVersion}`;
14526
14627
  attempt: void 0
14527
14628
  }, () => this.runExecutionTurn(run, fn, registered));
14528
14629
  }
14529
- async runExecutionTurn(run, fn, registered) {
14630
+ async runExecutionTurn(run, registeredFn, registered) {
14631
+ let fn = registeredFn;
14530
14632
  if (run.status === "cancelling") this.cancelRequested.add(run.id);
14531
14633
  if (run.status === "pending") {
14532
14634
  if (!await this.markStarted(run, registered?.singleton !== void 0)) {
@@ -14542,8 +14644,10 @@ ${run.workflowVersion}`;
14542
14644
  });
14543
14645
  }
14544
14646
  await this.noteServedWakes(run.id);
14545
- if (run.status !== "cancelling" && registered?.singleton && !await this.singletons.admit(run, registered.singleton)) {
14546
- return this.singletonWaitResult(run);
14647
+ if (run.status !== "cancelling" && registered?.singleton) {
14648
+ const admission = await this.singletons.admit(run, registered.singleton, registered.parseInput);
14649
+ if (admission instanceof UnparseableStoredInput) fn = failingBody(admission.error);
14650
+ else if (!admission) return this.singletonWaitResult(run);
14547
14651
  }
14548
14652
  const stickyOk = this.stickyEligible(run);
14549
14653
  let cont = stickyOk ? this.takeContinuation(run, fn) : void 0;
@@ -19055,6 +19159,7 @@ export {
19055
19159
  singletonAdmissionDenialPatch,
19056
19160
  singletonAdmissionTags,
19057
19161
  singletonClaimantIds,
19162
+ singletonKeyTag,
19058
19163
  sqlComparator,
19059
19164
  stepConfigOf,
19060
19165
  stepId,