You write a function, put @flow on top, and call it. Something inside the process creates a run record, proposes a state to a server, catches a retry, persists a result, and stamps a timestamp you never asked for. That gap between the function you wrote and the run the platform reports is where most debugging happens, and it is not obvious from the tutorial.

Prefect is a Python workflow orchestration library maintained by PrefectHQ. The repository is large, but the path from a decorated function to an orchestrated run is short enough to read. This tour follows that path through the real tree of the main branch — the decorators, the state model, the run engine, the proposal loop, and the contexts and cache keys that surround them — so the next time a run is stuck, paused, or retried, you know which object to open.

Everything below is anchored to file paths and line numbers that exist in the repository today. Where a name looks like a class but is really a factory, or lives in a surprising module, it is called out, because those are exactly the detours that cost time. If you come from a Celery-style task queue, the mental model changes: this is not fire-and-forget dispatch, but a run whose every transition is negotiated with a server.

Overview of the Prefect source: decorators, state model, run engine, orchestration client, runtime context, and cache policy

The main path: a decorated function becomes a Flow or Task, the engine drives it, and every transition is proposed to the orchestration API.

Reading the overview from left to right:

  • Flow, L152 is the generic wrapper that holds the entrypoint, retry settings, hooks, and task runner for a workflow.
  • flow, L2407 is not a function but a single FlowDecorator instance; the decorator class itself begins at FlowDecorator, L2146.
  • Task, L317 carries cache policy, retries, result storage, and state hooks for a unit of work.
  • task, L1996 is the overloaded factory function whose real implementation returns a Task instance.
  • State, L237 is the Pydantic model for the status of a run, including its type, name, details, and data.
  • BaseFlowRunEngine, L432 is the shared dataclass that owns begin_run, set_state, and result.
  • propose_state, L514 sends a proposed state to the API and retries while the answer is WAIT.
  • RunContext, L408 is the base context object that exposes the ambient flow run, task run, and settings.
Detailed Prefect architecture: decorators, state constructors, sync and async engines, orchestration routes, contexts, settings, and transactions

The detailed view separates the two engines, the four state responses, the context hierarchy, and the cache and transaction layer.

What the decorators actually hand you

The first surprise is that @flow is not a function. flows.py defines a FlowDecorator class and then instantiates it once as flow, so the decorator supports both @flow and @flow(name=...) forms through overloaded __call__ signatures. When it runs, it builds a Flow object whose __init__ accepts a long list of options: retries, retry delay, task runner, parameter validation, result storage, and five categories of state hooks. That list is why @flow can change execution without changing your function body.

@task is a plain function with layered overloads. Its implementation returns a Task, and the constructor mirrors almost the same option set plus caching. This is where the asymmetry matters: flows own the run boundary and the task runner, while tasks own cache keys and result persistence. MaterializingTask, L2218 is a smaller subclass that commits artefacts through a transaction, which is a hint that tasks are not only calls but also write units.

The decorators also explain a common confusion. A Flow is callable, so calling my_flow() does not call your function directly; it enters the engine, creates or updates a flow run, and only then invokes the wrapped entrypoint. The task path is similar but shorter, because a task normally runs inside an existing flow run context.

Parameter validation is a good example of the hidden work. Flow.__init__ records validate_parameters, and begin_run re-checks it before execution; a bad argument becomes a handled failure with a Failed state rather than a raw traceback at the call site. The task side repeats the pattern through retry_condition_fn, which lets a failed task decide whether it should continue to its retry policy or stop. These switches are all stored on the object, so they travel with the call.

The state machine is the contract

The most important file to open is not states.py. The State class lives in client/schemas/objects.py, beside StateType, because both are shared by the client and the server schemas. StateType has eight members — SCHEDULED, PENDING, RUNNING, COMPLETED, FAILED, CANCELLED, CRASHED, and PAUSED — and the model adds a name, a timestamp, details, and payload data. If you are inspecting a run, this is the object you should print first.

states.py is where the convenience constructors live. Scheduled, Running, Completed, and Failed are functions, not classes; each wraps _traced, injects a trace parent, and returns a State. Reading them makes the transition vocabulary concrete: a status is a typed object with timestamps and optional data, not a bare string. StateGroup aggregates many states and exposes counters such as fail_count, all_completed, and any_failed, which is what makes aggregate inspection readable in logs.

