lineage-copilot
# Lineage Copilot
**Change a dbt column → see what breaks, why, and who to tell.** Column-level lineage of a dbt project lives in one Relate graph file. A Claude agent, a PR-diff checker, a web graph view and an MCP server all answer from paths in that graph — every claim cites the chain of edges behind it.

## Use case
An analytics engineer renames `orders.amount` to `order_amount` in a pull request. Static checks pass. Two days later the board's KPI deck shows zero revenue, and the dashboard owner hears about it first.
The questions they needed answered before merging are graph questions:
- **What breaks?** Which downstream columns, models and dashboards read this column, through which SQL transforms?
- **Why is this number wrong?** Walk a dashboard back to its raw source columns.
- **Who do I tell?** The owners of every affected table and dashboard, with the reason for each.
dbt's own docs stop at model-level lineage. Lineage Copilot parses every model's compiled SQL with sqlglot to get **column-level** edges (with the transform on each hop, e.g. `SUM(payments.amount)`). It stores them, together with dbt exposures, owners and tests, in Relate. Then it answers those three questions in four ways:
| Surface | Command | What you get |
|---|---|---|
| PR check | `lineage-copilot pr-impact --diff my.patch` | Markdown report for a PR comment: dropped / renamed / changed columns, risk, dashboards, owners, a suggested fix |
| Web UI | `lineage-copilot ui` | Search → impact or root-cause graph with the SQL on every hop, PR check, Ask (FastAPI + plain JS, no build step) |
| Agent | `lineage-copilot ask "…"` | Claude walks the graph with 7 tools and answers with cited chains (offline fallback without a key) |
| MCP | `lineage-copilot mcp` / `.mcp.json` | The same 7 tools for Claude Code, Cursor or any MCP host |
## How it uses Relate
**Mode: single file — [`data/lineage.rl`](data/lineage.rl) (1.4 MB, committed).**
Why a single file:
- **One portable snapshot per project and commit.** CI can build it from `manifest.json`, attach it to the PR, and diff it against `main`'s snapshot.
- **Embedded, no server.** The CLI, the UI and the MCP server open it read-only in-process via the `relate-db` Python package. Judges need no database setup.
- **Inspectable as-is.** You can open the committed file with the `relate` CLI and query it (see below).
**What the graph models** (112 nodes, 180 relationships for the bundled jaffle_shop project):
```mermaid
graph LR
Column -- "DERIVES_FROM {transform}" --> Column
Table -- HAS_COLUMN --> Column
Table -- DEPENDS_ON --> Table
Exposure -- USES --> Table
Owner -- OWNS --> Table
Owner -- OWNS --> Exposure
Test -- TESTS --> Column
Test -- TESTS --> Table
```
| Label | Count | Notes |
|---|---|---|
| `Column` | 61 | `description`, `data_type`, 384-dim `embedding` (all-MiniLM-L6-v2) |
| `Table` (`:Model` / `:Seed`) | 12 | dbt models and seeds |
| `Exposure` | 4 | dashboards / applications from `exposures.yml` |
| `Owner` | 5 | from `meta.owner` / exposure owners |
| `Test` | 30 | dbt data tests |
Relate features the project relies on:
- **Quantified path patterns** (`<-[:DERIVES_FROM]-{1,6}`) with the `SHORTEST 1` selector for `impact`, `root_cause` and `path`. Each tool returns the chain plus the transform on every hop.
- **Hybrid retrieval for `resolve`.** Exact id, full-text index and vector index (`SEARCH … VECTOR INDEX`) results are fused. "order amount" or "board deck" find `orders.amount` or `board_kpi_deck` without exact names.
- **`EXISTS {}` subqueries** to tell whether a dashboard reads the changed column or only its table.
- **`next_hop`**: one real edge at a time, ranked by relevance to the agent's goal. The agent walks the graph instead of guessing ids.
- Every tool returns the Cypher it ran. The UI shows it next to the graph (Cypher button), so judges can paste it into the `relate` CLI.
## Setup and run
Requirements: macOS or Linux, [uv](https://docs.astral.sh/uv/), Python 3.12+ (uv installs it). No database server.
```bash
git clone https://github.com/lehuubao2909/lineage-copilot.git && cd lineage-copilot
uv sync # installs relate-db, sqlglot, fastapi, anthropic, mcp…
```
**1. PR impact report (no key, < 1 s):**
```bash
uv run lineage-copilot pr-impact --diff examples/rename-amount.patch
uv run lineage-copilot pr-impact --diff examples/drop-first-name.patch
```
**2. Web UI** — http://localhost:8501 (localhost only):
```bash
uv run lineage-copilot ui
```
The first search takes about 20–30 s: the embedding model loads, and downloads (~90 MB) on the very first run. After that, searches take under 1 s.
**3. Ask the agent:**
```bash
cp .env.example .env # then put your key in ANTHROPIC_API_KEY
uv run --env-file .env lineage-copilot ask -v "What breaks if I rename stg_payments.amount?"
uv run lineage-copilot ask --offline "Who should I tell before dropping customers.first_name?"
```
For the UI's Ask screen, start the UI with the key too: `uv run --env-file .env lineage-copilot ui`.
**4. Use it from Claude Code (MCP):** open Claude Code in this folder. `.mcp.json` registers the `lineage-copilot` server (stdio). Then ask "what breaks if I drop orders.amount?".
**Rebuild the store** from the committed dbt artifacts (optional; the store is already committed):
```bash
uv run lineage-copilot ingest # dbt/jaffle_shop/dbt-artifacts → data/lineage.rl
```
**Tests:** `uv run pytest` (119 tests: SQL lineage extraction, graph tools, PR-diff parsing/hardening, agent loop with a stub client, MCP over stdio, CLI, web API via FastAPI TestClient).
### LLM provider, model and key
- Provider: **Anthropic**. Model: **`claude-opus-5-5`** by default; override it with `LINEAGE_COPILOT_MODEL`.
- Key: set **`ANTHROPIC_API_KEY`** in `.env` (copy `.env.example`) or in your shell. No key ships in this repo.
- Only `ask` and the UI's Ask screen call Claude. `pr-impact`, the impact explorer and the MCP server never call an LLM.
- Without a key, Ask falls back to an offline fixed plan (`resolve` → `impact`/`root_cause` → `who_to_notify`) over the same graph. The answer is labelled "Offline mode".
## Where the data lives
| Path | What |
|---|---|
| [`data/lineage.rl`](data/lineage.rl) | **The Relate store** (single file, committed). Opened read-only by every command. |
| `dbt/jaffle_shop/` | Demo dbt project: jaffle_shop_duckdb plus 4 marts models, exposures and owners added for this project |
| `dbt/jaffle_shop/dbt-artifacts/manifest.json`, `catalog.json` | dbt output that `ingest` reads (committed, so you don't need to run dbt) |
| `examples/*.patch` | Sample PR diffs |
Inspect the store with the Relate CLI (`curl -sSfL https://relatedb.ai/install.sh | bash`). Use `--read-only` so the committed file is never checkpointed. Stop the UI first: Relate allows one process per store, and a second process gets `storage locked`.
```bash
relate -d data/lineage.rl --read-only "MATCH (n) UNWIND labels(n) AS l RETURN l, count(*) AS n ORDER BY l"
relate -d data/lineage.rl --read-only "MATCH p = SHORTEST 1 (:Column {id:'orders.amount'})<-[:DERIVES_FROM]-{1,6}(:Column) RETURN [n IN nodes(p) | n.id] AS chain"
relate -d data/lineage.rl --read-only "MATCH (e:Exposure)-[:USES]->(t:Table)<-[:OWNS]-(o:Owner) RETURN e.label, t.name, o.name"
```
## Screenshots
| Root cause | PR diff | Ask (offline) |
|---|---|---|
|  |  |  |
## Architecture
```mermaid
graph LR
M[dbt manifest + catalog] --> I[ingest: sqlglot column lineage + embeddings]
I --> R[(data/lineage.rl<br/>Relate)]
R --> W[GraphWorker<br/>read-only, one thread]
W --> T[7 lineage tools<br/>resolve · describe · impact · root_cause · path · who_to_notify · next_hop]
T --> A[Claude agent loop]
T --> P[pr-impact report]
T --> U[Web UI<br/>FastAPI + SVG graph]
T --> X[MCP server stdio]
```
Relate connections are thread-affine, so one worker thread owns the store, and the UI and the MCP server send their calls to it.
## Limits
- Lineage is as good as sqlglot's parse of the compiled SQL. Columns it cannot resolve are flagged `partial`, never guessed.
- The demo project is small (jaffle_shop + 4 marts). Ingest is linear in models and has not been benchmarked on large projects.
- One process per store (Relate's design). While `ui` or `mcp` holds `data/lineage.rl`, another process (e.g. the `relate` CLI) gets `storage locked`.
- PR analysis renders Jinja with stub `ref`/`source`/`var` macros, not a full dbt compile.
## Credits and licenses
- Code: Apache-2.0 ([LICENSE](LICENSE)).
- Demo dbt project derived from [dbt-labs/jaffle_shop_duckdb](https://github.com/dbt-labs/jaffle_shop_duckdb) (Apache-2.0; its LICENSE is kept in `dbt/jaffle_shop/`).
- Libraries: [Relate](https://github.com/relatedb/relate) (`relate-db`), sqlglot, dbt-core / dbt-duckdb, sentence-transformers (all-MiniLM-L6-v2), FastAPI, Uvicorn, Anthropic Python SDK, MCP Python SDK.
- UI assets loaded from CDNs: [Lucide](https://lucide.dev) icons (ISC), [Inter](https://rsms.me/inter/) font (OFL). The UI still works offline with system fonts; icons then don't show.
- Not affiliated with or endorsed by Neo4j.
## AI use statement
- **At runtime:** `ask` uses Anthropic Claude (`claude-opus-5-5`) through a manual tool-use loop. The system prompt is in [`src/lineage_copilot/agent_system_prompt.py`](src/lineage_copilot/agent_system_prompt.py) and the tool schemas are in [`src/lineage_copilot/lineage_tools.py`](src/lineage_copilot/lineage_tools.py). Claude only sees what the tools return from the graph.
- **During development:** this project was built with significant help from Claude Code (Anthropic), which wrote most of the code, tests and docs under the author's direction and review. All work was done during the contest period (from 11 Nov 2026).
TDQS
Scored across 7 tools
Most tools have clearly distinct purposes: resolve for id lookup, impact for downstream, root_cause for upstream, path for node-to-node flow, and who_to_notify for owner notification. There is minor overlap because describe and next_hop both surface neighbours, and impact also reports owners that who_to_notify focuses on, but the descriptions give enough guidance to separate them.
The names are all lowercase/snake_case and readable, but they mix conventions: resolve and describe are verbs, impact and path are nouns, and root_cause, who_to_notify, and next_hop are noun-like phrases. The set is understandable but lacks a predictable verb_noun or otherwise consistent pattern.
Seven tools is well-scoped for a lineage exploration server. Each tool covers a distinct part of the workflow: resolving ids, describing assets, walking lineage, analysing impact and root cause, finding paths, and identifying owners to notify.
The surface covers the core read-only lineage domain: id resolution, asset metadata, one-hop traversal, upstream root-cause analysis, downstream impact analysis, path finding, and owner notification. No obvious lifecycle gaps exist for a read-only lineage copilot.