Sub topic 6
The life of a batch job: statuses and completion windows
This chapter covers what happens to a batch after you submit it. It explains each status, which statuses are final, what the completion window promises, and how to write polling code that handles every outcome. It assumes you can read and write JSONL request files and have made basic calls to a chat completions API. Examples use the OpenAI Batch API. Other providers use different status names but follow a similar pattern, which a later chapter compares.
A batch is a state machine
A synchronous call has two outcomes: you get a response or you get an error, usually within seconds. A batch job runs for minutes to hours and passes through several stages. The API reports the current stage in the batch object's status field.
Your code has to answer two questions about this field:
- Is the job still moving? If so, keep waiting.
- Has it reached a final state? If so, what do I collect, and what do I do about the requests that did not succeed?
The second question matters more than it first appears. A batch can end in expired or cancelled and still hold usable results.
The statuses
| Status | Meaning | Final? |
|---|---|---|
| `validating` | The input file is being checked for format and consistency before work starts. | No |
| `failed` | Validation rejected the whole file. No requests ran. | Yes |
| `in_progress` | The file passed validation and requests are being executed. | No |
| `finalizing` | Execution is done and the output and error files are being assembled. | No |
| `completed` | Every request has been processed. Result files are ready. | Yes |
| `expired` | The completion window ran out before every request finished. | Yes |
| `cancelling` | You asked to cancel. In-flight requests are being wound down. | No |
| `cancelled` | The cancellation finished. | Yes |
The statuses form a mostly one-way flow. This diagram shows the allowed transitions.
Four statuses are final: failed, completed, expired, and cancelled. Once a batch reaches one of them, it never changes again, so polling can stop. The non-final statuses are validating, in_progress, finalizing, and cancelling. A common mistake is to stop polling at finalizing, because the work looks finished. The output file does not exist until the batch is completed.
validating and failed
Validation happens after the batch is created, not when you upload the file. Creating the batch returns immediately with status validating, even if the file is malformed. Validation then checks things like:
- every line is valid JSON;
- every line has
custom_id,method,url, andbody; custom_idvalues are unique within the file;- every request targets the same endpoint, and it matches the
endpointyou passed when creating the batch; - the file stays under the size and request-count limits.
When validation fails, the batch goes to failed. The batch object's errors field then lists the problems, usually with a line number. This is a whole-job failure. Nothing ran, so nothing is billed. Fix the file and submit a new batch.
Do not confuse this with a per-request failure. A single request with a bad parameter, such as an invalid model name in the body, does not fail the batch. It shows up in the error file once the batch finishes, and the rest of the batch continues.
in_progress and finalizing
In in_progress the provider executes your requests at a time of its choosing, using spare capacity. You get no per-request progress events. The only progress signal is request_counts, which holds three numbers: total, completed, and failed. They update while the batch runs, so you can log progress. Here, completed means requests that returned a successful result, and failed means requests that errored. Together they should add up to total when the batch ends normally.
finalizing is short. The provider is writing the output and error files. Treat it as "almost done, keep polling."
completed
completed means the provider has processed every request, successfully or not. It does not mean every request succeeded. After completed, check request_counts.failed, then read both the output file and the error file. The next chapters cover reading them.
expired
Every batch has a completion window, set when you create it. The Batch API currently accepts a single value, "24h". The batch gets an expires_at timestamp 24 hours after creation. The window is a ceiling, not a typical duration. Many batches finish much sooner, but you cannot count on it.
If the window elapses with requests still unprocessed, the batch moves to expired. Requests that already finished are not lost. They are in the output file, and you pay for them. Requests that never ran are listed in the error file with an expiry error code, and you are not charged for them. Handle this like any partial failure: collect what exists, find what is missing, and resubmit only those requests.
cancelling and cancelled
You can call client.batches.cancel(batch_id) on a batch that is not yet final. The status moves to cancelling, and the job takes some time to stop, which can be several minutes. Requests already in flight may still complete. The final status is cancelled. As with expiry, partial results from requests that finished before cancellation are available, and you are billed for those.
Timestamps tell you what happened
The batch object carries a timestamp for each transition: created_at, in_progress_at, finalizing_at, completed_at, failed_at, expired_at, cancelling_at, cancelled_at, and expires_at. Fields for transitions that have not happened are None. These are Unix times in seconds.
They are useful for monitoring. The gap between created_at and in_progress_at shows queue and validation time. The gap between in_progress_at and finalizing_at shows how long execution took. Logging these over several runs shows you the real turnaround for your workload, which you need when you plan around the 24-hour ceiling.
Polling correctly
The polling loop from the spine is the minimum. A production version needs four more things:
- A wall-clock timeout, so a bug or an outage cannot hold your process forever.
- A poll interval that grows, so a long job does not generate thousands of retrieve calls.
- Logging of status changes and progress counts.
- Tolerance for transient network or API errors on the retrieve call. A failed poll does not mean a failed batch.
import time
from openai import OpenAI, APIConnectionError, APITimeoutError, RateLimitError
client = OpenAI()
TERMINAL = {"completed", "failed", "expired", "cancelled"}
def wait_for_batch(batch_id, max_wait_s=26 * 3600, first_interval_s=30, max_interval_s=600):
"""Poll a batch until it reaches a final status or the local timeout passes."""
start = time.monotonic()
interval = first_interval_s
last_seen = None
while True:
try:
batch = client.batches.retrieve(batch_id)
except (APIConnectionError, APITimeoutError, RateLimitError) as exc:
print(f"poll failed ({type(exc).__name__}), will retry")
batch = None
if batch is not None:
counts = batch.request_counts
snapshot = (batch.status, counts.completed, counts.failed)
if snapshot != last_seen:
print(
f"{batch.status}: {counts.completed}/{counts.total} done, "
f"{counts.failed} failed"
)
last_seen = snapshot
if batch.status in TERMINAL:
return batch
if time.monotonic() - start > max_wait_s:
raise TimeoutError(f"batch {batch_id} not final after {max_wait_s}s")
time.sleep(interval)
interval = min(interval * 2, max_interval)The timeout is set a little above 24 hours. The provider's expiry should always fire first and move the batch to expired, so your local timeout only matters if something is wrong with the polling itself.
Once the loop returns, branch on the status instead of assuming success:
batch = wait_for_batch("batch_abc123") # replace with your batch id
if batch.status == "failed":
# Whole-job rejection: nothing ran. Inspect the errors, fix the file, resubmit.
for err in (batch.errors.data if batch.errors else []):
print(f"line {err.line}: {err.code} - {err.message}")
elif batch.status in {"completed", "expired", "cancelled"}:
# Results may exist for all three. Collect them, then find what is missing.
print("output file:", batch.output_file_id)
print("error file:", batch.error_file_id)
print("counts:", batch.request_counts)Note that expired and cancelled go down the same path as completed. In all three cases you read whatever files exist and then compare results against your inputs by custom_id.
Common errors
- Treating
completedas "all succeeded." It means every request was processed. Checkrequest_counts.failedand read the error file. - Treating
expiredas total loss. Finished requests are in the output file and have been billed. Discarding them means paying twice when you rerun everything. - Reading
output_file_idtoo early. It isNoneuntil the batch is final. Even then it can beNoneif no request succeeded, so test it before downloading. - Polling too fast. A retrieve call every second for hours wastes quota and adds nothing, because the status changes at most a handful of times.
- Losing the batch ID. If your process dies after creating a batch, the job keeps running. Store the batch ID somewhere durable the moment
createreturns, so a restarted process can resume polling instead of submitting a duplicate. A later chapter builds this into a full pipeline. - Assuming the window is a deadline you can shorten. You cannot ask for a faster window. If you need an answer sooner, use synchronous calls.
Planning around the window
The 24-hour window affects how you schedule work. If a downstream step needs results by a fixed time, submit the batch at least 24 hours before that deadline, plus time to handle failures. A resubmission of the failed subset starts a new 24-hour window of its own. In the worst case, one retry cycle takes about 48 hours. For work with a tighter deadline, send the urgent portion through synchronous calls and the rest through batch.
Exercise
A batch you submitted shows status expired. request_counts reads total=1000, completed=940, failed=0. What do you do, and what are you billed for?
Show answer
Do not rerun the whole batch. Download the output file, which holds the 940 finished results, and key them by customid. Compare the set of input customids against the results to find the 60 requests that never ran. The error file lists them with an expiry code. Resubmit only those 60 in a new batch. You are billed for the 940 completed requests, not for the 60 that expired unprocessed.
Exercise
Your polling loop exits on any status other than validating and in_progress, and then downloads output_file_id. Name two ways this fails.
Show answer
First, finalizing and cancelling are also non-final, so the loop exits while output_file_id is still None, and the download call fails. Second, the loop treats failed like a normal result. A batch that failed validation has no output file and an errors field that explains why. A correct loop stops only on completed, failed, expired, or cancelled, and handles each.