KatInterview

Streaming Text Labeling Pipeline with Retry Logic

System DesignModel answer
EasyModel answerSystem Designpythonconcurrencydata-pipeline

Last 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:

  1. Reads a CSV where each row has an id and a text field.
  2. Calls labeler.label(text) for each row and validates the returned label against a caller-supplied permitted_labels list.
  3. Retries the call (up to max_retries additional attempts) when the API raises LabelingError or returns a label outside permitted_labels.
  4. Writes one JSON object per line to an output file, preserving the original row order.
  5. Marks any row as "FAILED" — rather than crashing — when it runs out of retries or has missing/empty required fields.
  6. 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

ColumnDescription
idUnique string identifier for the row
textRaw 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") → raises LabelingError on 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_labels has 1–50 unique strings.
  • The CSV has 0–100,000 rows.
  • A row with a missing or empty id or text must be marked FAILED immediately — do not call the labeler for it.
  • max_retries = 0 means 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.