@durable: compile generators into picklable state machines

I want to pitch a @durable decorator. It takes a generator function and rewrites it into a generated class. Any local that’s still needed after a yield becomes an instance attribute, and a match on a program-counter field jumps back to the right checkpoint. What you end up with is a plain object that pickle can save and resume.

I’m not trying to put storage or scheduling in the language. That stays in libraries. The bit I think only the language can do properly is the state machine itself, built by the compiler, which also refuses to resume if the code it was saved from has changed.

The problem

Python has no built-in way to make a long-running function survive a restart. Today you pick from:

  • Event sourcing and replay (Temporal-style). Every resume re-runs the function from the top against a recorded history.
    • It gets slower the longer the history is.
    • Your code has to be deterministic, so the framework gives you its own sleep, now, uuid4 and random, and you have to remember to use them instead of the real ones.
  • Step memoization (DBOS-style). Each step is wrapped in a decorator and finished steps get skipped on re-run. It’s still a replay of the function body, and it still needs a database or server.
  • Hand-written state machines. They work, but the logic disappears into a big match and a pile of boilerplate.

Pretty much all of these mean running or paying for an orchestrator before you get any durability. If the language did the transform, a plain script could persist to a file, SQLite or S3 and that’s it. No server.

The idea

@durable
def onboard(user_id):
    account = yield Step(create_account, user_id)
    yield Step(send_welcome, account)
    yield Sleep(days=3)
    yield Step(send_tips, account)
    return account.id

Every yield is a checkpoint. The decorator swaps the function for a class that works roughly like this (illustration only):

class onboard:
    def __init__(self, user_id):
        self.user_id = user_id    # only locals still needed after a yield become fields
        self.account = None
        self._pc = 0              # program counter: which checkpoint we're at

    def __iter__(self):
        return self

    def __next__(self):
        return self.send(None)

    def send(self, value):
        match self._pc:
            case 0:
                self._pc = 1
                return Step(create_account, self.user_id)
            case 1:
                self.account = value
                self._pc = 2
                return Step(send_welcome, self.account)
            case 2:
                self._pc = 3
                return Sleep(days=3)
            case 3:
                self._pc = 4
                return Step(send_tips, self.account)
            case 4:
                raise StopIteration(self.account.id)

It follows the normal generator protocol (next(), send(), for loops), pickle and copy just work on it, and calling onboard(...) looks the same as calling the generator did.

Saving and waking back up is left to you (or a library):

run = onboard(user_id)
request = next(run)                   # start, same as any generator
store[key] = pickle.dumps(run)        # file, SQLite, S3, whatever

run = pickle.loads(store[key])        # later, in any process
request = run.send(result_of_last_request)   # or next(run) if there's nothing to pass in

When the code changes

I don’t want a version number you have to remember to bump. Instead, when @durable is applied it hashes the function’s AST (ignoring comments and formatting) and saves that hash with the state. When a saved run is loaded:

Saved hash vs current code restore defined? What happens
same n/a resumes as normal
different no raises DurableCodeChanged
different yes restore(state) is called and its result is used

restore is basically pickle’s __setstate__, registered the same way @property.setter is:

@onboard.restore
def _(state):
    # state is the old dict of fields, including "_pc"
    state.setdefault("plan", "free")
    return state

So the default is safe. Resuming a run against code it wasn’t saved from is an error, never a quietly wrong answer. If you want old runs to carry on, you tell it how.

Why this isn’t just a macro or syntax sugar

  • It needs the compiler’s own control-flow and scope analysis.
    • try/finally, with, nested loops, comprehensions, yield from and closures all have to be turned into dispatch cases.
    • The compiler has to figure out which locals are still live across a yield, so only those become fields. This is how C#'s async state machines work.
    • A text or AST macro can get close, but it’s fragile and ends up copying the compiler’s symbol-table logic.
  • Tooling has to keep working. Tracebacks, line numbers, sys.monitoring and debuggers should point at the code you wrote, not the generated match.
  • It replaces replay rather than hiding it. Resuming is O(1): jump straight to a case. Nothing in the stdlib needs swapping out and nothing has to be deterministic, because finished work never runs again.
  • State is just data, not an opaque frame. A _pc plus some fields can be inspected, hashed and migrated. It isn’t a pickled interpreter frame, so a tampered bytecode offset can’t crash the interpreter.

