Sub topic 9
Resubmitting Only What Failed
A large batch rarely finishes with every request succeeding. This chapter shows how to find the requests that did not produce a usable answer, decide which of them are worth retrying, and submit a second batch that contains only those. It assumes you can already build a JSONL request file, submit and poll a batch, and read the output and error files by custom_id, as covered in the earlier chapters.
Why partial failure is normal
A batch job has a status for the whole job, but each request inside it succeeds or fails on its own. A batch that ends as completed can still hold hundreds of failed lines. A batch that ends as expired can hold thousands of good ones.
Resending the whole input after a partial failure has two costs:
- You pay again for requests that already succeeded.
- You may overwrite good results with new ones that differ, because model output is not deterministic.
The goal is to find the exact set of inputs that still lack a good result, and submit only those.
Three kinds of failure
Every input ends up in one of four states once a batch reaches a terminal status.
| State | Where it shows up | Typical cause | Retry? |
|---|---|---|---|
| Succeeded | Output file, status code 200 | Normal case | No |
| Failed in the output file | Output file, non-200 status code or an `error` value | Rate limit, server error, bad request | Depends on the cause |
| Failed in the error file | Error file | Request rejected or never run, such as an expired batch | Depends on the cause |
| Missing | Neither file | Cancelled job, or a gap between the two files | Yes |
The missing state matters because a loop over the output file only sees what is there. You find missing requests by comparing the set of IDs you sent against the set of IDs you got back. Never compare counts alone. A count tells you something is wrong but not which inputs are affected.
Retryable and permanent errors
Resubmitting a request that failed for a permanent reason wastes money and gives the same failure. Sort the failures into two groups first.
- Retryable (transient): the request was valid, but the system could not process it. Examples are HTTP 429 (rate or quota pressure), 500 and 503 (server trouble), and requests that were never run because the batch hit its completion window.
- Permanent: the request itself is wrong. Examples are HTTP 400 for a malformed body, an unknown model name, or an input longer than the context window. A retry with the same body fails again.
Permanent failures need a fix to the input or the code. Collect them in a separate list and report them. Do not loop them back into the pipeline automatically.
The exact error codes differ by provider and change over time. The sets in the code below are a starting point. Check them against the error records from your own pilot batch.
Computing the retry set
This function reads both files, keys everything by custom_id, and returns four groups. It builds on the parsing from the previous chapter, with the classification added.
import json
RETRYABLE_STATUS = {408, 409, 429, 500, 502, 503, 504}
RETRYABLE_CODES = {"batch_expired", "rate_limit_exceeded", "server_error"}
def read_jsonl(client, file_id):
if not file_id:
return []
text = client.files.content(file_id).text
return [json.loads(line) for line in text.splitlines() if line.strip()]
def classify(client, batch, documents):
results = {}
retryable = {}
permanent = {}
records = read_jsonl(client, batch.output_file_id)
records += read_jsonl(client, batch.error_file_id)
for record in records:
custom_id = record["custom_id"]
error = record.get("error")
response = record.get("response")
status = response["status_code"] if response else None
if error is None and status == 200:
body = response["body"]
results[custom_id] = body["choices"][0]["message"]["content"]
continue
code = error.get("code") if error else None
if status in RETRYABLE_STATUS or code in RETRYABLE_CODES:
retryable[custom_id] = error or response
else:
permanent[custom_id] = error or response
seen = set(results) | set(retryable) | set(permanent)
missing = set(documents) - seen
for custom_id in missing:
retryable[custom_id] = {"code": "missing"}
return results, retryable, permanentMissing requests are folded into the retryable group. A request with no record at all was most likely never run, so there is no evidence the input is bad.
One edge case: a custom_id could appear in both files, or twice in one file. The dictionary assignments above let a later record replace an earlier one, which could replace a success with a failure. If you want to be strict, check custom_id not in results before writing to retryable or permanent. A success should always win.
Building the retry file
The retry file has the same format as the original. You regenerate each line from your source data, not by copying lines out of the old file. That keeps one function responsible for the request body, so a retry uses the same prompt and model as the first attempt.
def build_request(custom_id, text):
return {
"custom_id": custom_id,
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "Summarize the text in one sentence."},
{"role": "user", "content": text},
],
"max_tokens": 100,
},
}
def write_batch_file(path, documents, ids):
with open(path, "w", encoding="utf-8") as f:
for custom_id in sorted(ids):
request = build_request(custom_id, documents[custom_id])
f.write(json.dumps(request) + "\n")The retry batch reuses the original custom_id values. IDs only need to be unique inside one batch file, and reusing them lets you merge results into one dictionary with no translation step. Your results store then holds one answer per input, no matter how many attempts it took.
If your provider or your own storage requires IDs to be unique across batches, append an attempt suffix such as doc-001#2 and strip it when merging. Pick one scheme and stay with it.
Submitting the retry batch
Submission is the same as before. Here it is wrapped in a helper so the retry loop can call it.
import time
from openai import OpenAI
client = OpenAI()
TERMINAL = {"completed", "failed", "expired", "cancelled"}
def run_batch(path):
uploaded = client.files.create(file=open(path, "rb"), purpose="batch")
batch = client.batches.create(
input_file_id=uploaded.id,
endpoint="/v1/chat/completions",
completion_window="24h",
)
while batch.status not in TERMINAL:
time.sleep(60)
batch = client.batches.retrieve(batch.id)
return batchA bounded retry loop
Put a ceiling on the number of rounds. A request that is retryable in theory can still fail every time in practice, for example when it consistently trips a rate limit.
MAX_ATTEMPTS = 3
def process(documents):
all_results = {}
all_permanent = {}
pending = set(documents)
for attempt in range(1, MAX_ATTEMPTS + 1):
if not pending:
break
path = f"batch_input_attempt{attempt}.jsonl"
write_batch_file(path, documents, pending)
batch = run_batch(path)
print(f"attempt {attempt}: {batch.status}, {len(pending)} requests sent")
remaining = {cid: documents[cid] for cid in pending}
results, retryable, permanent = classify(client, batch, remaining)
all_results.update(results)
all_permanent.update(permanent)
pending = set(retryable)
return all_results, all_permanent, pendingThe function returns three things: answers, permanent failures, and IDs still pending after the last attempt. Pass remaining, not the full documents, to classify. Otherwise every input from earlier rounds would look missing.
Practical notes
Partial success on expired batches
When a batch passes its completion window, the requests that finished are still delivered. The rest are reported as expired. This is the most common reason to retry a large block of requests at once. Classify the batch's files even when the status is expired. Do not discard the batch on status alone.
Retrying a batch that is `failed`
A failed status usually means the whole file was rejected during validation, for instance because of a bad line, a duplicate custom_id, or a size limit. No requests ran. Fix the file, then submit it as a new batch. This is a different case from per-request failure, and classify will report every input as missing.
Cost
You are normally billed for requests that completed, and not for those that did not run. Check your provider's rules for failed requests. Either way, a retry round costs only the retry set, which is why the filtering is worth the code.
Cap the blast radius
If more than a small share of requests fail on the first pass, stop and look at the errors before retrying. A rate-limit wave at 3% is routine. A 60% failure rate usually means a systematic problem such as a wrong model name or a quota ceiling. Retrying blindly spends money and can make queue pressure worse.
Keep a record
Write each attempt's batch ID, the number of requests sent, and the counts per state to a log or a small file. When a pipeline is rerun after a crash, that record tells you which batches are in flight so you do not submit the same work twice. The last chapter of this tutorial builds on that idea.
Exercise
A batch of 5,000 requests ends with status completed. The output file has 4,820 successful lines and the error file has 150 lines with a 400 error about an invalid parameter. List the IDs that you would resubmit automatically and explain how you would find them.
Show answer
Compute the set of IDs you sent minus the set of IDs in the success results. That leaves 180 IDs. The 150 IDs in the error file with a 400 are permanent failures, so you do not resubmit them automatically. You fix the input or the request code first. The remaining 30 IDs appear in neither file, so they are missing and are worth retrying. You find them by set difference on custom_id, not by comparing line counts.
Exercise
Why does the retry loop pass only the pending documents to classify and not the full document set?
Show answer
classify marks every ID that is in its input but absent from both files as missing. If you passed the full set, every input that succeeded in an earlier round would be absent from the current batch's files and would be treated as missing and queued for retry again. Passing only the pending subset limits the comparison to the requests sent in this round.