Streaming Text Labeling Pipeline with Retry Logic
System DesignModel answerLast updated
Build a function that reads a CSV of text records, labels each one via an external API with retries, and writes ordered JSON Lines output with per-row failure handling.
Background
Annotation workflows often start with raw text sitting in a CSV file. Before that text reaches any downstream system, it needs a category label attached — something that comes back from a remote model API. Your job is to write the glue code that makes this reliable: read the file, call the API for each row, deal with failures gracefully, and produce clean output.
Task
Implement label_records, a function that:
- Reads a CSV where each row has an
idand atextfield. - Calls
labeler.label(text)for each row and validates the returned label against a caller-suppliedpermitted_labelslist. - Retries the call (up to
max_retriesadditional attempts) when the API raisesLabelingErroror returns a label outsidepermitted_labels. - Writes one JSON object per line to an output file, preserving the original row order.
- Marks any row as
"FAILED"— rather than crashing — when it runs out of retries or has missing/empty required fields. - Returns a summary of how many rows were processed, succeeded, and failed.
Interface
from typing import Protocol, List, Dict
class LabelingError(Exception):
pass
class LabelerAPI(Protocol):
def label(self, text: str) -> str:
"""Calls a remote model. May raise LabelingError."""
...
def label_records(
input_csv_path: str,
output_jsonl_path: str,
labeler: LabelerAPI,
permitted_labels: List[str],
max_retries: int = 2,
) -> Dict[str, int]:
"""
Returns:
{
"total": int,
"success": int,
"failed": int,
}
"""
pass
Input / Output Schema
Input CSV columns
| Column | Description |
|---|---|
id | Unique string identifier for the row |
text | Raw text to be labeled |
Output JSONL — one JSON object per line
Successful row:
{"id": "r1", "text": "Cancel my subscription", "label": "billing", "status": "SUCCESS"}
Failed row:
{"id": "r2", "text": "...", "label": null, "status": "FAILED", "error": "LabelingError: timeout"}
Example
Input (items.csv)
id,text
r1,Cancel my subscription
r2,Server keeps crashing
r3,
Call configuration
permitted_labels = ["billing", "technical_support", "general"]labeler.label("Cancel my subscription")→"billing"labeler.label("Server keeps crashing")→ raisesLabelingErroron every attempt
Expected output (out.jsonl)
{"id": "r1", "text": "Cancel my subscription", "label": "billing", "status": "SUCCESS"}
{"id": "r2", "text": "Server keeps crashing", "label": null, "status": "FAILED", "error": "LabelingError: timeout"}
{"id": "r3", "text": "", "label": null, "status": "FAILED", "error": "Empty text"}
Expected return value
{"total": 3, "success": 1, "failed": 2}
Constraints
permitted_labelshas 1–50 unique strings.- The CSV has 0–100,000 rows.
- A row with a missing or empty
idortextmust be markedFAILEDimmediately — do not call the labeler for it. max_retries = 0means one attempt total; no retries.
Hints
Hint 1
Split the problem into three independent concerns before writing any code: input validation per row, the retry loop around the API call, and the output writer. Mixing them together makes each part harder to test and reason about.
Hint 2
For the retry loop, track the error from the most recent attempt so you can include it in the FAILED record. Apply exponential backoff with jitter between attempts, but skip the sleep after the last attempt since there is no next attempt to delay.
Hint 3
To preserve output order while still running API calls concurrently, submit each row to a thread pool and store the resulting Future objects in a queue that mirrors the original row order. Drain from the front of that queue — not by completion order — before writing.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has three distinct concerns that are easiest to reason about separately: per-row validation, a retrying API wrapper, and an ordered concurrent writer. Tangling them together is the most common mistake.
1. Per-row validation
Before touching the network, check the row. If id or text is absent, None, or blank after stripping whitespace, emit a FAILED record immediately. The labeler is never called. This keeps the retry logic clean — by the time a row reaches it, text is guaranteed to be a non-empty string.
One subtle point: csv.DictReader returns None for a column that is entirely absent from the header (not just an empty cell). Check for None and for "".strip() separately so the error message is specific.
2. Retry helper with backoff
"Up to max_retries retries" means 1 initial attempt + max_retries retries, so the loop runs max(0, max_retries) + 1 times. Two conditions trigger a retry:
- The labeler raises
LabelingError— a transient API fault. - The returned label is not in
permitted_labels— treat this like a bad response, not a hard stop, so a flaky model that occasionally returns garbage does not poison the whole run.
Any other exception (programming error, network library bug) is non-retryable. Convert it to a FAILED record rather than crashing, but do not retry.
Use exponential backoff with jitter between attempts. Cap the sleep to avoid runaway waits. Skip the sleep after the final attempt — there is nothing to wait for. Always record the error from the last attempt so the message in the output file reflects what actually went wrong on the final try.
Category membership is checked with a frozenset for O(1) lookup instead of scanning a list on every attempt.
3. Ordered concurrent writer
The labeler is I/O-bound, so running calls in parallel with a ThreadPoolExecutor cuts wall-clock time roughly proportional to worker count. The challenge is preserving output order without waiting for the slowest row to finish before writing anything.
The solution: submit each row to the pool and immediately append the resulting Future to a deque that mirrors CSV row order. A drain_one helper always calls .result() on the leftmost future — the oldest unwritten row. This means a slow row at position i blocks writing of rows i, i+1, ... but never blocks the workers processing rows i+2, i+3, .... Output order is guaranteed because writes happen left-to-right from the ordered deque.
Cap the deque at a fixed window size (e.g., 4 × worker_count) for backpressure: once the window is full, drain one entry before submitting the next. This keeps at most O(window) rows in memory regardless of CSV size, which matters for files with 100,000 rows.
Complexity
- Time: O(N × (1 + R)) labeler calls worst-case, where R =
max_retries. Parsing and serialization are O(N). Wall-clock time is roughly O(N × (1 + R) / workers) since the work is I/O-bound. - Space: O(W) for the in-flight window, independent of N. Reading and writing are both streamed.
Edge cases worth mentioning
- Empty CSV (header only or zero bytes): returns
{"total": 0, "success": 0, "failed": 0}and writes an empty output file. - BOM-prefixed UTF-8 files: opening with
utf-8-sigprevents the first column name from becoming"\ufeffid". - Whitespace-only text: treated as empty and failed. The original text is preserved in the output record.
- Case sensitivity:
"Billing"is rejected ifpermitted_labelscontains"billing". Normalize both sides deliberately if the product wants case-insensitive matching — don't silently coerce. max_retries = 0: exactly one attempt, no sleep, which is correct from the formula above.
Code
import csv
import json
import random
import time
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Dict, FrozenSet, List, Optional, Protocol, Tuple
class LabelingError(Exception):
pass
class LabelerAPI(Protocol):
def label(self, text: str) -> str:
...
MAX_WORKERS = 16
WINDOW = MAX_WORKERS * 4 # max futures held in the deque at once
BASE_BACKOFF_S = 0.05
MAX_BACKOFF_S = 2.0
def _label_with_retry(
text: str,
labeler: LabelerAPI,
permitted: FrozenSet[str],
max_retries: int,
) -> Tuple[Optional[str], Optional[str]]:
"""Return (label, None) on success, or (None, error_message) on failure."""
attempts = max(0, max_retries) + 1
last_error = "Unknown error"
for attempt in range(attempts):
try:
result = labeler.label(text)
except LabelingError as exc:
last_error = f"LabelingError: {exc}"
except Exception as exc:
# Unexpected error — don't retry, but don't crash the pipeline.
return None, f"{type(exc).__name__}: {exc}"
else:
if isinstance(result, str) and result in permitted:
return result, None
last_error = f"Invalid label: {result!r}"
# Backoff before the next attempt (skip after the last one).
if attempt < attempts - 1:
delay = min(MAX_BACKOFF_S, BASE_BACKOFF_S * (2 ** attempt))
time.sleep(delay * random.uniform(0.5, 1.5)) # jitter
return None, last_error
def _make_failed(
row_id: Optional[str],
text: Optional[str],
error: str,
) -> Dict[str, Any]:
return {"id": row_id, "text": text, "label": None,
"status": "FAILED", "error": error}
def _process_row(
row: Dict[str, Optional[str]],
labeler: LabelerAPI,
permitted: FrozenSet[str],
max_retries: int,
) -> Dict[str, Any]:
raw_id = row.get("id")
text = row.get("text")
row_id = raw_id.strip() if isinstance(raw_id, str) else None
if not row_id:
return _make_failed(None, text, "Missing id")
if text is None:
return _make_failed(row_id, None, "Missing text")
if not text.strip():
return _make_failed(row_id, text, "Empty text")
label, error = _label_with_retry(text, labeler, permitted, max_retries)
if error is not None:
return _make_failed(row_id, text, error)
return {"id": row_id, "text": text, "label": label, "status": "SUCCESS"}
def label_records(
input_csv_path: str,
output_jsonl_path: str,
labeler: LabelerAPI,
permitted_labels: List[str],
max_retries: int = 2,
) -> Dict[str, int]:
permitted = frozenset(permitted_labels)
summary = {"total": 0, "success": 0, "failed": 0}
with (
open(input_csv_path, newline="", encoding="utf-8-sig") as fin,
open(output_jsonl_path, "w", encoding="utf-8") as fout,
ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool,
):
reader = csv.DictReader(fin)
pending: deque = deque()
def drain_one() -> None:
# Always drain the oldest future to preserve input order.
record = pending.popleft().result()
fout.write(json.dumps(record, ensure_ascii=False) + "\n")
summary["total"] += 1
summary["success" if record["status"] == "SUCCESS" else "failed"] += 1
for row in reader:
pending.append(
pool.submit(_process_row, row, labeler, permitted, max_retries)
)
if len(pending) >= WINDOW:
drain_one() # backpressure: cap memory usage
while pending:
drain_one()
return summary
Two things worth flagging in a review
Head-of-line blocking. A single very slow row stalls the writer but not the worker threads — they keep processing future rows in parallel. For most workloads this is fine. If tail latency is a real concern, a more complex approach would buffer completed out-of-order results and write them once all predecessors are done, at the cost of higher memory and code complexity.
Thread safety of the labeler. The solution assumes labeler.label() is safe to call from multiple threads simultaneously. If the client wraps a non-thread-safe HTTP library, you may need a per-thread client instance or a lock — worth confirming with whoever owns the client.