Runs execute as asyncio tasks inside the API process. That process is reloaded on every deploy and restarted when it passes its memory limit. A run that was in flight at that moment has a charge attached to it and nobody left to finish it. This page is about how the system notices, who is allowed to act, and why a slow worker and a dead worker are handled by the same rule.
The problem
The obvious recovery is a startup sweep: when the API boots, mark every running run as failed and refund it. That sweep is wrong on a host that reloads processes with overlap. During a reload the old process is still draining while the new one starts. The new process sees runs that are running because the old process is running them, and a sweep would close live work and refund customers for results they are about to receive.
I met this class of bug first on site audits, which used a timestamp instead of a lease. Audits stuck in scoring after a restart needed a reaper, and review of the first version showed that it could flip a live audit during the reload overlap, overwrite its fields, or refund a paid audit that then finished normally. The run reaper was designed after that, with one rule: act only on a run whose owner has provably stopped renewing it.
Who owns a run
Each process builds an owner id once, at import time.
# host, pid, and a random suffix: separates two processes that overlap during a pm2 reload
OWNER = f"{socket.gethostname()}:{os.getpid()}:{uuid.uuid4().hex[:8]}"
CELLS_PER_BEAT = 20
The lease is a sub-document on the run batch with four fields: owner, acquired_at, heartbeat_at and expires_at. An initial lease is written when the run is created as queued, so a process that dies between accepting a request and starting it still leaves something that can expire. start replaces the lease when the run moves to running.
| Setting | Default | What it controls |
|---|---|---|
RUN_LEASE_GRACE_SECONDS | 300 | how long a lease lives after its last heartbeat |
RUN_HEARTBEAT_SECONDS | 30 | interval of the periodic heartbeat |
RUN_MAX_SECONDS | 3600 | after this the keeper stops renewing, so a hung run expires too |
CELLS_PER_BEAT | 20 | extra heartbeat after this many saved cells |
Ten heartbeats fit inside one grace period. A single missed heartbeat, a slow database call or a long garbage-collection pause does not cost a run its lease.
Renewing the lease
heartbeat is a conditional update. It extends the lease only if the run is still running and still belongs to the caller.
async def heartbeat(batch_id: str, *, owner: str = OWNER) -> bool:
now = utc_now()
res = await _coll().update_one(
{"_id": batch_id, "status": "running", "lease.owner": owner},
{"$set": {"lease.heartbeat_at": now, "lease.expires_at": now + lease_grace()}},
)
return bool(res.matched_count)
A False return means the lease is gone: the reaper closed the run, or it ended some other way. LeaseKeeper wraps this in an async context manager. On entry it starts a loop that sleeps for the interval and beats. The pipeline also calls touch() after each saved cell, which beats every 20 cells or when the interval has passed, so a run that is busy writing keeps its lease even if the timer task is starved. If any beat returns False the keeper sets lost = True. After RUN_MAX_SECONDS the loop stops renewing on purpose. A run that hangs without crashing would otherwise hold its lease forever.
The reaper

The reaper runs once at startup and then every 60 seconds, in whichever process is alive. One pass does this:
- Find runs with an active status and
lease.expires_at < now. The indexbatch_lease_expiryon(status, lease.expires_at)serves the scan. - For each id, call
claim_interrupt. If it returns nothing, skip the run. - Tally the stored attempts and record the counts.
- Check whether a snapshot exists and settle: a full refund if nothing was measured, a proportional refund otherwise.
The claim is the whole safety argument, so here it is.
doc = await _coll().find_one_and_update(
{"_id": batch_id, "status": {"$in": list(ACTIVE_STATUSES)},
"lease.expires_at": {"$lt": now}},
{"$set": {"status": "interrupted", "finished_at": now, "error": reason},
"$push": {"timeline": {"at": now, "event": "interrupted", "reason": reason}}},
)
Three things follow from the filter. A live worker keeps pushing expires_at into the future, so its run never matches. Two reapers that scan at the same moment both try the update, and only one finds the document still active. A run that finished normally between the scan and the claim is no longer active, so the reaper leaves it alone. The claim comes before the refund, never after, which is why a refund can only follow a won claim.
There is no startup grace period and no bulk flip of running rows. Expiry is the only signal.
The worker that was only slow
A lease can expire while its worker is still alive, for example when the host is under memory pressure and the event loop stalls for minutes. The reaper then closes the run and refunds it, and a few seconds later the original task finishes its last calls and tries to write. Two gates stop it.
- Before the snapshot is written the pipeline calls
still_owned, which checks that the run is active and itslease.owneris this process. If not, the snapshot and the post-run hooks are skipped. finishcarries the same owner condition in its filter. It matches nothing and returnsFalse.
The EngineRun rows that the slow worker already inserted stay in the database as raw observations. They are not rolled up into a snapshot, so the customer never sees a result for a run they were refunded for.
Failure modes
| What goes wrong | What the system does | Regression test |
|---|---|---|
Process killed while running | Lease expires, reaper interrupts and refunds in full | test_reaper_interrupts_only_expired_and_refunds_in_full |
Process killed after accepting, before start | The initial lease on the queued row expires and is reaped the same way | test_queued_batch_whose_process_died_before_start_is_recovered |
| Two reapers claim the same run | One update matches, one refund is paid | test_two_reapers_race_one_wins_one_refund |
| Reaper sees a live run | The filter does not match, nothing is written | test_running_expired_lease_is_interrupted_live_one_is_not |
| A finished run still has an old lease | Terminal status is not active, the reaper ignores it | test_reaper_ignores_finished_batches_even_with_old_lease |
| Slow worker finishes after being interrupted | Snapshot discarded, one refund only | test_interrupted_run_discards_late_snapshot_and_refunds_once |
| Run interrupted after a snapshot was written | Proportional refund by the same rule as a normal finish | test_reaper_after_snapshot_uses_proportional_rule |
| A run hangs without crashing | The keeper stops renewing after the maximum runtime | test_lease_keeper_beats_periodically_and_stops_after_max_runtime |
| The refund itself fails | The run stays unsettled and a later pass settles it | test_reaper_resettles_interrupted_run_whose_refund_failed |
Limits I know about
The ownership check before the snapshot and the insert that follows are two operations, not one. A lease that expires in the instant between them could still let a snapshot through. The window is a few milliseconds against a 300-second grace period, and the consequence is a refunded run with a visible result, which costs the company and not the customer.
Lease times are compared with the application clock. That is sound on one host. On several hosts the comparison would have to use the database’s clock, or the grace period would have to absorb the worst clock skew.
Recovery is a refund, not a resume. An interrupted run’s saved cells could in principle be reused to finish the run in another process. I chose not to build that: a customer who is refunded and reruns loses a few minutes, while a resume path would need the fan-out to be restartable cell by cell.
