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

TermMeaning in the code
Run batchOne run. A RunBatch document in run_batches. Its id is also the reference for the charge and the refund.
CellOne combination of prompt, engine, market and repeat. The id is cell:{prompt_set_version}:{prompt_key}:{engine}:{market}:{context_version}:r{repeat}.
AttemptOne 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.
EngineRunOne 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

Three rows of five boxes. Accept: POST run, plan_batch, create_batch saving a queued RunBatch with a lease, charge with the batch id as reference or HTTP 402, then execute_batch as a background asyncio task. Fan out per market group: cells, a global semaphore of 8 calls, a per-engine semaphore of 4, the engine adapter making one paid call per attempt, and one EngineRun row per attempt. Persist and close: per-cell insert, LeaseKeeper.touch every 20 cells, mention extraction, a snapshot written only by the owner, then settle and finish as completed, partial or failed.
Figure 1. The three phases of a run. The request path ends once the run is saved and charged. Everything after that happens in a background task that must still own the run when it writes.

The order inside the request handler is deliberate:

  1. plan_batch builds the draft and the expected cell count.
  2. create_batch inserts the RunBatch with status queued and an initial lease.
  3. charge takes the credits, with the batch id as the reference.
  4. If the charge fails, discard_queued deletes the row and the API answers 402.
  5. Otherwise the handler starts execute_batch as 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

State diagram. Inside an Active zone, queued leads to running through start, and running loops on heartbeat. From running, finish leads to one of three terminal states: completed when no cell is refundable and none is pending, partial when some cells failed and results are kept, failed when every charged cell failed or the run raised. A dashed claim_interrupt transition leads from queued and from running to interrupted when the lease expired. A panel lists the filters: start requires status queued; heartbeat and finish require status running and lease.owner equal to this process; claim_interrupt requires an active status and an expired lease.
Figure 2. The run batch state machine. Orange transitions are made by the run's own worker, dashed grey ones by the reaper. The panel lists the filter each update must match.

Every transition is a query-level update with a filter. None of them loads the document, edits it in Python and saves it back.

TransitionFunctionThe filter it must match
new to queuedcreate_batchnone: an insert, refused by a unique index if the same request key or schedule claim exists
queued to deleteddiscard_queuedstatus = queued
queued to runningstartstatus = queued
running, lease extendedheartbeatstatus = running, lease.owner = me
running to completed, partial or failedfinishstatus = running, lease.owner = me
queued or running to interruptedclaim_interruptstatus 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 wrongWhat the system doesRegression test
Not enough creditscharge returns False, the queued row is deleted, the API answers 402test_charge_requires_sufficient_balance
The same request arrives twiceThe unique request-key index refuses the second insert and the first run is returnedtest_concurrent_same_key_creates_one_batch
start is called twiceThe second update matches nothingtest_duplicate_schedule_claim_and_double_start_are_rejected
Some cells errorpartial, with a proportional refundtest_queued_running_partial_with_proportional_refund
The pipeline raisesfailed, with a full refundtest_pipeline_exception_fails_batch_with_full_refund
Only skipped cells remainfailed, since nothing chargeable was measuredtest_only_region_skipped_cells_left_means_failed_run
Counting cells and attempts as oneThey are tallied separatelytest_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.