Sub topic 13
Designing a restartable, idempotent pipeline
This chapter assumes you can write Python with file I/O and JSON, and that you have already submitted a batch, polled it, and read its output and error files. It also assumes you know what custom_id is for and how partial failures appear in the results. Here you will combine those pieces into a pipeline that can be killed at any moment and restarted without losing work or paying twice for the same request.
Why a script is not a pipeline
The earlier examples ran top to bottom in one process. That works for a pilot. A real job runs for hours, and the batch itself can take up to 24 hours to complete. In that time your process can be killed, your laptop can sleep, a deploy can restart the worker, or the network can drop in the middle of a call.
A restartable pipeline keeps its progress outside the process. An idempotent one gives the same final state whether a step runs once or five times. Together they let you apply one rule: after any crash, start the program again and it finishes the job.
The crash points that matter are listed below.
| Crash point | What goes wrong in a naive script | Design answer |
|---|---|---|
| Before the batch is created | Nothing is lost, but the request file may be half written | Rebuild the file from the ledger |
| After the batch is created, before its ID is saved | The batch runs and is billed, but you have lost its ID, and a restart submits it again | Tag the batch with a deterministic key and look it up on restart |
| While the batch runs | The poll loop dies | Poll from saved batch IDs, not from a variable in memory |
| Halfway through reading results | Some results are saved and some are not | Make each write safe to repeat |
| After results are read | A rerun reprocesses finished work | Skip requests already marked done |
The ledger: one row per request
The core of the design is a ledger, a small database that records the state of every request. This chapter uses SQLite because it needs no server and survives restarts. Any durable store works the same way.
Each request is in exactly one of four states.
The dead state matters. Some requests fail every time, for example when the body is invalid or the input is too long. Without an attempt cap, a pipeline that retries "failed" work would resubmit them forever and pay for each try.
Deterministic custom_id values
Idempotency starts with the ID. If you generate custom_id with a random UUID, a restarted program creates new IDs for the same documents, and the ledger cannot tell it has seen them. Derive the ID from the input instead.
import hashlib
import json
import sqlite3
import time
from openai import OpenAI
client = OpenAI()
db = sqlite3.connect("pipeline.db")
db.executescript("""
CREATE TABLE IF NOT EXISTS requests (
custom_id TEXT PRIMARY KEY,
body TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'pending',
batch_id TEXT,
attempts INTEGER NOT NULL DEFAULT 0,
result TEXT,
error TEXT
);
""")
TERMINAL = {"completed", "failed", "expired", "cancelled"}
MAX_ATTEMPTS = 3
PROMPT_VERSION = "v1"
def make_custom_id(doc_id: str, text: str) -> str:
digest = hashlib.sha256(f"{PROMPT_VERSION}\n{text}".encode("utf-8")).hexdigest()[:12]
return f"{doc_id}:{PROMPT_VERSION}:{digest}"
def enqueue(doc_id: str, text: str) -> None:
body = {
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "Summarize the text in one sentence."},
{"role": "user", "content": text},
],
"max_tokens": 100,
}
db.execute(
"INSERT OR IGNORE INTO requests (custom_id, body) VALUES (?, ?)",
(make_custom_id(doc_id, text), json.dumps(body)),
)
db.commit()The ID combines the document ID, the prompt version, and a hash of the text. This has three effects:
- Running
enqueuetwice on the same document does nothing the second time, becauseINSERT OR IGNOREskips the existing primary key. - If the document text changes, the hash changes, so the new text gets a new request instead of reusing a stale result.
- If you change the prompt, bump
PROMPT_VERSION. Every document then gets a new ID, and old results stay in the ledger under the old IDs.
The blocks in this chapter form one Python file, so continue in the same module.
Submitting a chunk without losing the batch
The riskiest step is the gap between batches.create returning and your program writing the batch ID to the ledger. If the process dies there, a restart sees the requests as still pending and submits them again. You pay twice.
The fix is a chunk key. It is a hash of the request IDs in the chunk, so the same set of pending requests always produces the same key. You attach the key to the batch as metadata. Before creating a batch, you search your existing batches for that key.
def find_batch(chunk_key: str):
for batch in client.batches.list(limit=100):
meta = batch.metadata or {}
if meta.get("chunk_key") == chunk_key and batch.status not in {"failed", "expired", "cancelled"}:
return batch
return None
def submit_chunk(max_requests: int = 1000):
rows = db.execute(
"SELECT custom_id, body FROM requests "
"WHERE state = 'pending' AND attempts < ? ORDER BY custom_id LIMIT ?",
(MAX_ATTEMPTS, max_requests),
).fetchall()
if not rows:
return None
chunk_key = hashlib.sha256("\n".join(r[0] for r in rows).encode("utf-8")).hexdigest()[:32]
batch = find_batch(chunk_key)
if batch is None:
path = f"chunk_{chunk_key}.jsonl"
with open(path, "w", encoding="utf-8") as f:
for custom_id, body in rows:
line = {
"custom_id": custom_id,
"method": "POST",
"url": "/v1/chat/completions",
"body": json.loads(body),
}
f.write(json.dumps(line) + "\n")
with open(path, "rb") as f:
uploaded = client.files.create(file=f, purpose="batch")
batch = client.batches.create(
input_file_id=uploaded.id,
endpoint="/v1/chat/completions",
completion_window="24h",
metadata={"chunk_key": chunk_key},
)
db.executemany(
"UPDATE requests SET state = 'submitted', batch_id = ?, attempts = attempts + 1 "
"WHERE custom_id = ?",
[(batch.id, r[0]) for r in rows],
)
db.commit()
return batch.idSorting by custom_id makes the chunk deterministic, which the key depends on. If the program crashes after batches.create, the restart rebuilds the same chunk, computes the same key, finds the running batch, and adopts it. It never creates a second one.
The max_requests value is where you apply the provider's size limits. Choose a number below both the request-count and file-size limits for your account, and remember that quotas on queued tokens can also reject a chunk that is otherwise small enough.
A leftover uploaded file from a crash is harmless. It is an unused input, and it is not billed as a job.
Collecting results with repeatable writes
Reading results must be safe to run twice. The crash you are guarding against here happens after you have saved some results but before you have finished.
def record(custom_id: str, ok: bool, payload: str) -> None:
if ok:
db.execute(
"UPDATE requests SET state = 'done', result = ?, error = NULL "
"WHERE custom_id = ? AND state != 'done'",
(payload, custom_id),
)
else:
db.execute(
"UPDATE requests SET error = ?, "
"state = CASE WHEN attempts >= ? THEN 'dead' ELSE 'pending' END "
"WHERE custom_id = ? AND state = 'submitted'",
(payload, MAX_ATTEMPTS, custom_id),
)
def collect(batch_id: str) -> bool:
batch = client.batches.retrieve(batch_id)
if batch.status not in TERMINAL:
return False
for file_id in (batch.output_file_id, batch.error_file_id):
if not file_id:
continue
for line in client.files.content(file_id).text.splitlines():
rec = json.loads(line)
resp = rec.get("response")
if rec.get("error") is None and resp and resp["status_code"] == 200:
text = resp["body"]["choices"][0]["message"]["content"]
record(rec["custom_id"], True, text)
else:
record(rec["custom_id"], False, json.dumps(rec.get("error") or resp))
leftovers = db.execute(
"SELECT custom_id FROM requests WHERE batch_id = ? AND state = 'submitted'",
(batch_id,),
).fetchall()
for (custom_id,) in leftovers:
record(custom_id, False, f"no result in batch {batch_id} (status {batch.status})")
db.commit()
return TrueEach guard in the SQL does a specific job:
state != 'done'stops a repeated success from overwriting a result.state = 'submitted'on the failure path stops a late failure from downgrading a request that already succeeded.- The leftovers query finds requests that appear in neither file. This covers an expired batch that finished only part of its work, and a failed batch with no files at all.
If the program dies midway through collect, nothing is committed. On restart the batch is still completed, the rows are still submitted, and the whole read runs again with the same outcome.
The driver loop
The driver reads only from the ledger, so it has no state of its own to lose.
def run(poll_seconds: int = 60) -> None:
while True:
in_flight = [
row[0]
for row in db.execute(
"SELECT DISTINCT batch_id FROM requests WHERE state = 'submitted'"
)
]
for batch_id in in_flight:
collect(batch_id)
remaining = db.execute(
"SELECT COUNT(*) FROM requests WHERE state = 'submitted'"
).fetchone()[0]
if remaining == 0 and submit_chunk() is None:
break
time.sleep(poll_seconds)
counts = db.execute("SELECT state, COUNT(*) FROM requests GROUP BY state").fetchall()
print(dict(counts))
if __name__ == "__main__":
enqueue("doc-001", "The meeting moved to Thursday because of a venue conflict.")
enqueue("doc-002", "Quarterly revenue grew 4% while costs stayed flat.")
run()This loop keeps one chunk in flight at a time. That is the simplest way to stay under queued-token quotas. If you need more throughput, allow several chunks in flight, but keep the per-chunk logic the same.
Edge cases to plan for
- Duplicate results. A request can appear in a result file twice only if you submitted it twice. The
state != 'done'guard keeps the first answer. If you must compare duplicates, store them in a separate table instead. - Prompt changes mid-run. Requests already in the ledger keep the body they were enqueued with. If you change the prompt, bump
PROMPT_VERSIONand enqueue again. Do not edit stored bodies. - Cancellation. If you cancel a batch, it passes through
cancellingbefore reachingcancelled. Requests that finished before the cancel still have output. The leftovers logic handles the rest. - Retention of files. Provider output files do not stay forever. Copy results into your own store as soon as a batch completes, as
collectdoes. Do not rely on downloading them again later. - Poison requests. The attempt cap sends a request that always fails to
dead. Review dead rows by hand, since retrying them unchanged will not help. - Ledger backups. The ledger is now the source of truth. Back it up the way you would back up any other data you cannot cheaply rebuild.
Observability and the pilot
Print the state counts on every loop, or write them to a log. A healthy run shows pending shrinking, submitted rising and falling in steps, and dead staying near zero. A rising dead count usually means a systematic problem such as a bad prompt template or a model name your account cannot use.
Test the whole pipeline on a pilot of 20 to 50 requests before the full run. Then deliberately break it. Kill the process right after batches.create, restart, and confirm in the provider dashboard that only one batch exists. Kill it during collect and confirm the rerun ends in the same state. Recovery paths that have never run are the ones most likely to be wrong.
Exercise
A worker crashes after batches.create succeeds but before the batch ID is written to the ledger. On restart, how does the pipeline avoid creating a second batch for the same requests?
Show answer
The pipeline sorts the pending request IDs and hashes them into a chunk key, so the same pending set always gives the same key. The key was stored in the batch metadata. On restart, submitchunk rebuilds the same chunk, computes the same key, finds the running batch with findbatch, and records its ID instead of calling batches.create again.
Exercise
You edit the system prompt and rerun the pipeline against the same documents. Nothing is resubmitted and the old summaries are returned. What went wrong, and what is the fix?
Show answer
The customid values did not change, because PROMPTVERSION stayed the same, so INSERT OR IGNORE skipped every document. Bump PROMPTVERSION (for example to "v2") so each document gets a new customid, then enqueue the documents again. The v1 results stay in the ledger, and the v2 requests are submitted as new work.