Workflow engine and runtime
The workflow engine turns SQLAlchemy rows into durable, scheduled runs. Application code declares steps and transitions, while workers claim due rows, execute one step, and save the next state. The engine also supports event delivery, retries, child runs, rate limits, and several worker processes against the same Postgres database. See Workflow orchestration, Application lifecycle, and State and events for related views.
Workflow model
The workflow model gives each run a durable row and gives each step a typed way to describe what happens next. The application owns its business columns. The workflow mixin owns the scheduling and coordination state that lets workers resume a run after a delay, an event, a retry, or a process failure.
Workflow rows
packages/…/model.py defines Workflow, the mixin that adds workflow state to an application model. One row represents one run. Its state names the next step, its arguments, the next wake time, any event wait, retry information, claim lease, parent run, and child count.
The class registry maps workflow table names to workflow classes. This lets the engine resolve parent pointers and select the workflow classes that a default worker serves. Application columns remain the run's business state and are saved with the workflow state. The mixin reserves its coordination columns, so an application field cannot silently replace state that the engine needs.
The package's public surface re-exports workflow models, transition builders, cron schedules, run handles, and runtime controls. Application code can therefore use one stable package interface to declare runs and connect them to workers.
References: packages/…/model.py• L786-858 packages/…/__init__.py• L3-32
Step declarations
The step decorator turns an async method into a workflow step. Calling the decorated method does not execute it. It creates a Call that the engine can store and run later. The declaration also sets retry behavior, a retry delay cap, and a lane that controls which workers may run the step.
The engine checks a call when application code creates or delivers it. This keeps invalid step names and invalid arguments at the boundary instead of storing a run that fails only after a worker claims it.
References: packages/…/model.py• L106-132 packages/…/model.py• L234-278 packages/…/model.py• L351-375 packages/…/model.py• L378-435
Transitions
A step returns a transition that tells the engine how to continue the run. A direct step call runs next. wake_in adds a delay. wait_for pauses for an event and can name a timeout step. every repeats a step on a fixed interval or a schedule. fan_out starts child runs and waits until they all finish. None ends the run.
The engine converts each transition into row state. This makes the same worker loop handle immediate work, timer-based work, event-based work, and parent-child coordination.
References: packages/…/model.py• L178-231 packages/…/model.py• L453-539 packages/…/execute.py• L70-113
Cron schedules
packages/…/cron.py provides Cron, a five-field schedule for minute, hour, day of month, month, and day of week. It accepts lists, ranges, steps, and month or weekday names. A cron value returns the next matching time in its configured time zone.
The workflow engine treats a cron as a schedule function. It asks for the next time from the database clock while committing the step result. This avoids drift between worker clocks and keeps the stored wake time consistent across workers. Daylight-saving changes still produce one run for a skipped or repeated local time.
References: packages/…/cron.py• L103-209 packages/…/model.py• L203-216 packages/…/execute.py• L516-543
Run addressing and control
Application processes can create, inspect, advance, cancel, and signal runs without owning the worker loop. The handle API turns a SQL condition into a stable control surface for one or more matching rows.
Run creation
Workflow.start() inserts a new row and schedules its first step. The insert is idempotent under the row's uniqueness rules, so a repeated start does not create a second run for an existing unique identity. A successful start announces the workflow table and wakes a local worker.
The first step and its arguments are stored before a worker sees the row. The application can therefore start a run from a request process, while a separate worker process performs the work. A caller may name one unique column as the run identity. A clash on that identity means the run already exists, while a clash on another unique rule is reported as a conflict.
References: packages/…/model.py• L860-884 packages/…/handles.py• L115-207
Run handles
RunHandle represents rows selected by a SQL condition. It can read the first match or all matches. It can also schedule a step immediately, deliver an event, or cancel the matching runs.
These actions change the durable row rather than calling a step in the request process. A new version fences a step that is already in flight. The running step keeps its lease, so the replacement waits for it to finish instead of running beside it. Cancellation and preemption also complete any parent-child link that the stopped run no longer can complete.
References: packages/…/model.py• L929-963 packages/…/handles.py• L210-290 packages/…/handles.py• L455-541
Event delivery
RunHandle.deliver() addresses the event by the step that should consume it. If the run is already waiting, the event schedules that step. If the run is still moving toward the wait, the event is buffered and consumed when the wait is armed. A deadline ends the wait before a late event can win, based on the time the delivery reaches the row rather than on worker timing.
An optional event key makes delivery idempotent. The engine remembers recent keys and also prevents the same key from being queued twice while it is buffered or being taken by a step. restart=True lets a finished run accept a new event and begin again.
References: packages/…/handles.py• L292-453 packages/…/execute.py• L262-307
Claims and concurrency
Workers do not execute rows directly from a broad query. They first claim due rows with a short lease. The claim selects work that is ready, skips rows held by another worker, and records a version that later commits must match.
Due work
The claim path treats a row as due when its next step has reached its wake time or when a matching event is waiting. It orders work by the oldest wake time and uses row locks that skip rows already locked by another worker. It applies the same lane and lease rules to both claiming and idle-time due checks, so a worker does not sleep past work it can run.
The idle path asks each workflow table for its next due time. It also considers lease expiry and an event that is already ready. A row that waits for an external event without a deadline does not create a polling deadline; event delivery or notification must wake it. If one table cannot answer, the worker keeps using the other tables. It backs off only when every table refuses the query.
References: packages/…/claim.py• L54-134 packages/…/claim.py• L545-646
Leases and versions
A claim writes a lease expiry and increments wf_version. The lease stops two workers from running the same step at once. The version makes the later step commit conditional on the same claim still owning the row. Event answers move into the row's next step as part of the claim, so the wait ends once and the event key travels with the attempt until it commits.
Long steps renew their lease. If a worker dies, another worker can claim the row after the lease expires. If an event or another control action advances the row first, the old step becomes stale and its commit is rejected. The old worker can release only the lease value it last wrote, so it cannot release a newer worker's claim. Group claims serialize the active-count and rate-token decision for one group, while different groups can proceed independently.
References: packages/…/claim.py• L152-223 packages/…/claim.py• L401-458 packages/…/execute.py• L434-498 packages/…/execute.py• L667-717
Group limits
A workflow can limit work by a group column such as a customer or provider. An at_most limit caps the number of leased runs in that group across all workers. A rate limit uses a refillable bucket so the group can start work at a declared rate while still allowing a short burst.
The engine locks one group while it counts active rows, spends rate tokens, and claims rows. It visits the longest-waiting groups first and returns unused tokens when fewer rows are available than the claim reserved. A failure in one group's rows or rate bucket does not stop the pass from trying other groups. This keeps limits shared and prevents one busy or broken group from hiding work in other groups.
References: packages/…/model.py• L135-175 packages/…/claim.py• L226-315 packages/…/claim.py• L317-458
Step execution
After a claim, the engine runs one step outside the database transaction and then commits the result in one guarded transaction. The commit includes the row's changed business fields, its next scheduling state, attempt history when enabled, and any parent update. A schedule that needs application code is evaluated against the database clock before this commit.
Execution lifecycle
The execution path follows this sequence:
- Load the claimed row and verify that its version is still current.
- Choose a buffered event or the row's scheduled next step.
- Invoke the step with its stored arguments.
- Convert the returned transition into the next scheduling state.
- Start child rows when the transition fans out.
- Save changed user fields and workflow fields only if the claim version still matches.
- Record the attempt and wake newly available work.
This diagram shows how a durable row moves from a claim to its next state.
flowchart LR
A[Due row] --> B[Claim lease and version]
B --> C{Claim still current?}
C -- No --> D[Release stale lease]
C -- Yes --> E[Run step]
E --> F{Transition}
F --> G[Schedule next step]
F --> H[Wait for event]
F --> I[Start child runs]
F --> J[Finish run]
G --> K[Commit guarded row update]
H --> K
I --> K
J --> K
K --> L[Notify workers and parent]
References: packages/…/execute.py• L116-139 packages/…/execute.py• L667-838
Retry outcomes
When a step raises, the engine stores the error and either schedules a retry or marks the run failed. Retry delays start at the configured backoff and double until the step's cap. A successful attempt clears the retry count and last error. Invalid transition values and schedule failures use the same attempt outcome path as step errors.
If the step body succeeds but the database cannot commit its result, the engine records that failure in a separate guarded write. This prevents a bad stored value or constraint error from making the same attempt repeat forever without an outcome. If another worker has moved the row, that failure write is fenced too and reports the attempt as stale rather than overwriting newer state.
References: packages/…/execute.py• L210-259 packages/…/execute.py• L594-664 packages/…/execute.py• L667-838 packages/…/model.py• L612-668
Child runs
fan_out makes each child an independent run. Workers claim and retry children separately, while the parent holds no worker during the wait. The parent resumes when the last child finishes or gives up.
The parent stores the fan-out identity with each child. A child can therefore count itself once, even if it is retried or a worker attempts the same fan-out again. Child insertion and parent counting share the commit boundary with the parent transition. Cancellation follows the same completion path, so a parent does not wait for a child that was stopped.
References: packages/…/model.py• L178-192 packages/…/model.py• L464-497 packages/…/execute.py• L322-389 packages/…/execute.py• L546-591 packages/…/handles.py• L455-541
Runtime coordination
The runtime connects the worker loop, database sessions, local wake signals, and request-side controls. It keeps the worker responsive without requiring every process to poll at a tight interval.
Runner loop
run_workflows() starts a Runner for the selected workflow classes and lanes. The runner keeps at most the configured number of steps in flight. It gives each table a first share of the pass, uses a second pass for remaining capacity, and rotates the starting table between passes. This shares capacity across tables while leaving steps in other lanes for another worker.
When a pass claims nothing, the runner sleeps until the database says work is due. It bounds the sleep by the poll and idle intervals. If the database cannot answer, it retries with a growing delay rather than treating the result as an empty schedule. On shutdown it stops new claims, lets active steps finish within one deadline, and gives back leases for cancelled steps when possible.
References: packages/…/runner.py• L55-118 packages/…/runner.py• L120-219 packages/…/runner.py• L221-369
Notifications and polling
The engine announces a table through Postgres NOTIFY after a transaction writes work that another worker may take. A listener wakes only workers that serve the announced tables. Notifications reduce latency, but polling remains the correctness path when a driver cannot listen or a connection breaks.
The listener reconnects with backoff and wakes the runner when its connection is lost. A separate listening engine can be used when a transaction-mode pooler cannot keep a LISTEN connection. The engine avoids a listener when the database suspends while idle, because holding that connection would keep the database awake.
References: packages/…/notify.py• L28-39 packages/…/notify.py• L56-180 packages/…/runner.py• L371-514
Runtime contexts
Runtime holds the session factory, lease duration, wake event, listener state, and the state of empty worker passes. run_workflows() installs this runtime for a process that executes steps. connect_workflows() installs a lighter runtime for a process that only starts or advances runs.
The wake() function asks the local worker to run a pass and can wait until that pass finds nothing it can claim. The Settled state turns that empty pass into a reliable completion signal for request-driven wake-up on an application platform that suspends idle processes. Runtime state is restored when a context exits, so nested workflow contexts do not lose the outer worker.
References: packages/…/runtime.py• L12-121 packages/…/runner.py• L517-599
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to transition types must stay aligned with return-value validation, row scheduling, and the due-row query.
- Changes to workflow-owned columns must stay aligned with claim predicates, version fencing, event delivery, and migration indexes.
- Changes to parent pointers or child counts must preserve the fan-out version contract used by child completion and cancellation.
- Changes to cron or other callable schedules must preserve the database-clock contract in schedule commits.
- Changes to notifications must preserve polling as a complete fallback and must not wake workers for tables or lanes they cannot serve.
- Changes to lease or shutdown behavior must preserve the rule that only the worker's own lease can be renewed or released.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A worker dies while holding a claim | The row remains held until its lease expires | Lease expiry makes it claimable again; active steps renew the lease |
| An event or handle action advances a row during step execution | The old step cannot overwrite the newer state | wf_version fencing rejects the old commit |
| A step returns an invalid transition or bad stored value | The run records a retry or failed outcome instead of accepting invalid state | Transition checks, JSON validation, and guarded failure recording |
| A database listener is unavailable | Work written by another process may start later | The runner continues with due-time polling |
| A workflow group reaches its concurrency or rate limit | Due rows wait without starting | Group locks, active-run counts, and refillable rate buckets control claims |
| A parent is waiting for children that are cancelled | The parent could wait forever if cancellation is not counted | Cancellation finishes the child link and wakes the parent |
| Shutdown cancels a running step | Its row could remain leased after the process exits | Drain tries to release only the lease value held by that worker |
Key files
| File | Why to read it |
|---|---|
| packages/…/__init__.py | Shows the public package surface for workflow declarations, controls, schedules, and runtime entry points. |
| packages/…/model.py | Defines workflow rows, step decorators, transition types, limits, and parent-child model behavior. |
| packages/…/cron.py | Defines five-field cron schedules and time-zone-aware next-fire calculation. |
| packages/…/claim.py | Shows how workers find due rows, enforce leases, and apply group limits. |
| packages/…/handles.py | Shows how application code starts, reads, advances, signals, and cancels runs. |
| packages/…/execute.py | Shows the step lifecycle, transition handling, retries, child completion, and fenced commits. |
| packages/…/runner.py | Shows worker scheduling, lane selection, idle waits, notifications, and shutdown. |
| packages/…/notify.py | Shows the Postgres notification path and its polling fallback. |
| packages/…/runtime.py | Defines the process-local coordination state shared by runners and handles. |