To retry expired OpenAI Batch API requests, join the saved request, output, and error JSONL by custom_id. Build a local retry manifest from original rows with explicit batch_expired errors after every input ID has exactly one recorded outcome. Missing artifacts or conflicting rows block the manifest before submission.

On the synthetic Batch below, the original input has five requests. Three have HTTP 200 results, one has an explicit expiration, and one has another error. The CLI emitted just b. OpenAI documents that completed responses remain available when a Batch expires and that tokens consumed by completed requests are charged. Replaying the whole input would include the three completed requests in this fixture. The fixture measures row selection. Billing details come from the provider's documentation. OpenAI Batch expiration

Then I removed the error file while leaving its file ID in the saved Batch. The CLI still read the three completions. It exited with code 2, reported two unknown input outcomes, and wrote zero bytes to stdout. An absent local artifact is enough to make a perfectly plausible retry list unsafe to use.

AI disclosure. This article and tool were produced fully autonomously with AI. The terminal output comes from local runs on Python 3.11.9 on December 2, 2026. The Batch, request bodies, responses, and errors are synthetic. The demo uses Python's standard library and local files.

How do you make the OpenAI Batch API retry expired requests?

Treat expired as a job-level status and batch_expired as evidence about a particular request. OpenAI documents that result order can differ from input order. The useful thing to bring back from the error file is the request's custom_id. The original input already has the correct method, URL, and body to put into the manifest. OpenAI Batch guide

I want an unambiguous answer for every ID before I hand a file to the next stage. This CLI counts an output row as completed when it has a valid HTTP 2xx envelope and an object in response.body. An error row with a null response and the exact code batch_expired is eligible when the job status is expired. An error row with another code, or a properly wrapped HTTP client or server failure, accounts for its ID and stays out of the manifest. You can handle those failures under your existing policy for rate limits, invalid input, or other errors.

The fixture makes the distinction easy to check by eye. The input is a, b, c, d, e. The output starts with e, then comes a, then c. The first error belongs to d. Joining by position would cross both lists with the wrong source rows. Joining by ID leaves d held and lets the explicit error for b select the original line for b.

Alexey Spinov, author of the archive's cost-per-verified-success tool, writes, “A witness has to be concrete or it is just vibes with a checkmark.” Here the witness is the error row for a specific request. Your eval pipeline still has to check whether an HTTP success met the task's requirements before counting it as useful work. Cost Per Verified Success

Why block when an expired ID is already visible?

I started with a missing error file. That was the easy test. In a second run, I dropped a complete JSONL row from the output and kept the error file intact. The parser still read the expiration for b. It also had an input with no outcome. That combination is why eligibility and emission need separate steps. By the time the code sees b, it has enough evidence to label b but still needs to establish coverage of the saved input.

There is a different way to get an empty file. Change the job to completed, replace the expiration with a properly formed non-expiration error, and reconcile the full input again. That exits successfully with an empty manifest. The shell can leave a zero-byte file for either outcome, so a job that decides what to do next needs the exit status as well as the file size.

The Batch JSON comes from Retrieve Batch. Its file IDs tell you which artifacts to fetch. Save the original input and the output and error files associated with those IDs alongside that Batch object. Pass each result-file path when its ID is set. With an absent or null ID, leave that flag out and expect the other artifact to account for the input. batch.errors.data can explain a Batch-level validation problem, sometimes with a line number. The manifest requires an error-file record tied to a request ID. Likewise, expires_at tells you about a time boundary, while the error row tells you what happened to an individual request. Retrieve Batch reference

How do you build a Batch retry manifest locally?

Start in an empty directory. Save the next Python block as batch_retry_manifest.py and the fixture block after it as make_fixture.py. The only inputs the CLI opens are the file paths you pass. It builds the manifest in memory before it writes to stdout, so a parse failure near the end of the error file can still withhold a candidate from the start of that file.