You also get forking for free: copy.copy(run) gives you an independent continuation you can resume as many times as you like which in theory allows for multi-threaded async loops.

Trade-offs and open questions

  • Locals must be picklable. Anything still live across a yield has to pickle.
  • yield inside with or try/finally. I’d start by making a yield inside with a SyntaxError, and maybe later let context managers opt in.
  • Performance. Attribute access is slower than fast locals, but only @durable functions pay for it.
  • The AST hash is blunt. Any real edit to the function changes it, so every in-flight run needs a restore or it fails. I think that’s the right default, but it does mean one restore has to cope with every old shape, same as __setstate__ does.
  • Hash stability. ast.dump output can change between Python versions, so the normalisation would need defining. Otherwise upgrading Python could invalidate saved runs.
  • Checkpoint identity. Checkpoints are numbered in source order, so adding a yield shifts every later _pc and restore has to remap it. Would nameable checkpoints make that easier?
  • Async. Should this cover async def, with await as the checkpoint? I’d start with plain generators.
  • Where it lives. functools, a new module, or a proper language feature, since it needs a compiler hook.

What would help from the language

None of this is needed for a first version. That could be a third-party prototype built on ast, symtable and inspect.getsource. But these would make it a lot sturdier:

  • A public, stable API for liveness analysis and the control-flow graph.
  • A default __reduce__ and restore hook for generated state-machine classes.
  • A defined, stable way to hash a function’s code across edits and Python versions.
  • A debugger and traceback mapping API for generated code.

Prior art

  • C# async state machines (the compiler turns async into a state machine with hoisted locals).
  • Kotlin coroutines (a continuation-passing transform).
  • Rust async (generated state-machine enums).

I’m not aware of anything like this inside Python itself.

What I’d like feedback on

  1. Is a compile-time state machine acceptable, given its restrictions, compared with snapshotting a running frame?
  2. Is hash-and-raise with an optional restore the right shape for changed code?
  3. Which of the language-support items would matter most if you were writing a durable-execution library?

Why do you want this? A real-world use case motivating this workflow would help make this less abstract.

2 Likes

Side point: match is a poor choice here IMO - it’s not a C switch statement.

I don’t think your goal of transparency is viable. You want tracebacks and such to point to the original code, but the actual code being run is very different. That’s going to be either impossible, or very confusing.

Maybe Python’s generators aren’t the right tool for this job. I’ve built a number of apps that are designed to hot reload, and usually the solution isn’t to try to shoehorn a generator into working that way, it’s to rearchitect in a way that separates code from data. This requires some care from the programmer, otherwise it WILL be fragile.

6 Likes

I second @Rosuav’s point about the goal of transparency viability, and think it is worth elaborating on. My relevant experience is building orchestration engines, which I think is what you are working towards.

As I read it the simplicity in your proposal is that users don’t have to worry about the state machine or defining it explicitly. I think this isn’t true though…they do in order to handle the case where they need to change the @durable-decorted function. Your proposal says users have to handle that manually, but to do that they need to know the state model, what state in-progress executions are in and how to adapt the old state machine to the new state machine. In addition to this, they have to figure out how to map that onto the constructs your decorator/execution engine provides. I think that is actually a bigger task than just managing the state machine itself because that doesn’t incur the extra abstraction.

For a proposal like this to be viable I think it needs to address the full lifecycle, including the path of upgrading an existing workflow to incorporate changes. That is one of the hardest parts of a system like this and it can’t really be evaluated while saying it’s out of scope. At the very least you need to understand what that scope is and that it’s even possible. As it stands, I don’t think there is a way to do it that doesn’t involve managing the state explicitly, negating the key benefit. Users would have to find all the ast-hash-invalid workflows, extract the state from them, and write the new version to manage that state…or just start them fresh/have duplicate tips sent…which makes the framework not very useful.

There really isn’t a way to avoid the state machine. It is what is being managed. Modeling the execution of rigid static code that implements it manages something as a proxy for it, but it’s a leaky abstraction and ultimately not what the user really wants…they want a simple way to manage a state machine, not a way to model execution of code that walks through an implicitly defined state machine.

