CD0007 Debug QA Data Pipeline

Mode A · Bug Hunt 30 Min Python 3.10 · json + csv 4 Silent Bugs

Scale AI’s annotation pipelines turn human-labeled tasks into training data for LLM customers, and small pieces of glue code sit between the labeled JSON exports and the files a training job actually ingests. In this coding round you are handed one of those pieces: extract_qa.py, a 40-line script that walks a directory of annotation files, pulls question-answer pairs, deduplicates them, and writes a two-column CSV used as LLM fine-tuning data.

The nightly run reads annotations/, which holds 64 task files and 15,872 items. The script exits with status 0, but the data QA report on qa_train.csv flags three anomalies: (1) only 198 data rows were written, (2) 6 rows parse to more than two columns, with answer text bleeding into a third or fourth field, and (3) a reviewer’s spot check finds approved QA pairs missing from the CSV even though their source files load cleanly with json.load.

The vendor exporter was upgraded last quarter. Items reviewed after the upgrade are re-emitted in the new shape, so a single task file can mix both item shapes. The data contract you are given is below.

FieldSchema v1 (Legacy Exporter)Schema v2 (Current Exporter)
File envelope{"task_id": str, "items": [...]}Same envelope
Item idid: int, the item’s position within its task file (0, 1, 2, …)Same as v1
Questionquestion: strquestion: str
Answeranswer: str at the item’s top levelresponse: object holding answer (str) and rater_id (str)
RedeliveryA task may be re-sent as a second file with the same task_id; each item must reach the CSV onceSame as v1

Walk the script the way a record flows from disk to CSV. Find the 4 silent bugs, state exactly which line drops or corrupts each class of record, patch them in place with a minimal diff, and write a verification test on a mixed edge-case fixture that proves both row counts and CSV escaping.

Script Under Review (40 Lines):

01  import json
02  from pathlib import Path
03
04
05  def load_items(src_dir):
06      """Return (task_id, item) pairs from every annotation file."""
07      paths = sorted(Path(src_dir).glob("*.json"))
08      items = []
09      for path in paths:
10          with open(path, encoding="utf-8") as f:
11              doc = json.load(f)
12          for item in doc["items"]:
13              items.append((doc["task_id"], item))
14          return items
15
16
17  def extract_pairs(src_dir):
18      """Deduplicated (question, answer) pairs, in file order."""
19      pairs, seen = [], set()
20      for task_id, item in load_items(src_dir):
21          try:
22              question = item["question"].strip()
23              answer = item["answer"].strip()
24          except KeyError:
25              continue
26          key = item["id"]
27          if key in seen:
28              continue
29          seen.add(key)
30          pairs.append((question, answer))
31      return pairs
32
33
34  def write_csv(pairs, out_csv):
35      """Write a two-column CSV with a header row."""
36      with open(out_csv, "w", encoding="utf-8") as f:
37          f.write("question,answer\n")
38          for question, answer in pairs:
39              f.write('"' + '","'.join([question, answer]) + '"\n')
40      return len(pairs)
Data QA report for qa_train.csv: a bar chart comparing 15,872 annotation items on disk with 198 CSV data rows, and a second bar chart of fields per parsed CSV row showing 192 rows with 2 fields, 4 rows with 3 fields, and 2 rows with 4 fields

Figure 1: the data QA report. Only about 1.2% of the items on disk reach the CSV, and 6 of 198 rows read back with more than two columns, yet the script never raised.

Interactive Python Workspace: Switch to the split-screen workspace to patch the script in the live editor and run the hidden fixture checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) File Coverage: Compare how many paths the glob returns with how many files the loop actually opens before load_items returns.
(2) Schema Contract: For each item shape in the schema table, trace which keys lines 22-23 read and what the except branch does on a miss.
(3) Identity Contract: Decide what uniquely identifies one annotation across the whole directory, then compare it with the key built on line 26.
(4) Serialization Contract: List the characters that RFC 4180 says force quoting or escaping inside a field, and test each one against line 39.

2Visual Review Map (Figure 2)
Pipeline review map: annotations on disk flow through four stages, the file loop at lines 05-14, the field read at lines 20-25, the dedup key at lines 26-29, and serialization at lines 34-40, each marked with a question mark, into qa_train.csv; a second row lists the count to reconcile at each stage

Figure 2: the four stages a record crosses between disk and CSV. Each ? marks a stage to inspect; reconcile the count beneath it before you edit any line.

3Interviewer Nudge & Line Focus

Answer each Socratic check on paper before touching the editor:

File Loop: paths holds 64 files. Trace control flow through one full iteration: after line 13 appends the first file’s items, which line executes next, and how many times does line 10 run in total?
Field Read: Hand-feed one item of each schema version through lines 22-23. Which one raises, which exception is it, and does any counter or log record that the item was skipped?
Dedup Key: Take item 0 of two different task files and compute the line-26 key for each by hand. If every file numbers its 248 items from 0, how many distinct keys can 64 tasks produce?
Serialization: Write the row for the answer He said "stop", then left. by hand exactly as line 39 would. Then read it back character by character as a CSV parser would: how many fields come out?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *