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,uuid4andrandom, 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
matchand 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 fromand 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.monitoringand debuggers should point at the code you wrote, not the generatedmatch. - 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
_pcplus 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
yieldhas to pickle. yieldinsidewithortry/finally. I’d start by making ayieldinsidewithaSyntaxError, and maybe later let context managers opt in.- Performance. Attribute access is slower than fast locals, but only
@durablefunctions pay for it. - The AST hash is blunt. Any real edit to the function changes it, so every in-flight run needs a
restoreor it fails. I think that’s the right default, but it does mean onerestorehas to cope with every old shape, same as__setstate__does. - Hash stability.
ast.dumpoutput 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
yieldshifts every later_pcandrestorehas to remap it. Would nameable checkpoints make that easier? - Async. Should this cover
async def, withawaitas 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__andrestorehook 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
asyncinto 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
- Is a compile-time state machine acceptable, given its restrictions, compared with snapshotting a running frame?
- Is hash-and-raise with an optional
restorethe right shape for changed code? - Which of the language-support items would matter most if you were writing a durable-execution library?