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.

SettingDefaultWhat it controls
RUN_LEASE_GRACE_SECONDS300how long a lease lives after its last heartbeat
RUN_HEARTBEAT_SECONDS30interval of the periodic heartbeat
RUN_MAX_SECONDS3600after this the keeper stops renewing, so a hung run expires too
CELLS_PER_BEAT20extra 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

Sequence diagram with four lifelines: worker process A identified by host, pid and a random suffix; the run_batches collection in MongoDB; the run reaper that runs every 60 seconds in any process; and the credit ledger. Step 1, the worker starts the run, status queued to running. Step 2, heartbeat sets expires_at to now plus 300 seconds. A note marks the process being killed by reload, crash or out-of-memory so heartbeats stop. Step 3, the reaper scans for active runs whose lease expired. Step 4, claim_interrupt moves the run to interrupted. Step 5, settle_run refunds once. Below a divider for the case where process A was only slow, step 6 shows its finish update missing its filter and writing nothing.
Figure 1. A worker is killed mid-run. Its lease stops moving, the reaper claims the run with one conditional update and refunds it. If the worker was only slow, its late finish matches nothing.

The reaper runs once at startup and then every 60 seconds, in whichever process is alive. One pass does this:

  1. Find runs with an active status and lease.expires_at < now. The index batch_lease_expiry on (status, lease.expires_at) serves the scan.
  2. For each id, call claim_interrupt. If it returns nothing, skip the run.
  3. Tally the stored attempts and record the counts.
  4. 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 its lease.owner is this process. If not, the snapshot and the post-run hooks are skipped.
  • finish carries the same owner condition in its filter. It matches nothing and returns False.

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 wrongWhat the system doesRegression test
Process killed while runningLease expires, reaper interrupts and refunds in fulltest_reaper_interrupts_only_expired_and_refunds_in_full
Process killed after accepting, before startThe initial lease on the queued row expires and is reaped the same waytest_queued_batch_whose_process_died_before_start_is_recovered
Two reapers claim the same runOne update matches, one refund is paidtest_two_reapers_race_one_wins_one_refund
Reaper sees a live runThe filter does not match, nothing is writtentest_running_expired_lease_is_interrupted_live_one_is_not
A finished run still has an old leaseTerminal status is not active, the reaper ignores ittest_reaper_ignores_finished_batches_even_with_old_lease
Slow worker finishes after being interruptedSnapshot discarded, one refund onlytest_interrupted_run_discards_late_snapshot_and_refunds_once
Run interrupted after a snapshot was writtenProportional refund by the same rule as a normal finishtest_reaper_after_snapshot_uses_proportional_rule
A run hangs without crashingThe keeper stops renewing after the maximum runtimetest_lease_keeper_beats_periodically_and_stops_after_max_runtime
The refund itself failsThe run stays unsettled and a later pass settles ittest_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.