Sub topic 13
Designing a restartable, idempotent pipeline
This chapter assumes you can already build a JSONL request file, submit a batch, poll it, and read the output and error files. It also assumes you know the custom_id pattern from earlier chapters. Here you combine those pieces into a script that you can kill and rerun at any point without losing work or paying twice.
What the pipeline must survive
A batch job can take up to 24 hours. Over that time your process may crash, your laptop may sleep, and some requests will fail. Two properties handle all of this:
- Restartable: the script records its progress on disk, so a rerun resumes instead of starting over.
- Idempotent: running the script twice produces the same results as running it once. It does not submit duplicate work.
Principles
- Derive
custom_idfrom the content. Hash the input text plus a prompt version. The same input always gets the same ID, so you can tell what is already done. If you change the prompt, bump the version and every ID changes, which correctly marks old results as stale. - Treat the results file as the source of truth. A request is done only when a successful result is stored under its ID.
- Record the batch ID before you wait. If you crash after
batches.createbut before saving the ID, you will pay for a job you cannot find. - Compute pending work from state, not from memory. Pending means not done and not already in an uncollected batch.
- Make retries the same code path as the first run. A failed request is simply still pending on the next pass.
A working skeleton
This version keeps a state.json file that maps batch IDs to their request IDs, and an append-only results.jsonl.
import hashlib
import json
import os
import time
from pathlib import Path
from openai import OpenAI
client = OpenAI()
PROMPT_VERSION = "v1"
CHUNK_SIZE = 5000
STATE = Path("state.json")
RESULTS = Path("results.jsonl")
TERMINAL = {"completed", "failed", "expired", "cancelled"}
def make_id(text):
return hashlib.sha256(f"{PROMPT_VERSION}:{text}".encode()).hexdigest()[:16]
def load_state():
return json.loads(STATE.read_text()) if STATE.exists() else {"batches": {}}
def save_state(state):
tmp = STATE.with_suffix(".tmp")
tmp.write_text(json.dumps(state))
os.replace(tmp, STATE) # atomic: no half-written state file
def done_ids():
if not RESULTS.exists():
return set()
return {json.loads(line)["custom_id"] for line in RESULTS.read_text().splitlines() if line}
def submit_chunk(chunk, state):
path = Path(f"chunk_{next(iter(chunk))}.jsonl")
with open(path, "w", encoding="utf-8") as f:
for cid, text in chunk.items():
f.write(json.dumps({
"custom_id": cid,
"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,
},
}) + "\n")
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",
)
state["batches"][batch.id] = {"ids": list(chunk), "collected": False}
save_state(state) # saved immediately, before any waiting
def collect(batch_id, state):
batch = client.batches.retrieve(batch_id)
while batch.status not in TERMINAL:
time.sleep(60)
batch = client.batches.retrieve(batch_id)
if batch.output_file_id:
text = client.files.content(batch.output_file_id).text
with open(RESULTS, "a", encoding="utf-8") as out:
for line in text.splitlines():
rec = json.loads(line)
resp = rec.get("response")
if rec.get("error") is None and resp and resp["status_code"] == 200:
content = resp["body"]["choices"][0]["message"]["content"]
out.write(json.dumps({"custom_id": rec["custom_id"], "content": content}) + "\n")
state["batches"][batch_id]["collected"] = True
save_state(state)
def run(documents): # documents: {text-derived id: text}
state = load_state()
in_flight = {i for b in state["batches"].values() if not b["collected"] for i in b["ids"]}
pending = [i for i in documents if i not in done_ids() and i not in in_flight]
for start in range(0, len(pending), CHUNK_SIZE):
submit_chunk({i: documents[i] for i in pending[start:start + CHUNK_SIZE]}, state)
for batch_id, info in list(state["batches"].items()):
if not info["collected"]:
collect(batch_id, state)
return [i for i in documents if i not in done_ids()] # still unfinishedCall it with documents = {make_id(t): t for t in texts}. Rerun run(documents) until it returns an empty list.
Why this survives a crash
- Crash before submit: nothing is saved, so the chunk is pending again.
- Crash while polling:
state.jsonlists the uncollected batch, so the rerun polls it instead of resubmitting. - Crash during collection: the batch is still marked uncollected, so the next run collects it again. Duplicate lines may land in
results.jsonl, but they share onecustom_idanddone_ids()treats them as one result.
Exercise
Exercise
Your script crashes right after client.batches.create returns but before the batch ID is written to state.json. What goes wrong on the rerun, and how would you reduce the risk?
Show answer
The rerun cannot see the batch, so it treats those requests as pending and submits them again. You pay for the work twice, and the first batch's output is never collected. Reduce the risk by saving state as the very next statement after create. You can also attach metadata, such as a run label, to the batch. After a crash, list recent batches and match them by that label.