A measurement run in TRAIL Search asks many questions of several AI answer engines, in several markets, several times each. Every one of those calls is paid for at an external provider before the customer sees a number. The run therefore has to exist in the database before the first call is made, and it has to end in a state that says exactly what was bought.
The problem
A run takes minutes. During those minutes the API process can be reloaded by a deploy, killed for memory, or crash. The customer was charged credits when the run was accepted. Three things can go wrong if the run lives only in memory:
- The process dies after the charge and nothing records that a run was ever accepted, so nothing knows a refund is owed.
- Most calls succeed and a few fail, and the whole run is thrown away although the provider was paid for the ones that worked.
- Two pieces of code both believe they are finishing the run and both write a result.
The fix for all three is the same: one document per run, saved first, changed only by updates that state what they expect to find.
Vocabulary
| Term | Meaning in the code |
|---|---|
| Run batch | One run. A RunBatch document in run_batches. Its id is also the reference for the charge and the refund. |
| Cell | One combination of prompt, engine, market and repeat. The id is cell:{prompt_set_version}:{prompt_key}:{engine}:{market}:{context_version}:r{repeat}. |
| Attempt | One real call for a cell. A transport retry after a 429 or 503 stays inside the same attempt. A retry after a truncated answer is a new attempt. |
EngineRun | One stored attempt. Older attempts point to their replacement through superseded_by, so the last attempt is the cell’s final result. |
plan_batch counts the cells a request will need before anything is saved, as prompts times engines times repeats, with prompts grouped by market.
Accept first, execute second

The order inside the request handler is deliberate:
plan_batchbuilds the draft and the expected cell count.create_batchinserts theRunBatchwith statusqueuedand an initial lease.chargetakes the credits, with the batch id as the reference.- If the charge fails,
discard_queueddeletes the row and the API answers 402. - Otherwise the handler starts
execute_batchas an asyncio task and returns the run id.
Saving before charging matters because of the crash between the two steps. If the charge came first and the process died, there would be a charge and no run. With the row saved first, the worst case is a queued row whose lease expires, which the reaper closes and refunds.
Six states

Every transition is a query-level update with a filter. None of them loads the document, edits it in Python and saves it back.
| Transition | Function | The filter it must match |
|---|---|---|
new to queued | create_batch | none: an insert, refused by a unique index if the same request key or schedule claim exists |
queued to deleted | discard_queued | status = queued |
queued to running | start | status = queued |
running, lease extended | heartbeat | status = running, lease.owner = me |
running to completed, partial or failed | finish | status = running, lease.owner = me |
queued or running to interrupted | claim_interrupt | status is active, lease.expires_at < now |
start is the shortest of them. Comments are translated from the original.
async def start(batch: RunBatch, *, owner: str = OWNER) -> bool:
"""queued -> running, with a lease. False if the run is already in another state."""
now = utc_now()
lease = _lease(owner, now)
res = await _coll().update_one(
{"_id": batch.id, "status": "queued"},
{"$set": {"status": "running", "lease": lease.model_dump()},
"$push": {"timeline": {"at": now, "event": "running", "owner": owner}}},
)
if not res.modified_count:
return False
A second start on the same run finds no document with status = queued and returns False. A finish from a worker that lost its lease finds no document with its owner id and writes nothing. The database arbitrates, so no lock is held in the application.
Deciding how the run ended
The terminal status is computed from the stored attempts, not from counters kept in memory. tally_runs looks at the final attempt of each cell and counts two numbers: charged_cells, the cells that reached a final state minus those skipped because the engine does not serve the market, and refundable, the final attempts whose status is error.
def outcome_status(t: Tally) -> str:
cells = t.counts.cells
if t.charged_cells <= 0 or t.refundable >= t.charged_cells:
return "failed"
if t.refundable == 0 and cells.pending == 0:
return "completed"
return "partial"
partial is the state that pays for itself. A run of 300 cells in which 30 failed keeps its 270 answers, reports them, and refunds the 30 in proportion, as cost * failed // terminal. Without that state the choices are to show a result with silent holes or to discard paid work.
The worker and the reaper call the same tally function, so a run closed by the reaper is counted by the same rule as a run that closed itself.
Fanning out
Cells of one market group run under asyncio.gather. Two semaphores bound the concurrency: a global one of 8 calls in flight and one per engine, 4 by default and lower for engines with tighter limits. The per-engine semaphores are shared across the whole process, so two runs at once cannot double an engine’s load. A call that waits for a transport retry releases both semaphores while it sleeps.
Market groups run one after another. After a group returns, the loop inserts each cell’s EngineRun rows and calls LeaseKeeper.touch, which sends a heartbeat every 20 cells. Mentions are extracted next. The ShareOfVoiceSnapshot is written last and only if this process still owns the run.
Failure modes
| What goes wrong | What the system does | Regression test |
|---|---|---|
| Not enough credits | charge returns False, the queued row is deleted, the API answers 402 | test_charge_requires_sufficient_balance |
| The same request arrives twice | The unique request-key index refuses the second insert and the first run is returned | test_concurrent_same_key_creates_one_batch |
start is called twice | The second update matches nothing | test_duplicate_schedule_claim_and_double_start_are_rejected |
| Some cells error | partial, with a proportional refund | test_queued_running_partial_with_proportional_refund |
| The pipeline raises | failed, with a full refund | test_pipeline_exception_fails_batch_with_full_refund |
| Only skipped cells remain | failed, since nothing chargeable was measured | test_only_region_skipped_cells_left_means_failed_run |
| Counting cells and attempts as one | They are tallied separately | test_tally_runs_counts_cells_and_attempts_separately |
Trade-offs I accepted
Cells are persisted after their market group returns, not as each call lands. A process killed in the middle of a group loses that group’s answers even though the provider was paid. I accepted this because recovery is a refund, not a resume: the customer is made whole, and writing every cell as it lands would put a database round trip inside the fan-out’s hot path.
Runs are asyncio tasks inside the API process. There is no queue and no separate worker fleet. On one host that removes a moving part, and the state machine is what makes it safe: any process can prove from the document alone whether a run is alive, who owns it and what it is owed.
Where to read next
- Leases, heartbeats and the reaper covers what happens to a run whose process dies.
- Exactly once covers scheduled runs, settlement and refunds.
- Data model lists the indexes this page relies on.