1 Like

Thanks both, I will clarify

Why I want this

Fair question, I should have led with a real example. Durable execution is basically a new programming paradigm, and right now it’s been shoehorned into
Python from the outside.

Here’s the kind of thing I mean. Say you’ve got a photo processing job: upload the images, merge them, enhance them, wait for a webhook or a human review,
deliver, then send a follow-up three days later. It runs for minutes to days, and it’ll get killed halfway by a deploy, a timeout or a crash. What I want to
write is just that straight-line function. What I actually do today is one of two things:

  • Hand-roll a state machine. A table of step rows plus a big if/elif that works out where we got to.
  • Adopt a framework (Temporal, DBOS and friends). That means their own sleep, now, uuid4 and random, determinism rules I have to remember, and usually a
    server or database to run it. The code looks like Python but isn’t quite Python.
  • Build a complicated web of distributed systems that all need to coordinate with each other.

This sort of workflow shows up in payment and onboarding flows. It also shows up in LLM agent loops, where you want to resume after a crash without re-running (and re-paying for) the tool calls you already made.

I think built-in support would help for the same reason async/await did. That pattern started as library tricks (callbacks, then generator-based coroutines) and became language support edonce everyone was doing it. Every durable framework currently reinvents the same machinery in its own incompatible way, and small cases need a whole server for something that could be a file on disk.

On match and transparency

Both good points. The match in my snippet was only a mental model of roughly how these libraries get it done, and I don’t expect the real implementation to look like that. It could be an if chain or a jump table or whatever the compiler prefers, so I wouldn’t hang anything on it.

You’re also right about transparency. If the code that runs is very different from the code you wrote, tracebacks that pretend otherwise would be impossible or confusing, and I shouldn’t have promised it.

That pushed me towards a smaller idea. What the libraries really do is build a custom data flow. They record each step’s result in an event log, and onresume they re-run the function and check the log at each step. If a step is already done, they hand back the recorded result instead of executing it again.
That “knowing when not to execute work” part is the core of it.

So maybe what Python could ship is a lightweight primitive for that, not a compiler transform. Think of a memoize function with a persistent log keyed by
call order, a bit like React hooks. Roughly:

with durable.run(log) as ctx:
account = ctx.step(create_account, user_id) # on replay, returns the recorded result
ctx.step(send_welcome, account)
ctx.sleep(days=3)

The stdlib could also provide the deterministic now, random and uuid4 on ctx, so nobody has to patch anything. It re-runs the function body, so it has the
replay trade-offs I mentioned. But it’s small, needs no compiler changes, works with ordinary functions, and tracebacks stay honest. We could see whether
compiler support is worth adding later.

My real motivation is that I don’t love needing patched functions or a custom library to get this, and other ecosystems have built-in support for parts of it.

In general, “here’s a smaller idea” is a good angle to take :slight_smile:

A state machine is a concept of execution. What you’re describing is very much akin to a job with states, which is a pretty straight-forward notion to implement. Divide your tasks into individual steps, and have each step mark the job as having had that step done. (Or have a sequence of steps that get marked as done.)

A bit of a mock-up:

@step
def crop(image, x, y, w, h):
    cropped_image = ...
    return cropped_image

The step() decorator would take care of recording state in some durable way (I’d reach for a PostgreSQL database for this, but anything would work), and also marking whether the task has been completed. Then when you start the task over, that same decorator would inspect the job’s state and determine that it can skip this one.

1 Like

Thanks, I’ve played with it more and changed the shape, so here’s where I’ve landed.

So I think what I’d like to see is something small in the stdlib, in the spirit of functools: a decorator plus a few helpers, no required server, no patched functions. A durable function is an async generator, every step is a yield, and the thing that drives it records each step so a run can be pickled and picked up later:

@durable
async def render_hdr(order_id):
    brackets = yield fetch_brackets(order_id)    # fetch_brackets is @durable too
    hdr = yield merge_brackets(brackets)
    yield durable.result(hdr)

