Interface IFlowRunStore
- Namespace
- FlowOrchestrator.Core.Storage
- Assembly
- FlowOrchestrator.Core.dll
Persistence contract for flow run lifecycle: creating runs, recording step progress, completing runs, and querying run history.
public interface IFlowRunStore
Methods
AnnotateDispatchAsync(Guid, string, string, CancellationToken)
Stores the runtime job or message ID returned by the dispatcher alongside the dispatch record. Best-effort — implementations should not throw; failures are silently ignored by the engine.
Task AnnotateDispatchAsync(Guid runId, string stepKey, string jobId, CancellationToken ct = default)
Parameters
runIdGuidstepKeystringjobIdstringctCancellationToken
Returns
CompleteRunAsync(Guid, string)
Marks the run as complete (status: Succeeded, Failed, or Cancelled)
and sets CompletedAt.
Task CompleteRunAsync(Guid runId, string status)
Parameters
Returns
CompleteRunIfActiveAsync(Guid, string)
Transitions the run to a terminal status only if it is still active
(Running), reporting whether this call performed the transition. Makes run completion
idempotent and safe against concurrent completers — notably the graph continuation and the
periodic timeout sweep (single- or multi-instance) — so a run's lifecycle event is published
exactly once and its terminal status is set by exactly one writer.
Task<bool> CompleteRunIfActiveAsync(Guid runId, string status)
Parameters
Returns
- Task<bool>
true if this call transitioned a
Runningrun tostatus; false if the run was already in a terminal state (another writer won).
Remarks
Default implementation delegates to CompleteRunAsync(Guid, string) and reports true, so existing custom IFlowRunStore implementations compile unchanged (retaining their prior, non-idempotent completion behaviour).
GetActiveRunsAsync()
Returns all runs currently in Running status (used for timeout enforcement).
Task<IReadOnlyList<FlowRunRecord>> GetActiveRunsAsync()
Returns
GetDerivedRunsAsync(Guid)
Returns runs whose SourceRunId equals sourceRunId,
i.e. all re-runs derived from a given run. Used by the dashboard to render lineage.
Task<IReadOnlyList<FlowRunRecord>> GetDerivedRunsAsync(Guid sourceRunId)
Parameters
sourceRunIdGuid
Returns
GetDispatchedStepKeysAsync(Guid)
Returns the set of step keys that have been dispatched (and not yet released) for a run. Used by the recovery service to avoid re-dispatching already-in-flight steps.
Task<IReadOnlySet<string>> GetDispatchedStepKeysAsync(Guid runId)
Parameters
runIdGuid
Returns
GetRunAsync(Guid)
Returns the run's header row only — no step records, no attempt history — or
null if no run with runId exists.
Task<FlowRunRecord?> GetRunAsync(Guid runId)
Parameters
runIdGuidThe run to read.
Returns
Remarks
For callers that need a field or two off the run itself (its FlowId, its status) and
have no use for the step graph. GetRunDetailAsync(Guid) issues three queries and
returns every step row and every attempt row including their unbounded JSON columns,
so its cost grows with the size of the run; on SQL Server that read has been observed to time
out on a 150-iteration ForEach under load. Use this instead wherever the graph is not
actually read.
The default implementation delegates to GetRunDetailAsync(Guid) so existing custom stores keep compiling and keep working — they simply do not get the saving. Providers should override it with a single-row query.
GetRunDetailAsync(Guid)
Returns full run detail including all step records and their attempt history,
or null if no run with runId exists.
Task<FlowRunRecord?> GetRunDetailAsync(Guid runId)
Parameters
runIdGuid
Returns
GetRunTimeseriesAsync(RunTimeseriesGranularity, DateTimeOffset, DateTimeOffset, Guid?)
Returns time-bucketed run counts and duration percentiles for the half-open
interval [since, until). Buckets that contain
no runs are still returned (with zero counts) so the caller can render a contiguous
timeline without gap-filling. When flowId is supplied, only runs
for that flow are included.
Task<IReadOnlyList<RunTimeseriesBucket>> GetRunTimeseriesAsync(RunTimeseriesGranularity granularity, DateTimeOffset since, DateTimeOffset until, Guid? flowId = null)
Parameters
granularityRunTimeseriesGranularityHour or Day bucket size.
sinceDateTimeOffsetUTC start of the window (inclusive). Aligned to the granularity boundary.
untilDateTimeOffsetUTC end of the window (exclusive). Aligned to the granularity boundary.
flowIdGuid?Optional filter — when non-null, only runs for this flow are counted.
Returns
GetRunsAsync(Guid?, int, int)
Returns a page of run records, optionally filtered by flowId.
Results are ordered by start time descending.
Task<IReadOnlyList<FlowRunRecord>> GetRunsAsync(Guid? flowId = null, int skip = 0, int take = 50)
Parameters
Returns
GetRunsPageAsync(Guid?, string?, int, int, string?)
Returns a paginated run list with total count, optionally filtered by flow, status, and free-text search.
Task<(IReadOnlyList<FlowRunRecord> Runs, int TotalCount)> GetRunsPageAsync(Guid? flowId = null, string? status = null, int skip = 0, int take = 50, string? search = null)
Parameters
flowIdGuid?Restricts results to a single flow when set.
statusstringRestricts results to runs in the given status when set.
skipintNumber of leading rows to skip (offset pagination).
takeintMaximum number of rows to return.
searchstringFree-text term matched (case-insensitively) against run identity columns and the current step records (step key, error message, output JSON). Step attempt history is intentionally not searched — its output duplicates the current step row.
Returns
GetRunsPageAsync(Guid?, string?, int, int, string?, bool, DateTimeOffset?, DateTimeOffset?)
Tiered, time-bounded variant of GetRunsPageAsync(Guid?, string?, int, int, string?).
Task<(IReadOnlyList<FlowRunRecord> Runs, int TotalCount)> GetRunsPageAsync(Guid? flowId, string? status, int skip, int take, string? search, bool deepSearch, DateTimeOffset? startedFrom = null, DateTimeOffset? startedTo = null)
Parameters
flowIdGuid?statusstringskipinttakeintsearchstringdeepSearchboolstartedFromDateTimeOffset?startedToDateTimeOffset?
Returns
Remarks
deepSearch: true (the behaviour of the five-argument overload) also matches the current
step records; deepSearch: false matches only the top-level run columns (id, flow name,
trigger key, status, background job id) — index-friendlier, suited to typeahead such as the
command palette. startedFrom / startedTo bound the scan to a start-time window
when set.
The default implementation delegates to the five-argument overload, so existing
IFlowRunStore providers keep compiling and stay correct (they simply do not get
the quick-search or time-window optimisations until they override this method).
GetStatisticsAsync()
Returns aggregate counts used by the dashboard overview panel.
Task<DashboardStatistics> GetStatisticsAsync()
Returns
GetStepAsync(Guid, string)
Returns a single step's row — status, error, timestamps and its own JSON columns — or null when the run or the step has no row yet.
Task<FlowStepRecord?> GetStepAsync(Guid runId, string stepKey)
Parameters
runIdGuidThe run owning the step.
stepKeystringThe runtime step key (e.g.
"process.3.validate").
Returns
Remarks
Attempts is not populated. Exists for
@steps('key').status / .error expressions, which are resolved per step execution
and per when-clause evaluation: fetching the whole run detail for them pulled every step
and attempt row with their JSON columns on each of those calls (#189).
The default implementation delegates to GetRunDetailAsync(Guid) and scans, so existing custom stores keep working without the saving. Providers should override it with a point read.
IsStepDispatchedAsync(Guid, string)
Returns whether one specific step currently holds a dispatch-ledger row for the run.
Task<bool> IsStepDispatchedAsync(Guid runId, string stepKey)
Parameters
runIdGuidThe run owning the step.
stepKeystringThe runtime step key to test, e.g.
"loop.3.child".
Returns
Remarks
A point lookup for callers that need membership rather than enumeration — notably the engine's
ForEach admission gate, which runs on every step completion while a loop is parked and
only ever probes the few keys around its started-iteration boundary. The ledger keeps one row
per dispatched step, so GetDispatchedStepKeysAsync(Guid) grows with run length and
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.
LeaseUnsentDispatchesAsync(TimeSpan, int, CancellationToken)
Finds dispatch-ledger rows whose hand-off to the runtime never completed, and leases them to the caller for re-delivery.
Task<IReadOnlyList<UnsentDispatch>> LeaseUnsentDispatchesAsync(TimeSpan minimumAge, int maxCount, CancellationToken ct = default)
Parameters
minimumAgeTimeSpanHow long a row must have gone without a runtime job id to qualify.
maxCountintUpper bound on the rows returned by one call.
ctCancellationTokenHonoured before the lease is written; never after.
Returns
- Task<IReadOnlyList<UnsentDispatch>>
The leased rows; empty when nothing qualifies or the store does not support the lease.
Remarks
The engine writes a ledger row before it hands the step to the runtime and annotates it
with the runtime's job/message id (AnnotateDispatchAsync(Guid, string, string, CancellationToken)) once the hand-off returns.
A row that still has no id long after it was written means the hand-off never returned: the process
died mid-send, or the send is hung. Startup recovery skips every ledgered key, so without this lease
such a step is never dispatched again and its run stays Running for ever.
A row qualifies when all of these hold: it has no job id; it is older than
minimumAge; its run is Running; no worker claims the step; and the step has
no status row, or only a Pending one (a poll whose re-attempt was never
handed over). Leasing re-stamps the row's dispatch time to now, in the same atomic statement that
selects it, so concurrent callers (one per replica) never lease the same row twice inside one
minimumAge window, and a re-delivery that fails again is retried a window later.
The store cannot tell "never sent" from "sent, but the process died before the annotation". Both are re-delivered; a duplicate message is absorbed by the execution claim (TryClaimStepAsync(Guid, string)), whereas a lost one strands the run.
No default implementation, deliberately: a store that silently returned nothing would keep the stranded-run bug this member exists to close. Custom stores must implement it (see the migration guide).
RecordStepCompleteAsync(Guid, string, string, string?, string?)
Records the outcome of a step attempt: updates status, persists output JSON, and sets error message on failure.
Task RecordStepCompleteAsync(Guid runId, string stepKey, string status, string? outputJson, string? errorMessage)
Parameters
Returns
RecordStepStartAsync(Guid, string, string, string?, string?)
Records the start of a step attempt: sets status to Running, persists inputs, and associates the Hangfire job ID.
Task RecordStepStartAsync(Guid runId, string stepKey, string stepType, string? inputJson, string? jobId)
Parameters
Returns
RecordStepStartAsync(Guid, string, string, string?, string?, string?)
Records the start of a step attempt like RecordStepStartAsync(Guid, string, string, string?, string?), and stamps the new attempt row with the server that runs it (ServerId).
Task RecordStepStartAsync(Guid runId, string stepKey, string stepType, string? inputJson, string? jobId, string? serverId)
Parameters
runIdGuidThe run owning the step.
stepKeystringThe step (manifest key or runtime loop path).
stepTypestringThe step's handler type name.
inputJsonstringJSON-serialised unresolved inputs, or null.
jobIdstringRuntime job id, or null.
serverIdstring
Returns
- Task
A task that completes when the start is durable.
Remarks
The engine calls this overload. The default implementation drops serverId and calls the
five-parameter overload, so a custom store written before 2.0 keeps working and simply records no server.
The built-in stores write it into the same attempt insert — no extra round trip.
ReleaseDispatchAsync(Guid, string, CancellationToken)
Removes the dispatch record for a step, allowing it to be re-dispatched. Called by the engine before rescheduling a Pending (polling) step.
Task ReleaseDispatchAsync(Guid runId, string stepKey, CancellationToken ct = default)
Parameters
runIdGuidstepKeystringctCancellationToken
Returns
ResetCascadeSkippedDependentsAsync(Guid, IReadOnlyCollection<string>)
Clears cascade-skip records (PrerequisitesUnmet) for the
given step keys so the DAG planner re-evaluates them after a manual retry of an
upstream step. Removes the step row, claim row, and dispatch-ledger row for any
matching descendant — the attempt history (FlowStepAttempts) is preserved so
the dashboard still surfaces the prior "Skipped" attempt as audit trail.
Task ResetCascadeSkippedDependentsAsync(Guid runId, IReadOnlyCollection<string> stepKeys)
Parameters
runIdGuidstepKeysIReadOnlyCollection<string>
Returns
Remarks
Only rows whose status is Skipped AND whose error message exactly matches
PrerequisitesUnmet are cleared. Steps skipped via
When-clause evaluation carry a different reason and are intentionally left
untouched. Idempotent — calling with keys that have no matching row is a no-op.
Default implementation is a no-op so external IFlowRunStore
implementations continue to compile; in that case the post-retry DAG advance
behaves as pre-fix (downstream steps stay Skipped).
RetryStepAsync(Guid, string)
Resets a Failed step back to a re-runnable state for a manual retry, only if it is still
Failed, and reports whether this call made the reset.
Task<bool> RetryStepAsync(Guid runId, string stepKey)
Parameters
Returns
- Task<bool>
true when this call reset a
Failedstep; false when the step has no row or is notFailed(for example because a concurrent retry reset it first). Nothing is changed when it returns false.
Remarks
On success, one transaction: the step row becomes Running with its output, error and
completion time cleared; the run goes back to Running with no completion time; and the step's
claim and dispatch-ledger rows are deleted so the engine can dispatch and claim the new attempt.
The Failed check and the reset must be one atomic step (a conditional UPDATE and its row
count, inside the same transaction as the deletes). Before 2.0 the reset was unconditional and
unbatched, so a second concurrent retry deleted the first retry's claim and the handler ran twice at
once (RFC 2.0 S4). There is deliberately no default implementation.
SearchRunsAsync(RunSearchQuery, CancellationToken)
Returns one page of runs matching a structured query, newest first, without
counting the whole filtered set unless CountsTotal allows it.
Task<RunSearchPage> SearchRunsAsync(RunSearchQuery query, CancellationToken cancellationToken = default)
Parameters
queryRunSearchQueryThe filters, window and page to read.
cancellationTokenCancellationTokenCancels the read.
Returns
- Task<RunSearchPage>
The page, whether more rows follow it, and an exact total when one was requested and cheap.
Remarks
This is the run-list path the dashboard uses. The built-in providers override it so that a run
id is a primary-key seek, a text term reads only the run's own columns inside the start-time
window, and step payloads are read only when IncludeStepPayloads is
set. The default implementation keeps third-party providers correct by delegating to
GetRunsPageAsync(Guid?, string?, int, int, string?, bool, DateTimeOffset?, DateTimeOffset?);
it does not get the seeks. That overload orders runs newest first but leaves runs that share a start
time in no defined order, so the default implementation re-sorts every page into the cursor order
(StartedAt descending, then Id ascending) and pages exactly — no run duplicated or
dropped — whatever the number of ties:
- with After, it reads the runs that started at the cursor's exact
start time as one group (a
startedFrom = startedTowindow), keeps those after the cursor, and reads the rest strictly older than the cursor; - when the page's last row shares its start time with rows the read did not reach, it reads that whole tie group too, so NextCursor never skips a tied run.
A tie group is read with growing page sizes until the overload returns fewer rows than asked, so
the extra reads are proportional to the number of tied runs and happen only on a tie. Exactness
relies on the overload honouring startedFrom / startedTo; with a
Skip, offset semantics apply to the rows older than the cursor, as they
do on the built-in providers. TotalCountCap is applied to the exact
count the legacy overload returns.
StartRunAsync(Guid, string, Guid, string, string?, string?, Guid?)
Creates a new run record in Running status and returns it.
Called once per TriggerAsync invocation.
Task<FlowRunRecord> StartRunAsync(Guid flowId, string flowName, Guid runId, string triggerKey, string? triggerData, string? jobId, Guid? sourceRunId = null)
Parameters
flowIdGuidThe flow definition this run belongs to.
flowNamestringDisplay name of the flow at trigger time.
runIdGuidUnique identifier for this run, generated by the engine.
triggerKeystringThe manifest trigger key that fired (e.g.
"manual","schedule").triggerDatastringJSON-serialised trigger payload, or null.
jobIdstringRuntime job ID (e.g. Hangfire BackgroundJobId) for cross-referencing, or null.
sourceRunIdGuid?When this run was created via "Re-run all" on a previous run, the ID of that run; otherwise null.
Returns
TryCompleteRunningStepAsync(Guid, string, string, string?, string?)
Records the outcome of a step exactly like RecordStepCompleteAsync(Guid, string, string, string?, string?), but only when the step is still Running, and reports whether this call made the transition.
Task<bool> TryCompleteRunningStepAsync(Guid runId, string stepKey, string status, string? outputJson, string? errorMessage)
Parameters
runIdGuidThe run owning the step.
stepKeystringThe runtime step key, e.g.
"outer.1.inner".statusstringThe terminal status to set.
outputJsonstringThe step output, or null.
errorMessagestringThe failure or skip reason, or null.
Returns
- Task<bool>
true when this call moved a
Runningstep tostatus; false when the step was no longerRunning(another writer won, or it has no row).
Remarks
The engine settles a ForEach loop step through this method. A loop step is the only step whose
completion is decided outside its own handler, by whichever worker completes the loop's last
outstanding child, so two workers can decide it at the same moment. Only the caller that wins the
transition publishes the loop's StepCompletedEvent and continues the graph from it. The check
and the write must be one atomic step (a conditional UPDATE and its row count, or a lock).
There is deliberately no default implementation: an unconditional fallback would bring the double
settle back without any compile-time signal.
TryRecordDispatchAsync(Guid, string, CancellationToken)
Atomically records that a step has been dispatched for execution. Returns true if this is the first dispatch for this step in this run; false if the step was already dispatched (idempotent guard — caller should skip).
Task<bool> TryRecordDispatchAsync(Guid runId, string stepKey, CancellationToken ct = default)
Parameters
runIdGuidstepKeystringctCancellationToken
Returns
Remarks
Must use an atomic INSERT-if-not-exists primitive (SQL WHERE NOT EXISTS,
PostgreSQL ON CONFLICT DO NOTHING, or TryAdd(TKey, TValue)).