The orchestration contract sits next to this model. A proposed state is not accepted blindly. The API answers with one of four values from SetStateStatus: ACCEPT, REJECT, ABORT, or WAIT. A rejection can return a different state, a wait asks the client to sleep and try again, and an abort raises. That small protocol is the reason a run can look “stuck” while the server is deliberately pacing it.

From a call stack to a supervised control loop

The single largest behavioural jump is the move from a normal call stack to a supervised loop. BaseFlowRunEngine is a dataclass, not a simple function. Its begin_run first resolves parameters and dependencies, validates them when the flow asks for it, and then proposes Running. If the proposal comes back pending, it sleeps for 0.2 seconds and proposes again, which is visible in the loop at the end of begin_run. That retry is not a bug; it is the client negotiating with orchestration policy.

set_state is the other half. It short-circuits when the engine is in a failure state, stops heartbeats before proposing a final state, calls propose_state_sync, writes the accepted state back onto the flow run, and then runs state hooks. The heartbeat floor is MINIMUM_HEARTBEAT_INTERVAL = 30, so the engine will not promise more frequent liveness than thirty seconds. This combination — heartbeat, proposal, hook — is the real meaning of “the engine ran my flow”.

The heartbeat thread and the proposal call are deliberately separated: the thread proves liveness while the proposal changes state, and set_state stops the thread before a terminal state is written. That ordering avoids an automation that expects one event per heartbeat firing on a finished run. The supervisor in engine.py then maps control outcomes to exit codes so a runner can distinguish an abort from a crash.

Dispatch happens in run_flow, which chooses between four paths based on two flags: isasync and isgenerator. The result is FlowRunEngine, AsyncFlowRunEngine, or one of the generator variants. At the process boundary, engine.py is a thin supervisor: its __main__ block loads the flow run, installs handle_engine_signals, and translates Abort, Pause, and termination signals into exit codes. In other words, the heavy logic is in flow_engine.py; engine.py is about staying alive long enough to report the outcome.

Context, settings, and cache keys

Runtime information is carried through context variables. RunContext is the base model; EngineContext adds the flow run and task runner, TaskRunContext adds the current task run, and SettingsContext wraps the active settings independently of a run. get_run_context returns either a flow or task variant, which is why helper code often asks for the context instead of receiving it as an argument. The settings root is a Pydantic model with sub-models for flows, server, and tasks, so configuration is validated rather than read as loose strings. The async layers build on AnyIO, and the orchestration client sends requests through HTTPX, so the transport can be swapped without changing the engine.

Caching is deliberately composable. CachePolicy defines compute_key, and policies can be added or subtracted to build a compound key. TaskSource, FlowParameters, and Inputs are concrete policies, while CompoundCachePolicy merges several into one deterministic value. Inputs hashes the call arguments, TaskSource hashes the function body, and FlowParameters hashes the flow inputs, so adding them together yields a key that changes only when the relevant part changes. That design keeps cache identity in code rather than in a magic string, and it is why changing a decorator argument can change the key without touching the cache backend.

Transactions cover the write side. CommitMode and TransactionState define when a result is staged, committed, or rolled back, and Transaction and AsyncTransaction implement the same shape for sync and async work. MaterializingTask uses this layer so a task can produce an artefact and still fail cleanly. For readers coming from simpler task queues, this is the part that feels most like a database: a write is prepared, then confirmed.

Honest Limits

This tour describes the code as it exists on main, and that code moves. Several behaviours depend on a running API: the engine proposes states, but the server decides whether they are accepted, rejected, or delayed. Reading only the client will not tell you why a particular deployment rejects a transition.

The split between flows.py and flow_engine.py, and between tasks.py and task_engine.py, also means there is no single “run” function to memorize. Sync and async paths diverge, generator flows add two more branches, and the engine dataclasses carry a lot of state. If you need to debug a specific run, start from the State object, then the engine’s set_state call, then the client route; that order follows the data rather than the documentation.

Finally, the repository is large and the package layout is still evolving. File paths and line numbers in this article were verified against the current tree, but they will drift. Treat the names and the control flow as durable, and the exact numbers as a snapshot. It is also worth remembering that the default local experience is intentionally forgiving: states can be set locally, and some failures only become visible once a real API and worker are involved. Reproducing an orchestration decision therefore means reproducing the server policy too, not just the client call.

Watch PyShine on YouTube

Contents