@durable
async def sleep_for(seconds):
    wake_at = (yield durable.memorize(time.time)) + seconds
    yield durable.suspend(until=lambda: time.time() >= wake_at)
    yield durable.result(None)

@durable
async def process_order(order_id):
    started_at = yield durable.memorize(time.time)        # non-deterministic, so it's recorded
    hdr = yield render_hdr(order_id)
    enhanced, thumbnails = yield durable.gather(enhance(order_id), make_thumbnails(order_id))
    yield sleep_for(3 * 24 * 3600)                        # three days
    receipt = yield notify(hdr)
    yield durable.result((started_at, receipt, enhanced, thumbnails))
run = process_order(42)
run.run()                    # say merge_brackets blows up here
blob = pickle.dumps(run)     # file, SQLite, Postgres, whatever

run = pickle.loads(blob)     # later, in another process
run.run()                    # SUSPENDED while the sleep isn't up, the result once it is

The rules are simple. Everything you yield has to be a @durable call, otherwise you get an error, and so does an await in the body. Anything non-deterministic goes through durable.memorize(fn, *args). A function can suspends itself with yield durable.suspend(until=...).

When the run is resumed the function is replayed from the top: recorded steps return their logged result without running again, and the until predicate gets checked live, so it can decide to suspend again (that’s how sleep_for works). The result is an explicit yield durable.result(x), because async generators can’t return a value and a plain yield has to be an error, otherwise forgetting memorize would quietly destroy your workflow.

I’ve got a working prototype of this (around 320 lines including the demo, tested on 3.14).

I think it belongs in the stdlib rather than as a library for a few reasons. It’s small and generic like functools.cache or contextlib. A shared log format means runs and tools can interoperate instead of every framework having its own. And only the stdlib can make time, random, uuid and secrets durable-aware without monkeypatching, so i theory wouldn’t need memorize(time.time) at all.

A hook to see every awaited coroutine (I think sys.set_coroutine_wrapper was something like that once, removed in 3.8 if I remember right) in theory could help.

Things I know are rough. A bare time.time() or random.random() inline in the body is invisible to the driver, so the “error if it isn’t durable” check only covers yields and awaits, not hidden non-determinism.

Replay cost grows with the log, though it only re-runs the glue code, not the work. Code changing under a saved run isn’t handled yet. gather only takes leaf calls in my prototype. There’s no TaskGroup or event loop around the body, which is the price of being strict. And calling a @durable function outside a run gives you a run object, which might surprise people.

Does something like this feel right for the stdlib, or is it better left as a library for now? And is there anything about async generators that makes this a bad foundation that I’ve missed?

IMO this shouldn’t be in the stdlib. The core features you’re looking for are async functions and the broad concept of a runner, both of which exist in the stdlib; the exact semantics of that runner are up to you, and can be third-party (possibly published to PyPI).

Part of the reason that this doesn’t belong in the stdlib is that word “pickled”. Is the pickle module the right choice? Would JSON be a better choice? Maybe there’s something even better, perhaps a binary blob in a Postgres database - and the stdlib doesn’t have pgsql support, so that would have to be provided elsewhere. To put it into the stdlib, you’re saying that this has to be right for everyone, but as your own tool, you can use whatever is best for you.

That said, though, if there ARE tools that would be better done in the stdlib - or even the core language - then this is the perfect way to figure those out.

Out of curiosity, why async AND generator? You never await anything here (or maybe I just missed seeing it); are you using both layers here?

I have just been doing something somewhat similar to this. Maybe you can borrow ideas. It’s in a Pike project, not a Python one, as that’s a better choice for the project overall - the languages have many similar facilities so this should be fine. In my system, I have two instances of my Twitch bot, and it’s possible that one or other of them needs to be brought down. When that happens, I signal the other one to take over, and it will request a package of half-done jobs that it needs to manage. Let’s say a job consists of say hello to one person, wait five seconds, then say hello to everyone. If the bot hops during those five seconds[1], the newly-active bot has to know to do the second part at the correct time, without redoing the first. I do this by translating “sleep five seconds” into “in five seconds, do this”, and I have the record of which things need to be done when in a transferrable blob. Everything’s JSONable so it can be sent down the wire.

