Interface IFlowRunRuntimeStore
- Namespace
- FlowOrchestrator.Core.Storage
- Assembly
- FlowOrchestrator.Core.dll
Runtime step-tracking store used by the orchestrator during execution to prevent duplicate step enqueuing in parallel/fan-out scenarios.
public interface IFlowRunRuntimeStore
Methods
CountSettledIterationsAsync(Guid, string, int, IReadOnlyCollection<string>)
Counts the iterations i in [0, of the loop instance
iterations)loopStepKey in which every one of bodyStepKeys —
"{loopStepKey}.{i}.{child}" — has a terminal status (Succeeded,
Failed or Skipped).
Task<int> CountSettledIterationsAsync(Guid runId, string loopStepKey, int iterations, IReadOnlyCollection<string> bodyStepKeys)
Parameters
runIdGuidThe run owning the loop.
loopStepKeystringRuntime key of the loop step, e.g.
"loop"or"outer.2.inner".iterationsintThe loop's iteration count; indices at or above it are not counted.
bodyStepKeysIReadOnlyCollection<string>The loop body's direct child keys (single segments, no dots), each listed once.
Returns
Remarks
Drives the ForEach barrier and admission gate (#189 P0-1): the loop settles when the count reaches
iterations, and admission keeps [0, count + ConcurrencyLimit) started. Only
a row whose key is exactly {loop}.{i}.{child}, with i a canonical decimal index and
child one of bodyStepKeys, counts — rows of nested loops
({loop}.{i}.{child}.{j}.{grandchild}) do not.
The answer travels as one row. Server-side it is a range read over the loop's own rows, so implement it
against the (RunId, StepKey) key with a prefix predicate. The same visibility contract as
GetStepStatusesAsync(Guid, IReadOnlyCollection<string>) applies; it is what makes two
iterations that settle concurrently admit both replacements.
GetClaimedStepKeysAsync(Guid)
Returns the set of step keys that have been claimed (locked) for execution but not yet completed, used to detect in-progress steps.
Task<IReadOnlyCollection<string>> GetClaimedStepKeysAsync(Guid runId)
Parameters
runIdGuid
Returns
GetRunStatusAsync(Guid)
Returns the current overall status of the run ("Running", "Succeeded", etc.),
or null if the run does not exist.
Task<string?> GetRunStatusAsync(Guid runId)
Parameters
runIdGuid
Returns
GetStepStatusesAsync(Guid)
Returns the current StepStatus for every step in the run.
Task<IReadOnlyDictionary<string, StepStatus>> GetStepStatusesAsync(Guid runId)
Parameters
runIdGuid
Returns
Remarks
O(steps in the run) in rows returned. The engine calls it only when a run is about to close (the terminal classification) and from startup recovery — never once per step completion; that path uses GetStepStatusesAsync(Guid, IReadOnlyCollection<string>).
GetStepStatusesAsync(Guid, IReadOnlyCollection<string>)
Returns the current StepStatus of each of stepKeys that has a status
row; keys without one are absent from the result.
Task<IReadOnlyDictionary<string, StepStatus>> GetStepStatusesAsync(Guid runId, IReadOnlyCollection<string> stepKeys)
Parameters
runIdGuidThe run owning the steps.
stepKeysIReadOnlyCollection<string>Runtime step keys to look up. May contain duplicates; may be empty.
Returns
- Task<IReadOnlyDictionary<string, StepStatus>>
A map keyed with Ordinal holding only keys that have a row.
Remarks
The engine's per-step-completion read (#189 P0-1). When step X reaches a status, only the steps
that depend on X can change classification, so the continuation asks for those steps and their
dependencies — a handful of keys — instead of every row in the run. Implement it as indexed point
lookups on (RunId, StepKey); a provider with a statement parameter limit must chunk.
Visibility contract (write-skew rule, RFC 2.0 §3.5). The call must observe every status write that committed before it started. Run it as its own statement against the primary — never inside a transaction that predates the caller's write, never against a read replica. Two steps that complete concurrently then cannot both miss the join that waits on them: whichever commits last reads the other's row.
There is deliberately no default implementation: falling back to the whole map would silently keep the continuation O(steps in the run).
HasRunningOrPendingStepAsync(Guid)
Task<bool> HasRunningOrPendingStepAsync(Guid runId)
Parameters
runIdGuidThe run to inspect.
Returns
Remarks
The first check of the run-completion gate, asked on every step completion that dispatched nothing. A Running or Pending row is work that will run a continuation of its own later (a handler still executing, a ForEach parked on its barrier, a poll waiting for its next attempt), so the gate can stand down without reading the run. Only when this returns false does the engine read the whole status map, claims and dispatch ledger to decide whether to close the run.
Back it with an index on the open rows only (a filtered or partial index on
Status IN ('Running','Pending')), so the cost follows the number of open steps, not the run's
length. The same visibility contract as
GetStepStatusesAsync(Guid, IReadOnlyCollection<string>) applies. A
false that should have been true only costs the full read; a
true that should have been false keeps a finished run open, so
never answer from a cache.
IsStepClaimedAsync(Guid, string)
Returns whether one specific step currently holds an execution claim.
Task<bool> IsStepClaimedAsync(Guid runId, string stepKey)
Parameters
Returns
Remarks
A point lookup for callers that need membership rather than enumeration — notably
FlowSignalDispatcher, which asks about a single parked step on every signal delivery.
Claims are deliberately NOT released when a step reaches a terminal status (the row is what
makes execution exactly-once under at-least-once delivery), so GetClaimedStepKeysAsync(Guid)
returns one key per executed step and grows with run length; answering a single-key question
through it is O(n) in both payload and scan. The default implementation does exactly that, so
existing stores keep compiling — override it with an indexed lookup.
LeaseExpiredStepLeasesAsync(TimeSpan, int)
Selects up to maxCount steps of running runs whose execution lease expired while the
step had not reached a terminal status, and stamps each so that no other caller selects it again within
redeliveryBackoff.
Task<IReadOnlyList<ExpiredStepLease>> LeaseExpiredStepLeasesAsync(TimeSpan redeliveryBackoff, int maxCount)
Parameters
redeliveryBackoffTimeSpanMinimum time between two redeliveries of the same expired lease.
maxCountintUpper bound on the rows returned.
Returns
- Task<IReadOnlyList<ExpiredStepLease>>
The steps to hand to the runtime again; a redelivery takes the expired lease over.
Remarks
Covers the owner dying mid-handler, between its claim and its first status write, and between the handler returning and the completion committing — every case where the runtime's own redelivery came too early (the lease was still live) or never came. Ages are measured on the store's own clock. Concurrent callers on other replicas must not select the same row in the same window.
PinStepLeaseAsync(StepLease)
Makes the lease permanent when its fence still matches: it no longer expires and can no longer be taken over. Used when a step parks on its loop barrier — its handler has returned, nothing renews the lease any more, and re-running it would fan the loop out again.
Task<bool> PinStepLeaseAsync(StepLease lease)
Parameters
leaseStepLeaseThe lease to pin.
Returns
RecordSkippedStepAsync(Guid, string, string, string?)
Records a step as Skipped without executing it,
used when runAfter conditions cannot be satisfied.
Task RecordSkippedStepAsync(Guid runId, string stepKey, string stepType, string? reason)
Parameters
Returns
Remarks
The engine calls this right after it wins TryClaimStepAsync(Guid, string), so the step row and its attempt row should be written in one transaction: a skip that is half written leaves a claim the completion gate cannot tell apart from a step that is still starting.
RecordSkippedStepAsync(Guid, string, string, string?, string?)
Records a step as Skipped and persists a
FlowOrchestrator.Core.Expressions.WhenEvaluationTrace describing why a When
clause evaluated to false.
Task RecordSkippedStepAsync(Guid runId, string stepKey, string stepType, string? reason, string? evaluationTraceJson)
Parameters
Returns
Remarks
Default implementation falls back to RecordSkippedStepAsync(Guid, string, string, string?) so existing custom storage providers continue to compile without modification.
ReleaseOrphanedClaimsAsync(Guid, TimeSpan)
Atomically deletes every claim of runId that has no step status row and was taken
at least minimumAge ago, together with the same keys' dispatch-ledger rows, and
returns the keys it released.
Task<IReadOnlyList<string>> ReleaseOrphanedClaimsAsync(Guid runId, TimeSpan minimumAge)
Parameters
runIdGuidThe run whose orphaned claims are released.
minimumAgeTimeSpanHow old a claim must be, measured on the store's own clock (the one that stamped the claim), before it counts as orphaned. Zero releases every claim without a status row.
Returns
- Task<IReadOnlyList<string>>
The released step keys; empty when nothing was orphaned.
Remarks
A worker records the step's first status row right after it wins the claim. A claim with no row therefore means that worker crashed (or its storage failed) in between, and nothing else would ever run that step: the claim makes every later attempt exit, and the completion gate counts the key as in-flight work for ever (RFC 2.0 S1b). Releasing the claim and the ledger row returns the step to "ready, never dispatched", which recovery re-dispatches.
The age is the only evidence that the claimer is gone, so a worker that is alive but stalled for
longer than minimumAge between its claim and its first status write can have its
claim released and the step run twice. A claim taken under a lease
(TryAcquireStepLeaseAsync(Guid, string, string, TimeSpan)) is reclaimed by its expiry instead; this release still covers
claims without one. There is deliberately no default implementation.
The check for a status row must serialise with a concurrent first status write for the same key (a key-range lock or one statement), so a claim whose row is being written is never released.
ReleaseStepClaimAsync(Guid, string)
Releases a previously-acquired step claim so a future TryClaimStepAsync(Guid, string) for the
same (runId, stepKey) can succeed. Called by the engine on Pending re-schedule and
retry paths, where the same logical step needs to run again.
Task ReleaseStepClaimAsync(Guid runId, string stepKey)
Parameters
Returns
Remarks
Idempotent — calling for a key with no claim is a no-op. Default implementation is a no-op so existing custom runtime stores continue to compile; in that case retry/Pending paths behave as before v1.22 (the schedule-time claim was non-strict). New implementations should remove the claim row atomically.
ReleaseStepLeaseAsync(StepLease)
Deletes the claim when its fence still matches lease, so the same step can be claimed
again — the fenced form of ReleaseStepClaimAsync(Guid, string), used by the Pending re-poll hand-off.
Task<bool> ReleaseStepLeaseAsync(StepLease lease)
Parameters
leaseStepLeaseThe lease to release.
Returns
RenewStepLeasesAsync(IReadOnlyList<StepLease>, TimeSpan)
Extends every lease in leases whose fence still matches by duration
from now, in one round trip.
Task<IReadOnlyList<StepLease>> RenewStepLeasesAsync(IReadOnlyList<StepLease> leases, TimeSpan duration)
Parameters
leasesIReadOnlyList<StepLease>The leases this process holds for steps that are executing right now.
durationTimeSpanThe new remaining lifetime, measured on the store's own clock.
Returns
- Task<IReadOnlyList<StepLease>>
The leases that were renewed; a lease missing from the result was taken over or released.
TryAcquireStepLeaseAsync(Guid, string, string, TimeSpan)
Atomically claims a step for execution under a lease that expires after duration
unless renewed, taking over a lease that already expired while the step had not reached a terminal
status.
Task<StepLease?> TryAcquireStepLeaseAsync(Guid runId, string stepKey, string ownerId, TimeSpan duration)
Parameters
runIdGuidThe run owning the step.
stepKeystringThe step to claim.
ownerIdstringIdentifies the acquiring process, for diagnostics.
durationTimeSpanHow long the lease lives without renewal, measured on the store's own clock.
Returns
- Task<StepLease>
The acquired lease; null when another worker holds an unexpired lease, the claim is permanent (a skip claim, a lease pinned by PinStepLeaseAsync(StepLease), or a claim written before leases existed), or the step already reached a terminal status.
Remarks
No claim row: one is inserted with fence 1. A row whose lease expired, for a step with no status
row or a Running / Pending one: the fence is raised by
one and the lease re-stamped — a takeover. Anything else: null.
The status check must serialise with a concurrent fenced completion (TryRecordLeasedStepCompleteAsync(StepLease, string, string?, string?)) of the same step: lock the claim row first, then read the status, so a completion that committed first is always seen and a takeover never re-runs a step that just finished.
TryClaimStepAsync(Guid, string)
Atomically claims a step for execution, returning true if this caller acquired the claim or false if another worker already claimed it.
Task<bool> TryClaimStepAsync(Guid runId, string stepKey)
Parameters
Returns
Remarks
This is the primary guard against duplicate step execution. Since v1.22 the engine calls
this at the top of RunStepAsync (execute time) rather than at schedule time, so it
correctly prevents concurrent execution under at-least-once delivery — including the
Service Bus topic-broadcast case where a single dispatched message reaches multiple
subscriptions. Implementations must use an atomic compare-and-set or equivalent database
primitive. Pair with ReleaseStepClaimAsync(Guid, string) on retry / Pending
re-schedule paths so the SAME step can claim again on a fresh attempt.
TryRecordLeasedStepCompleteAsync(StepLease, string, string?, string?)
Records a step's completion only while lease is still the step's current lease, in
the same transaction as the fence check.
Task<bool> TryRecordLeasedStepCompleteAsync(StepLease lease, string status, string? outputJson, string? errorMessage)
Parameters
leaseStepLeaseThe lease the completing attempt holds.
statusstringThe step status to record.
outputJsonstringSerialised step output, if any.
errorMessagestringFailure reason, if any.
Returns
- Task<bool>
true when recorded; false when another worker took the lease over — that worker's attempt owns the step now, and this completion must be discarded, continuation included.
Remarks
Same writes as RecordStepCompleteAsync(Guid, string, string, string?, string?) (step row and latest attempt row).