import argparse import json import sys from pathlib import Path ENDPOINT = "/v1/responses" def require(condition, reason): if not condition: raise ValueError(reason) def identifier(value): return isinstance(value, str) and bool(value.strip()) def unique_object(pairs): obj = {} for key, value in pairs: require(key not in obj, "duplicate JSON member") obj[key] = value return obj def reject_constant(_value): raise ValueError("non-JSON constant") def load_object(raw, where): try: obj = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object, parse_constant=reject_constant) require(isinstance(obj, dict), "expected a JSON object") except (ValueError, RecursionError) as exc: raise ValueError(f"{where}: invalid JSON object") from exc return obj def read_batch(path): try: return load_object(path.read_bytes(), "batch") except OSError as exc: raise ValueError("batch: cannot read file") from exc def read_rows(path, kind): try: with path.open("rb") as file: for number, raw in enumerate(file, 1): where = f"{kind}:{number}" if raw.endswith(b"\n"): raw = raw[:-1] if raw.endswith(b"\r"): raw = raw[:-1] yield where, raw, load_object(raw, where) except OSError as exc: raise ValueError(f"{kind}: cannot read file") from exc def outcome(row, kind, status, where): require(identifier(row.get("id")) and "response" in row and "error" in row, f"{where}: incomplete result envelope") response, error = row["response"], row["error"] if kind == "errors" and response is None and isinstance(error, dict): code = error.get("code") require(identifier(code) and isinstance(error.get("message"), str), f"{where}: invalid error object") if code == "batch_expired": require(status == "expired", f"{where}: batch_expired in completed batch") return "expired" return "held" require(error is None and isinstance(response, dict) and identifier(response.get("request_id")) and "body" in response, f"{where}: invalid response envelope") http = response.get("status_code") low, high = (200, 299) if kind == "output" else (400, 599) require(type(http) is int and low <= http <= high, f"{where}: HTTP status conflicts with artifact") if kind == "output": require(isinstance(response["body"], dict), f"{where}: invalid successful Responses body") return "completed" return "held" def reconcile(args, stats): batch = read_batch(args.batch) require(batch.get("object") == "batch" and identifier(batch.get("id")) and identifier(batch.get("input_file_id")), "batch: invalid identity") require(batch.get("endpoint") == ENDPOINT and batch.get("completion_window") == "24h", "batch: unsupported endpoint or completion window") status = batch.get("status") require(status in ("expired", "completed"), "batch: unsupported status") original = {} for where, raw, row in read_rows(args.input, "input"): key = row.get("custom_id") require(identifier(key) and row.get("method") == "POST" and row.get("url") == ENDPOINT and isinstance(row.get("body"), dict), f"{where}: invalid request envelope") require(key not in original, f"{where}: duplicate input custom_id") original[key] = raw require(original, "input: empty") stats["unknown"] = len(original) counts = batch.get("request_counts", {}) require(isinstance(counts, dict), "batch: invalid request_counts") for field in ("total", "completed", "failed"): if field in counts: require(type(counts[field]) is int and 0 <= counts[field] <= len(original), f"batch: invalid request_counts.{field}") require(counts.get("total", len(original)) == len(original), "batch: request_counts.total disagrees with input") file_ids = {batch["input_file_id"]} artifacts = (("output", "output_file_id", args.output), ("errors", "error_file_id", args.errors)) seen = {} for kind, field, path in artifacts: file_id = batch.get(field) require(file_id is None or identifier(file_id), f"batch: invalid {field}") require((file_id is None) == (path is None), f"{kind}: path and {field} must both be set or both absent") if path is None: continue require(file_id not in file_ids, f"batch: reused {field}") file_ids.add(file_id) for where, _, row in read_rows(path, kind): key = row.get("custom_id") require(identifier(key) and key in original, f"{where}: unknown custom_id") require(key not in seen, f"{where}: repeated result custom_id") label = outcome(row, kind, status, where) seen[key] = label stats[label] += 1 stats["unknown"] -= 1 require(stats["unknown"] == 0, "incomplete coverage") require(counts.get("completed", stats["completed"]) == stats["completed"], "batch: request_counts.completed disagrees with output") # The reference leaves the inclusion of expired rows in failed unspecified. failed = counts.get("failed", stats["held"]) require(failed in (stats["held"], stats["held"] + stats["expired"]), "batch: request_counts.failed disagrees with errors") return b"".join(raw + b"\n" for key, raw in original.items() if seen[key] == "expired") def main(): parser = argparse.ArgumentParser(description="Build an offline Batch retry manifest.") for flag in ("batch", "input", "output", "errors"): parser.add_argument(f"--{flag}", type=Path, required=flag in ("batch", "input")) args = parser.parse_args() stats = {"completed": 0, "expired": 0, "held": 0, "unknown": "unavailable"} try: manifest = reconcile(args, stats) except ValueError as exc: verdict, rc = f"BLOCKED reason={exc}", 2 else: sys.stdout.buffer.write(manifest) sys.stdout.buffer.flush() verdict, rc = "OK", 0 summary = " ".join(f"{name}={value}" for name, value in stats.items()) emitted = stats["expired"] if rc == 0 else 0 print(f"{verdict} | {summary} emitted={emitted}", file=sys.stderr) return rc if __name__ == "__main__": raise SystemExit(main()) 

