A batch classified 8,000 support tickets overnight. Some requests expired, output lines arrived in a different order, and one downloaded file appears twice. Rerunning the input file wastes successful work and can publish a second classification for the same ticket. Recover the individual requests from evidence instead.
This guide produces three sets: accepted results, candidates for another attempt, and held work needing investigation. The Python fixture runs offline without a provider account. It tests the recovery decision, not provider execution, billing, or a production database transaction.
Freeze the job and collect both result files
Keep an immutable manifest with a unique logical work key, request ID, input digest, model and prompt version. Maintain a durable attempt ledger linking each submitted provider batch ID and request ID back to that work key. A changed input, model or prompt is new work; do not overwrite an old attempt's identity.
For OpenAI Batch, each input request has a unique custom_id. The Batch guide documents unordered output and separate output/error files. Expired batches can still contain completed responses. Read both files after the job reaches a terminal state, preserve their IDs and checksums, and reconcile their counts with the provider's batch metadata. A terminal batch status does not establish that each individual response satisfies your application.
While a batch is validating, running or finalizing, poll its existing ID. Do not submit the same manifest again because a network request timed out. A lost submission acknowledgement needs lookup or manual reconciliation before a new submission; this fixture cannot discover an unknown remote job.
Use this recovery contract
For this ticket classifier, an accepted response must be HTTP 200, have Responses API status completed, and contain one JSON text message with exactly one label: billing, technical, or other. Other applications should supply their own business validator. Schema-valid JSON alone does not prove a classification is correct.
Apply these rules in order:
- Reject duplicate manifest IDs and unknown result IDs before planning any work. They indicate a broken join or mixed files.
- Hold every repeated result ID, including identical duplicates. Inspect whether the downloader repeated a file or two attempts were combined; never let “last row wins” decide.
- Accept a unique valid success. Hold malformed successes, refusals, incomplete generation and unexpected response shapes.
- Retry only explicitly classified transient outcomes after terminal reconciliation. Here those are HTTP 429, HTTP 5xx and
batch_expired. A missing line is held until download completeness is resolved. - Cap total submitted attempts at three per work key, including the first. Count durable submissions, not the number of times the recovery script ran. Use a deadline, spend ceiling and delayed backoff with jitter before actually submitting another batch.
Run the offline fixture
Save this block as recover_batch.py and run python recover_batch.py with Python 3.10 or newer. The sample rows follow the relevant Batch response envelope; IDs and ticket outcomes are synthetic.
import copy
import json
from collections import defaultdict
TERMINAL = {"completed", "expired", "failed", "cancelled"}
LABELS = {"billing", "technical", "other"}
def valid_label(body):
if not isinstance(body, dict) or body.get("status") != "completed":
return False
output = body.get("output")
if not isinstance(output, list) or len(output) != 1:
return False
message = output[0]
if not isinstance(message, dict) or message.get("type") != "message":
return False
content = message.get("content")
if not isinstance(content, list) or len(content) != 1:
return False
part = content[0]
if not isinstance(part, dict) or part.get("type") != "output_text":
return False
try:
value = json.loads(part["text"])
except (KeyError, TypeError, ValueError):
return False
return (isinstance(value, dict) and set(value) == {"label"}
and isinstance(value["label"], str)
and value["label"] in LABELS)
def reconcile(manifest, rows, attempts, batch_status, max_attempts=3):
if batch_status not in TERMINAL:
raise ValueError("Poll the existing batch before reconciliation")
if len(set(manifest)) != len(manifest):
raise ValueError("Duplicate manifest ID")
if set(attempts) != set(manifest) or any(
type(n) is not int or n < 1 for n in attempts.values()
):
raise ValueError("Supply the persisted submitted-attempt count")
if type(max_attempts) is not int or max_attempts < 1:
raise ValueError("Invalid attempt limit")
grouped = defaultdict(list)
for row in rows:
if not isinstance(row, dict) or row.get("custom_id") not in attempts:
raise ValueError("Unknown or malformed result ID")
grouped[row["custom_id"]].append(row)
accepted, retry, held = [], [], {}
for key in manifest:
matches = grouped[key]
if len(matches) != 1:
held[key] = "missing" if not matches else "duplicate"
continue
row = matches[0]
response, error = row.get("response"), row.get("error")
if response is not None and error is not None:
held[key] = "ambiguous envelope"
continue
if isinstance(response, dict):
code = response.get("status_code")
if type(code) is not int:
held[key] = "invalid HTTP status"
continue
if code == 200 and valid_label(response.get("body")):
accepted.append(key)
continue
transient = code == 429 or 500 <= code <= 599
else:
transient = (response is None and isinstance(error, dict)
and error.get("code") == "batch_expired")
if transient and attempts[key] < max_attempts:
retry.append(key)
else:
held[key] = "budget exhausted" if transient else "inspect outcome"
return {"accepted": accepted, "retry": retry, "held": held}
def success(key, label="billing"):
return {"custom_id": key, "error": None, "response": {
"status_code": 200, "body": {"status": "completed", "output": [{
"type": "message", "content": [{"type": "output_text",
"text": json.dumps({"label": label})}]}]}}}
manifest = ["ticket-a", "ticket-b", "ticket-c", "ticket-d", "ticket-e"]
attempts = dict.fromkeys(manifest, 1)
rows = [success("ticket-c"), success("ticket-a"),
{"custom_id": "ticket-b", "response": None,
"error": {"code": "batch_expired"}},
success("ticket-c"), success("ticket-e", "not-a-label")]
plan = reconcile(manifest, rows, attempts, "expired")
assert plan == {"accepted": ["ticket-a"], "retry": ["ticket-b"],
"held": {"ticket-c": "duplicate", "ticket-d": "missing",
"ticket-e": "inspect outcome"}}
assert reconcile(manifest, list(reversed(rows)), attempts, "expired") == plan
assert reconcile(["ticket-b"], [rows[2]], {"ticket-b": 3}, "expired")["retry"] == []
for status in [429, 503]:
row = {"custom_id": "ticket-a", "response": {"status_code": status}}
assert reconcile(["ticket-a"], [row], {"ticket-a": 1}, "completed")["retry"] == ["ticket-a"]
for status in [400, 401]:
row = {"custom_id": "ticket-a", "response": {"status_code": status}}
assert not reconcile(["ticket-a"], [row], {"ticket-a": 1}, "completed")["retry"]
bad = copy.deepcopy(success("ticket-a"))
bad["response"]["body"]["status"] = "incomplete"
assert not reconcile(["ticket-a"], [bad], {"ticket-a": 1}, "completed")["accepted"]
for keys, results, counts, state in [
(["ticket-a"], [success("unknown")], {"ticket-a": 1}, "completed"),
(["ticket-a", "ticket-a"], [], {"ticket-a": 1}, "completed"),
(["ticket-a"], [], {"ticket-a": 1}, "in_progress"),
]:
try:
reconcile(keys, results, counts, state)
except ValueError:
pass
else:
raise AssertionError("Unsafe input should stop planning")
print(json.dumps(plan, indent=2))
print("PASS: order, duplicates, missing results, validation and bounded retries")
Only ticket-b is eligible for another attempt. ticket-c remains held even though both duplicate lines look successful. ticket-d is absent, so investigate the files before treating it as an expired request. ticket-e contains valid JSON but violates the label contract. The reversed-file assertion catches accidental dependence on row order.
Submit the retry plan and publish once
Before submission, join retry IDs back to the immutable request manifest; reconstruct only those requests. Reserve their next attempt numbers atomically in the durable ledger and record the submitted batch ID. A new attempt gets its own provider request ID linked to the same work key. After a crash, recover that reservation and remote job before creating another one. For cancellation, first confirm the operator actually wants work resumed.
Persist accepted outputs under a database uniqueness constraint on logical work key plus input/model/prompt version. In one transaction, record the accepted attempt and enqueue downstream effects with a stable deduplication key. Replaying the same completed files must leave the accepted count and downstream queue unchanged. That is an application guarantee to implement and test; provider request IDs alone do not provide it.
Verify this release with a disposable database: ingest a shuffled result file twice, repeat after a simulated crash, and confirm one accepted classification and one downstream event per work key. Inject a competing worker and confirm the uniqueness constraint still holds. Keep held rows visible with a reason, owner and next action. Close the batch only when every manifest ID has a terminal application disposition and recorded cost remains within the agreed ceiling.
Sources and scope
Reviewed November 10, 2026 against OpenAI Batch and Python's JSON parser. The join rules, three-attempt example, classifier validator and persistence design are Ryan VerWey's worked application guidance. Provider completion windows, endpoint/model support and billing rules must be checked for the actual job; other providers use different result envelopes.