That shouldn’t be a major problem. As long as the “work” sections are done in reasonably large chunks, they’ll vastly dominate the run time, so rerunning the glue shouldn’t add too much.

I think it’s best left as a library, but IMO it has the potential to be very useful. Async generators might be overkill and either async functions or generators might be sufficient, but that’s just from my reading of your example and maybe that’s just my mistake. Async functions are definitely a great tool here - they’re specifically designed to be infrastructure for any of multiple runners, and you’re basically creating a special purpose runner.

So yeah, I think you have the start of something pretty good here, just not for the stdlib.


  1. ignore the fact that, in all plausible situations, it’s going to take me longer than that to decide to switch active bots - but pretend that this was actually a 30 minute delay or something ↩︎

1 Like

The mentioned finite-state machines do not have to be hand-written (*). An FSM backed by some reasonable implementation should be also considered as an alternative,


Side note: Actually, I recommend against. I wrote a partially related asyncio software and there is devil in the details.

Do you think that the durable paradigm is common enough yet to be added to the language, like async-await was?

1 Like

Thanks everyone, This was super helpful push back and I think I can distill this into some first principles. I’m not super familiar with all of python’s internals so this has helped me learn more.

I will answer each in turn and sum up where I have got to

I think the durable paradigm is becoming more and more common that it was. I think each implementation is similar to async in that it presents a sort of soft fork of python, not perhaps to the same extent that async did.

But at it’s core each one implements the control flow differently, some use generators and use yield to express checkpoints. Others use async but almost all of them force you to use custom objects and patched functions to workaround things.

This reminds me of how early async code in a lot of languages forced you to use custom async objects and made it so you needed to replace entire parts of your stack based on which async runtime they were built on.

I can already see elements of this happening.

Luckily alot of the ground work has already been done, Instead I think what python maybe needs is just some core primatives that create a consistent interface and control flow similar to what asyncio did for async.

These primatives will be unopinionated about the infrastructure of durable execution they simply exist to server two purposes:

  1. Allow end users to have one set of rules regarding control flow
  2. Durable execution libraries can consume code written in this structure and handle the durable execution, similar to how users can write asyncio code once and, with a few notable exceptions, run this code in a different asyncio runtime.

Here are the primatives I think such a solution would need to provide and perhaps there is an argument that this should live within the asyncio module.

  1. The ability to mark a coroutine as a discrete task via a decorator

All of these methods at their core depend on the ability to give some work a stable identifier, spin up the work, identify when it is done store that against the identifier and if we need to resume the work replay the result based on it’s identifier.

Most libraries create their own constructs or decorators for doing this. Asyncio has something equivalent to this in the form of a Task but it’s not super ergonormic.

The first primative I think we would need is to annotate a coroutine as being a task, it would handle spinning up as a task and giving that task the stable identifier needed for replay etc.

I envision this just being a new @task decorator which will handle doing asyncio.create_task and giving the task a stable ID

@task
async def this_function_name_is_the_identifier():
   return "Wow this is pretty cool"
  1. A new durable runner which keeps track of the execution and handles replay

The way many runtimes handle this such as temporal, is they provide a custom asyncio runner that is able to consume the objects they spin up and it keeps track of which order the tasks were created so they can be replayed.

So therefore we could provide a default implementation of this logic in asyncio.durable. The Runner sole purpose is just to keep track of which tasks were running, in which order were they spun up and for the ones that completed what were their result so it can be returned as a cached result.

I envision the API being no different than that of any other asyncio runner

  1. A way of capturing the current state on an exception and restoring the state

Essentially we need something equivalent to the getstate and setstate methods some objects have, anything else will be left to the runtime.

Here is one idea I had, asyncio.durable could provide a @durable decorator which uses the @task decorator to mark the function as a task (see above) and returns a special durable object.

It also provides these state methods, when ran in the context of the Durable runner from point 2 a DurableException error can be raised.

This is a special type of exception which gives you a reference to the durable object so you can grab it’s state, you can serialise this state how you wish.

The only functions that use this are ideally just the main parent function that represents the main workflow so it keeps the overhead of this small.