The fixture generator writes an expired Responses Batch with reordered output and mixed outcomes. The sample model and prompt strings are just payload fields that make it possible to check that the manifest contains the original request. You'll see them once more in retry.jsonl.

import json from pathlib import Path root = Path("fixtures") root.mkdir(exist_ok=True) def write(name, rows): (root / name).write_bytes(b"".join(json.dumps(row).encode() + b"\n" for row in rows)) def success(key): return {"id": f"synthetic_{key}", "custom_id": key, "error": None, "response": {"status_code": 200, "request_id": f"synthetic_http_{key}", "body": {"synthetic": True}}} def error(key, code): return {"id": f"synthetic_{key}", "custom_id": key, "response": None, "error": {"code": code, "message": "Synthetic error"}} write("batch.json", [{"object": "batch", "id": "batch_synthetic", "input_file_id": "file_input_synthetic", "endpoint": "/v1/responses", "completion_window": "24h", "status": "expired", "output_file_id": "file_output_synthetic", "error_file_id": "file_errors_synthetic", "request_counts": {"total": 5, "completed": 3, "failed": 2}}]) write("input.jsonl", [{"custom_id": key, "method": "POST", "url": "/v1/responses", "body": {"model": "gpt-4.1-mini", "input": f"Synthetic item {key}"}} for key in "abcde"]) write("output.jsonl", [success(key) for key in "eac"]) write("error.jsonl", [error("d", "synthetic_other"), error("b", "batch_expired")]) 

Run the generator and the CLI. The exit code in the transcript is captured immediately after Python finishes. The redirect keeps the diagnostics on the terminal and sends just the request rows into the manifest.

python3 make_fixture.py python3 batch_retry_manifest.py --batch fixtures/batch.json --input fixtures/input.jsonl \ --output fixtures/output.jsonl --errors fixtures/error.jsonl > retry.jsonl printf 'exit=%s\n' "$?" cat retry.jsonl 
OK | completed=3 expired=1 held=1 unknown=0 emitted=1 exit=0 {"custom_id": "b", "method": "POST", "url": "/v1/responses", "body": {"model": "gpt-4.1-mini", "input": "Synthetic item b"}} 

Now point the same command at a missing error path. Keep batch.json and its reference to the error file intact. This reproduces a download gap with the same logical inputs as the missing-file case in the run.

python3 batch_retry_manifest.py --batch fixtures/batch.json --input fixtures/input.jsonl \ --output fixtures/output.jsonl --errors fixtures/missing-error.jsonl > blocked.jsonl printf 'exit=%s\n' "$?" wc -c < blocked.jsonl 

The missing-file stderr from the synthetic run was

BLOCKED reason=errors: cannot read file | completed=3 expired=0 held=0 unknown=2 emitted=0 

That case exited with code 2 and wrote zero stdout bytes. Here unknown counts original IDs whose outcomes t...