Can You Trace any Prediction Back to the Exact Data that Caused it? Here’s How I Built that
From the publisher’s feed, collected in the ZeroLabs newsroom.
Most ML systems can tell you what a model predicted. Almost none can tell you why or which raw data file, pipeline run, and git commit led to that specific output.There’s a question every production ML engineer eventually gets asked:“That model just made a bad prediction. Where did it come from?”And the honest answer, in most ML systems, is: we don’t know. We know which model version ran. Maybe which dataset was used — if someone named the S3 bucket well. But the full chain — raw data → feature engineering → training run → model → prediction — that chain is invisible.I built a system that makes it visible. Every prediction is traceable back to the exact CSV row, the exact pipeline run, and the exact git commit that produced it. And if you change the raw data, you can instantly see which models and predictions downstream will be affected — before you make the change.Here’s how it works.The Problem with ML ReproducibilityMLflow tracks experiments. DVC versions datasets. Git tracks code. Each tool does its piece. But they don’t talk to each other.You end up with:A model artifact in S3 with no link to the dataset it was trained onA dataset with no link to the pipeline that produced itPredictions with no link to anythingWhen something goes wrong — a model degrading, a regulatory audit, a data quality incident — you’re piecing together a story from separate logs, timestamps, and human memory.What you need is a lineage graph: a DAG that connects every artifact, every run, and every prediction into a single queryable structure.The ArchitectureThe system has three layers:Raw Data → [DatasetTracker] → DatasetVersion (SHA-256 hash, stored in MinIO) ↓ [PipelineTracker] → PipelineRun (git commit + metrics) ↓ ModelArtifact (serialized to MinIO) ↓ PredictionLog ↓ [LineageGraph] — NetworkX DAG over all of the above ↓ Streamlit UI — interactive pyvis graph explorerEverything goes into PostgreSQL as structured records. NetworkX builds the graph on top. The key insight: every node has a UUID, and edges are just rows in a lineage_edges table with source_id, source_type, target_id, target_type, and edge_type. Simple to query, simple to traverse.SHA-256 Dataset VersioningThe foundation is content hashing. Every dataset — whether a CSV file or a pandas DataFrame — gets SHA-256 hashed before anything else.async def track_file(self, name: str, path: str, ...) -> DatasetVersion: content_hash, _ = hash_file(path) # Dedup: same content = same version, no redundant storage existing = await self._meta.get_version_by_hash(content_hash) if existing and existing.name == name: return existing # New content: snapshot to MinIO, register in PostgreSQL snap = await snapshot_file(name, path, self._blob) return await self._meta.create_dataset_version( name=name, content_hash=snap["content_hash"], row_count=snap["row_count"], schema_json=snap["schema_json"], ... )This gives you content-addressed storage — the same file ingested twice creates one version, not two. And you can always reconstruct exactly what data a model trained on, even if the original file is long gone.Tracking Pipeline RunsEvery transformation step is a PipelineRun — a record that captures the git commit, parameters, metrics, start time, end time, and status.async with tracked_run(pipeline_tracker, "feature_engineering", {"n_features": 3}) as run: await pipeline_tracker.link_input(run.id, raw_version) # ... do your feature engineering ... await pipeline_tracker.link_output(run.id, features_version)# Context manager auto-finishes the run on exit — success or failureEach link_input and link_output call adds an edge to the lineage graph:dataset:raw_v1 → consumes → pipeline_run:feature_engineering_1pipeline_run:feature_engineering_1 → produces → dataset:features_v1The git commit is captured automatically via subprocess — no manual tagging required. You just wrap your pipeline and the metadata appears.The Lineage GraphOnce the edges are in PostgreSQL, NetworkX builds the graph:async def build_graph(self) -> nx.DiGraph: edges = await self._meta.get_all_edges() G = nx.DiGraph() for edge in edges: src_key = f"{edge.source_type}:{edge.source_id}" tgt_key = f"{edge.target_type}:{edge.target_id}" G.add_node(src_key, node_type=edge.source_type, ...) G.add_node(tgt_key, node_type=edge.target_type, ...) G.add_edge(src_key, tgt_key, edge_type=edge.edge_type) return GFrom this graph, you can ask two powerful questions.Trace upstream: “Where did this prediction come from?”trace = await lg.trace_upstream(prediction_id, "prediction")# Returns: [dataset:raw_v1, pipeline_run:feature_eng, dataset:features_v1,# pipeline_run:model_training, model:v1, prediction:xxx]# depth: 5 hops from raw data to predictionImpact analysis: “If I change this dataset, what breaks?”impact = await lg.impact_analysis("heart_raw", version=1)# Returns: {# affected_pipeline_runs: [feature_engineering #1],# affected_models: [heart_disease_model v1],# affected_predictions_count: 5,# risk_level: "MEDIUM"# }That risk level is computed from the number of downstream models — 0 models is low, 1–2 is medium, 3+ is high. Before you update a dataset, you know exactly what will be affected.The Streamlit UIFour pages, all backed by live PostgreSQL queries:Dataset Versions — browse every tracked dataset, compare versions side by side. The diff view shows added/removed/changed columns in colour. When we simulated adding a bmi_proxy column to the heart disease dataset, the diff immediately flagged it in green: "Added columns: bmi_proxy."Pipeline Runs — every run with its status (🟢/🔴), git commit hash, duration, and expandable parameters/metrics. Both runs in the demo show git commit: 81f83912 — you can pinpoint exactly which code version produced each artifact.Lineage DAG — the interactive graph, rendered via pyvis inside Streamlit. Blue dots are datasets, green boxes are pipeline runs, orange diamonds are models, red triangles are predictions. You can drag nodes, zoom in, filter by type, and enter any node UUID to trace its full ancestry.Impact Analysis — enter a dataset name, click Run. The MEDIUM risk badge appears in orange, the affected model is listed, and a downstream subgraph renders showing exactly which nodes would be invalidated by a change.Framework IntegrationsThe system is designed to be zero-friction to add to existing pipelines.Pandas — @track_dataframe decorator:@track_dataframe("heart_features", tracker=dataset_tracker)def engineer_features(df: pd.DataFrame) -> pd.DataFrame: # your existing code, unchanged return features_dfThe decorator intercepts the return value, hashes it, and creates a DatasetVersion automatically. Your function code doesn't change.sklearn — TrackedPipeline:pipeline = TrackedPipeline( steps=[("scaler", StandardScaler()), ("clf", GradientBoostingClassifier())], pipeline_tracker=pipeline_tracker, pipeline_name="model_training", model_name="heart_disease_model", ...)pipeline.fit(X_train, y_train)# Automatically: starts run, trains, serializes to MinIO,# creates ModelArtifact, adds lineage edges, finishes runMLflow — LineageMLflowCallback:with LineageMLflowCallback(pipeline_run=run, metadata_store=meta): with mlflow.start_run(): mlflow.log_params(params) model.fit(X_train, y_train) mlflow.log_metrics(metrics)# On exit: MLflow run ID is written to the lineage PipelineRun record# Now you can look up either direction: MLflow → lineage, or lineage → MLflowThe CLIRich terminal output for everything:# Full ancestry tree of a predictionlineage trace e2c7ca14 --type prediction# Upstream lineage - depth 5## dataset:04cbf1f2 (heart_raw v1)# └── pipeline_run:b407b0d3 (feature_engineering #1)# └── dataset:979b293d (heart_features v1)# └── pipeline_run:e6db2bcd (model_training #1)# └── model:0f47ad35 (heart_disease_model v1)# └── prediction:e2c7ca14# Impact analysis before updating a datasetlineage impact heart_raw --version 1# Risk level: MEDIUM# Affected pipeline runs: 2# Affected models: 1 — heart_disease_model v1 (sklearn)# Affected predictions: 5What This SolvesThree concrete scenarios where this pays off:Regulatory audit. “Show me every model that was trained on data containing patient X’s record.” You query for the dataset version containing that record, traverse downstream, collect all model artifacts. Done in seconds.Data quality incident. You discover the source CSV had corrupted values in rows 50–75. Which models were trained on a version containing those rows? lineage impact gives you the list immediately.Debugging a degraded model. “Why is model v2 worse than v1?” You trace both models upstream, compare their dataset versions using the diff viewer, and find that v2 was trained on data with a different schema — the cholesterol column was renamed.None of these are hypothetical. They happen in production ML systems every week. And in most teams, the answer involves a lot of Slack messages and hoping someone remembers.How It Connects to Project 1This project is designed to plug directly into the feature store I built previously. Feature datasets produced by the feature store become DatasetVersion nodes in the lineage graph. This means you can trace an online prediction — served from Redis in under 10ms — all the way back to the original ingestion run, including the git commit of the @feature transform function that computed it.The two systems together give you the full MLOps story: fast serving on the front end, complete traceability on the back end.The CodeEverything is open source: github.com/Emart29/pipeline-lineage-trackerThe heart disease demo (examples/heart_disease/demo.py) runs all 8 steps end to end — download data, version it, engineer features, train a model, log predictions, simulate a dataset change, run impact analysis, trace a prediction, and export the interactive DAG — in under 60 seconds.Run it against the shared infrastructure stack, open http://localhost:8502, and the full lineage graph is live.Next: Project 3 — canary deployment with automated rollback. Two model versions serving live traffic, Prometheus watching both, and automatic promotion or rollback based on real metrics.Can You Trace any Prediction Back to the Exact Data that Caused it? Here’s How I Built that was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.