When restoring the state since the coroutine function hands you a durable object you would use the setstate object to restore it’s state and then upon dispatching this to the DurableRunner via run would simply replay execution.

  1. A simple way of making external non-durable functions or functions with side effects work with durable execution

Normally these libs patch or otherwise provide durable version of all of these but the number of ones they may need to patch are endless.

I suggest a simple function that works to utilise the durable execution runner’s infra to memorise results.

The most simple solution for this I can think of is to allow a non-async function to be passed into the task decorator so code like this could be memorised

@durable
async def send_email():
   the_date = await task(time.now)

runner = DurableRunner()
task = send_email()
task.setstate(state_i_loaded_earlier)
runner.run(task)

We are asking the durable runtime to take the time function convert it into a task that can be awaited, because it is now a task it an be replayed. And because it can be replayed it can now be part of a durable function.

So thats it 4 small primatives, anything else such as providing an simple implementation of sleep that works for durable execution could be provided by external libraries. Maybe common ones like sleep could be folded into this new module but I think we can defer that to see what they are.

It keeps the opinions to the frameworks, it just tackles what I think is the main annoying & fiddly bit these frameworks are having to solve which is how do you handle the control flow.

2 Likes

Hi all,

So I’ve been playing around with this and I think I can simplify this proposal even further, as discussed we want a consistent interface that diffetenr durable execution runtimes can use.

End users write their code once without tying themselves to a framework and libraries handle the details. This is along the same lines as asyncio or logging.

Therefore we just need to achieve theree goals:

  • A way of registering a hook which can be used to replay and store the results for a series of function calls (think lru_cache but for execution order similar to hooks in a library like React)
  • A way to provide a context which can be used to restore the state during replayes
  • A common API for suspending

I think we only actually need 3 primatives for this:

  • @durable / durable(func) - Registers a function as being durable and handles calling the hook before the function is called, and after if the library decides it should be called
  • DurableContext - ContextManger which provide the logic for storing and loading the state, provides the hooks. Details left to libraries, standard base class is just abstract implementation with details left to lib.
  • Suspend - A BaseException which semantically means something needs the Runtime to suspend the execution and resume it later. Used by libraries or user code to implement things like sleeping rather than being a true error.

I have a POC which I am happy to share which now works with any type of function and not just async.

if you think this is a good direction ? For now I’m thinking this would land as a simple “durable” module as no other fit this shape.

This is not a good way to handle this since your goal is to be able to resume. The problem with throwing exceptions into code rather than it raising from internally is relatively bad already for KeyboardInterrupt and asyncio related cancellations, as it can leave code in a non-recoverable state. People use these anyhow, but with the intention of not continuing. (I register a handler for signals to prevent arbitrary locations for KeyboardInterrupt, and avoid cancellation in asyncio, but that’s not the default nor is it common advice)

I would seriously rethink this proposal in it’s entirety, as there are reasonable ways to handle this already without trying to restore generators from a prior state. (usually most easily represented by a consumer producer pattern, and having some external storage or scheduling service)

1 Like

Good points, I actually needed this abstraction layer at work and it gave me an opportunity to iterate.

Based on the fact most durable runtimes just yield objects that represent what the runtime I should do, I’ve distilled it into the following two primatives:

  • A Durable Object - Represents a callable that we need to replay the result for, they can be suspended meaning that the condition has not been met for the callable to execute and finally the callable can be a generator function that yields other durables which is how the end user will implement workflows
  • The durable decorator - Removes a lot of the boilerplate by wrapping a callable in a Durable Object

This in itself is enough to write a driver that can step through a durable generator, call the functions and replay after errors.

When it comes to adding support for suspending and resuming we can simply add specialised subclasses of the Durable Object.

  • DurableTimer - This durable stays in the suspended state until the specific timestamp has passed. This is enough to implement sleeping, polling and timeouts.
  • DurableSemaphore - This durable stays in the suspended state until the driver marks it as complete. This is enough to implement callbacks.

Since they are just standard durable objects, they will be yielded and the driver is tasked with consuming and handling them similar to Task objects and asyncio.

I’ve used this setup to allow me to run the same durable code on both AWS’s Durable Lambda and in-memory during unit testing. So it so far seems like a reasonable direction.