Overview
Every result you compute later depends on the data you started with, so you need to be able to say where the data came from and prove they have not changed. A collector keeps a list of named sources: a CSV file, a JSON-lines file (one JSON object per line), or a function that returns records, which is where a database query or an API call plugs in. When it gathers a source it tries again if the read fails, computes a checksum (a short fingerprint of the bytes), and writes one entry in a manifest, a log of what was gathered. The values are kept exactly as they arrived. This template is an in-process version: files and functions only, with no network client, scheduler or credentials store.
A short history
Data collection has no single inventor. Systematic gathering of records goes back to censuses and scientific field notebooks, and the modern engineering form grew out of extract, transform, load work in data warehousing from the 1980s and 1990s and later out of web APIs and data lakes. The habits taught here, named sources, retries on failure and a manifest of what was fetched, come from that operational practice and from the reproducible research movement.
How it works
- Register each source under a name with add_csv, add_jsonl or add_callable.
- Call check_access to confirm a source can be reached before you depend on it.
- Call collect or collect_all. Each source is read once, and on failure it is read again up to max_retries more times, waiting retry_delay seconds between attempts.
- The raw bytes are hashed with SHA-256, and when raw_dir is set an untouched copy is written there.
- An entry goes into the manifest: source, location, time, rows, columns, checksum, number of attempts. A source that fails every attempt is recorded as failed and raises CollectionError.
- Use to_array to get a numeric view of chosen columns without altering the gathered records, and save_manifest to write the log to disk.
Watch out for
- The collector loads each source whole into memory, so a file larger than memory will fail. Read such files in chunks instead.
- CSV values are kept as text on purpose. If you forget to convert them, numeric code will compare strings and sort 10 before 9.
- Retries only help with failures that come and go. A wrong path or a bad delimiter fails the same way every time and just costs more waiting.
- Turning on dedupe changes the row count. The manifest records how many duplicates were dropped, and the checksum still describes the bytes as gathered, not the rows you received.
- A checksum proves the bytes are unchanged, not that they are correct. A source that was wrong when gathered stays wrong with a valid fingerprint.
Use cases
When to use it
At the top of a notebook or pipeline, so that every later result can be traced to named sources and exact bytes, and so that a flaky source fails loudly with a record instead of quietly returning less data.
In industry
- Retail analytics
- A retailer pulls daily sales exports from store systems and a weather feed, and logs the file names, row counts and checksums of each pull so a later report can be traced to its inputs.
- Machine learning teams
- Training data is gathered from application logs and labelling tools into a raw zone that is never edited, so every model can be rebuilt from the same snapshot.
- Scientific research
- A lab downloads public datasets from an archive and records the version and access date, as journals now ask for in data availability statements.
Choosing it: what must hold
- A clear question, so you know which sources and fields are worth gathering.
- Permission to access and store the data, including any licence, privacy or consent conditions.
- Somewhere to keep the raw copy unchanged, separate from cleaned versions.
- Sources reachable in a repeatable way such as a file export, a database query or an API.
When to choose something else
| If | Use instead |
|---|---|
| A suitable public or internal dataset already exists and is documented | Reuse it and move straight to data profiling |
| The population is too large or costly to gather in full | Sampling, with a design that keeps the subset representative |
| Real data cannot be obtained for privacy or cost reasons | Synthetic or simulated data, clearly labelled as such |
Math foundations
Chance that a source is gathered
If each attempt fails independently with probability , all attempts must fail for the gathering to fail. Retries shrink that chance geometrically, which is why a few are enough for failures that come and go.
Longest wait before a failure is reported
The collector waits seconds between attempts, so retries add at most waits. This is the price of the retries when a source is truly down.
The integrity check
A hash maps any byte string to 256 bits. Two different files with the same hash are so unlikely that matching hashes are taken as proof the raw copy is unchanged. This is what verify tests.
Symbols
- probability that one attempt to read a source fails
- max_retries: extra attempts allowed after the first
- retry_delay: seconds waited between attempts
- longest total waiting time before the source is reported as failed
- the bytes as gathered, and the bytes found in the raw copy later
Worked by hand
A source fails one read in five, so . The collector uses the default of 2 retries and a delay of 0.5 seconds.
Two retries turn a source that fails 20 percent of the time into one that fails 0.8 percent of the time, for at most one second of waiting.
Visual example
Loading the example.
Try this
- Set the failure chance to 0.5 and the retries to 0, then press Gather again a few times: about half the gatherings fail.
- Raise the retries one at a time and watch the long-run success share climb toward 1 while the longest wait grows.
- Press Change one byte of the raw copy, then click Raw copy in the diagram: the checksum no longer matches.
Code sample
from impl import DataCollector
from config import DataCollectorConfig
open("people.csv", "w").write("name,age\nAda,36\nBob,41\n")
collector = DataCollector(DataCollectorConfig(raw_dir="raw", max_retries=2))
collector.add_csv("people", "people.csv")
collector.add_callable("sensors", lambda: [{"id": 1, "temp": 20.5}, {"id": 2, "temp": 21.0}])
print(collector.check_access("people")) # (True, 'readable file')
data = collector.collect_all() # {"people": [...], "sensors": [...]}
print(DataCollector.to_array(data["people"], ["age"]))
collector.save_manifest("manifest.json") # provenance: rows, columns, sha256, attempts per sourceRead the implementation (184 lines)
"""Data collection: register sources, check access, gather raw records, and keep a provenance manifest.
Standard library and NumPy only, no network calls. A source is a CSV file, a JSON-lines file, or a Python callable
that returns records (the place where a database query or an API client would plug in). Every gathering is
retried on failure, checksummed, optionally copied untouched into a raw folder, and written down in a manifest so
that a later step can say exactly which bytes an analysis was built on.
"""
from __future__ import annotations
import csv
import hashlib
import json
import os
import time
from datetime import datetime, timezone
from typing import Callable
import numpy as np
try:
from .config import DataCollectorConfig
except ImportError: # run from the template's own folder
from config import DataCollectorConfig
KINDS = ("csv", "jsonl", "callable")
class CollectionError(RuntimeError):
"""A source could not be read after every allowed attempt."""
def _to_jsonl(records: list[dict]) -> bytes:
"""Records as JSON lines with sorted keys: one stable byte string per content."""
return "".join(json.dumps(r, sort_keys=True, default=str) + "\n" for r in records).encode("utf-8")
class DataCollector:
"""Registers data sources and gathers their records with retries, checksums and a manifest."""
def __init__(self, config: DataCollectorConfig | None = None) -> None:
self.config = config or DataCollectorConfig()
self.sources: dict[str, dict] = {}
self.manifest: list[dict] = []
# ---- registering sources -------------------------------------------------------------------------------
def _add(self, name: str, kind: str, location) -> None:
if not name or name in self.sources:
raise ValueError(f"source name must be new and non-empty, got {name!r}")
self.sources[name] = {"kind": kind, "location": location}
def add_csv(self, name: str, path: str) -> None:
"""Register a CSV file with a header row. Every value is kept as text: raw data is not interpreted."""
self._add(name, "csv", str(path))
def add_jsonl(self, name: str, path: str) -> None:
"""Register a JSON-lines file: one JSON object per line."""
self._add(name, "jsonl", str(path))
def add_callable(self, name: str, fetch: Callable[[], list]) -> None:
"""Register a function that returns a list of dict records each time it is called."""
if not callable(fetch):
raise ValueError("fetch must be callable")
self._add(name, "callable", fetch)
# ---- access --------------------------------------------------------------------------------------------
def check_access(self, name: str) -> tuple[bool, str]:
"""(ok, reason) for one source: does the file exist and may it be read? Nothing is gathered."""
source = self._source(name)
if source["kind"] == "callable":
return True, "callable source"
path = source["location"]
if not os.path.isfile(path):
return False, f"no such file: {path}"
if not os.access(path, os.R_OK):
return False, f"file is not readable: {path}"
return True, "readable file"
def _source(self, name: str) -> dict:
if name not in self.sources:
raise KeyError(f"unknown source {name!r}; registered: {sorted(self.sources)}")
return self.sources[name]
# ---- gathering -----------------------------------------------------------------------------------------
def _read_once(self, source: dict) -> tuple[list[dict], bytes]:
"""One attempt. Returns (records, raw bytes exactly as gathered)."""
if source["kind"] == "callable":
records = [dict(r) for r in source["location"]()]
return records, _to_jsonl(records)
with open(source["location"], "rb") as handle:
raw = handle.read()
text = raw.decode(self.config.encoding)
if source["kind"] == "csv":
return [dict(row) for row in csv.DictReader(text.splitlines(), delimiter=self.config.delimiter)], raw
return [json.loads(line) for line in text.splitlines() if line.strip()], raw
def collect(self, name: str) -> list[dict]:
"""Gather one source and add an entry to the manifest.
Returns the records, a list of dicts (column name to value). Raises CollectionError when every one of
the 1 + config.max_retries attempts fails; the failure is recorded in the manifest too.
"""
source = self._source(name)
entry = {"source": name, "kind": source["kind"], "collected_at": datetime.now(timezone.utc).isoformat()}
entry["location"] = source["location"] if source["kind"] != "callable" else getattr(source["location"], "__name__", "callable")
last_error: Exception | None = None
for attempt in range(1, self.config.max_retries + 2):
try:
records, raw = self._read_once(source)
break
except Exception as error: # any failure of a source is retried, then reported
last_error = error
if attempt <= self.config.max_retries and self.config.retry_delay:
time.sleep(self.config.retry_delay)
else:
entry.update(status="failed", attempts=attempt, error=f"{type(last_error).__name__}: {last_error}")
self.manifest.append(entry)
raise CollectionError(f"source {name!r} failed after {attempt} attempts: {last_error}") from last_error
gathered = len(records)
if self.config.dedupe:
seen, unique = set(), []
for record in records:
key = json.dumps(record, sort_keys=True, default=str)
if key not in seen:
seen.add(key)
unique.append(record)
records = unique
columns: list[str] = []
for record in records:
columns.extend(k for k in record if k not in columns)
entry.update(
status="ok", attempts=attempt, rows=len(records), duplicates_dropped=gathered - len(records),
columns=columns, bytes=len(raw), sha256=hashlib.sha256(raw).hexdigest(), raw_path=None,
)
if self.config.raw_dir is not None:
os.makedirs(self.config.raw_dir, exist_ok=True)
extension = "csv" if source["kind"] == "csv" else "jsonl"
entry["raw_path"] = os.path.join(self.config.raw_dir, f"{name}.{extension}")
with open(entry["raw_path"], "wb") as handle:
handle.write(raw)
self.manifest.append(entry)
return records
def collect_all(self, stop_on_error: bool = True) -> dict[str, list[dict]]:
"""Gather every registered source. Returns {source name: records}.
With stop_on_error=False a failing source is skipped (its failure stays in the manifest).
"""
out: dict[str, list[dict]] = {}
for name in self.sources:
try:
out[name] = self.collect(name)
except CollectionError:
if stop_on_error:
raise
return out
def save_manifest(self, path: str) -> str:
"""Write the manifest (one entry per gathering, in order) as JSON. Returns the path."""
with open(path, "w", encoding="utf-8") as handle:
json.dump(self.manifest, handle, indent=2)
return str(path)
@staticmethod
def verify(entry: dict) -> bool:
"""True when the raw copy named by a manifest entry still has the recorded SHA-256 checksum."""
if not entry.get("raw_path") or not os.path.isfile(entry["raw_path"]):
return False
with open(entry["raw_path"], "rb") as handle:
return hashlib.sha256(handle.read()).hexdigest() == entry["sha256"]
@staticmethod
def to_array(records: list[dict], columns: list[str]) -> np.ndarray:
"""Numeric view of gathered records: shape (len(records), len(columns)), float.
Values that are missing or do not parse as numbers become NaN. The raw records are left as they were.
"""
def number(value) -> float:
try:
return float(value)
except (TypeError, ValueError):
return float("nan")
out = np.array([[number(record.get(column)) for column in columns] for record in records], dtype=float)
return out.reshape(len(records), len(columns))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Write a small CSV file, then build a DataCollector with raw_dir set. Register the file with add_csv and a function with add_callable that raises an error on its first call and returns records on its second. Run collect_all, read the attempts field of each manifest entry, then edit the raw copy by one character and call DataCollector.verify on its entry.
Check on learning
- Why does the collector keep CSV values as text instead of converting them to numbers as it reads?
A way to think about it
Think about what is lost if a postal code such as 02134 or an identifier such as 1e5 is read as a number, and whether you could recover the original afterwards.
- The retry formula assumes attempts fail independently. Describe a failure where that assumption is badly wrong, and say what the retries achieve there.
A way to think about it
Consider a server that is down for ten minutes. Is the second attempt, made half a second later, a fresh draw?
- Two runs of the same pipeline give different model results. How would you use the manifests of the two runs to find out whether the data are the cause?
A way to think about it
Compare the sha256, rows and collected_at fields source by source. Equal checksums rule the raw data out and point at the code or the random seeds.
- With stop_on_error set to False a failing source is skipped. When is that the right choice, and what must the code after it check?
A way to think about it
Think about an analysis that can run on partial data against one where a missing table silently changes the answer. The manifest still holds the failure.