Designing retrieval and code review for a data-engineering agent

How I designed retrieval for Purgo’s LangGraph agent, chose the design by ablation on real tickets, and cut the tables it missed by about 70%, and what I built in the review loop that repairs its code.

Context
Purgo AI, 2025–present
Read
9 min
Updated
Built with
Python, LangGraph, sqlglot, Pinecone, Databricks, dbt, BM25, Presidio, Langfuse

My part

  • Lineage expansion
  • Moving two stages to a smaller model
  • Pinecone catalog search
  • Much of the graph retrieval, with the team
  • The schema check
  • The repo search index
  • Size limits for what reaches the prompt, and sample rows per table
  • Lint rules for generated code, the check on dbt sources, and the recovery when every draft fails

I built lineage expansion on my own. The benchmark harness and the other checks are the team’s.

Purgo’s agent does a data team’s work from a ticket. The team describes a change it needs, such as a new report or a fix to a pipeline, and the agent writes the code: PySpark, SQL, or models in dbt (a tool where each table is defined by a SQL query, called a model).

A ticket rarely lists the tables that code needs. It names a report, a dbt model or a business term, and the warehouse holds hundreds of tables. If a needed table never reaches the LLM’s context, the LLM guesses a name or leaves out a join without saying so. Every extra table uses up context and can mislead the LLM.

So the design has two jobs: get the right tables into a bounded context, and catch code that would fail on a Databricks cluster or in dbt before anyone runs it. I built most of the retrieval, and several of the checks and the recovery logic in the review. The dbt lineage step is all mine, from the idea to the ablation I used to choose its design. The diagrams mark each piece I built or reworked.

The agent’s seven stages, and where my work sits

Each label opens the section on my work in that stage, with what the change measured against the same run without it.

Retrieval picks the few tables the LLM sees out of hundreds

Code review

  1. 1Analyze the ticket (the team’s)
  2. 2Find candidate tables (I built this stage)
  3. 3Follow dbt lineage (I built this stage)
  4. 4Check against the warehouse schema (I built this stage)
  5. 5Rank candidates with an LLM (I reworked this stage)
  6. 6Draft a design (I reworked this stage)
  7. 7Write and review the code (I reworked this stage)

The agent’s stages: I built, I reworked, The team’s

The agent is a multi-agent LangGraph system in a supervisor and worker layout. A ticket passes through five teams in order: research, requirement analysis, design, test data and code. The diagram above follows the same path and zooms in where I worked: its table-finding stages all sit inside research, and the code team writes and reviews the code.

Each team is a sub-graph whose supervisor hands work to its worker nodes. Supervisors route with a fixed table, not an LLM, which keeps a run repeatable and lets every worker be tested on its own.

Most of my work is in research, which decides what the later teams see, and in the review at the end of the code team’s stage, which decides what ships. Research reads from a graph of the customer’s catalog: its tables, their columns and the lineage between them (which table is built from which). I built much of that graph retrieval with the team.

How it finds the tables

Retrieval works like a funnel: it gathers every table that could matter from several sources, then narrows them in steps that each remove one kind of mistake. Cheap, deterministic steps run first, and the LLM ranks only what survives them. Every step has a fallback, so one failing service never ends a run.

The research stage

Tables

  1. Gather candidates:
  2. Drop tables the warehouse doesn’t have: schemas cached for later (I built this)
  3. An LLM ranks the rest: keeps scores of 70 and up; lineage tables restored (I reworked this)
  4. Fetch schemas and sample rows: PII masked per project (I built this)

Code and documents

  1. Attachments chunked, then selected by BM25 within each file (I built this)
  2. Repo files from a cached BM25 index (I built this)
  3. An LLM ranks the files: keeps scores of 65 and up (I built this)

Both rows end in

  1. One research prompt: within the context budget (the team’s)

Each step removes one kind of mistake before the next, more expensive step runs.

I builtI reworkedThe team’sUnderlined opens its section

The candidates come from three sources: the ticket’s own words, a search by meaning, and the inputs of a dbt model the ticket names. I use all three because each misses something the others catch. I let the combined list run long on purpose, and the later steps narrow it.

Following the lineage

I added the lineage step after one ticket that named only a report’s dbt model. Nothing in the ticket’s words pointed at the table it needed, but the model’s own SQL did: a dbt model names every table it reads through ref() and source() calls, and those inputs are its lineage.

The ticket that led to the lineage step

Before: search and the ticket’s words alone

  1. The ticket names only a report’s dbt model (before the lineage step)
  2. Search returns 219 candidate tables: the needed table is 90th (before the lineage step)
  3. The ranker drops it, and the agent joins the wrong table (before the lineage step)

Now: whenever a ticket names a model

  1. Parse that model’s SQL with sqlglot: a SQL parser reads its ref() and source() calls (I built this)
  2. Follow the lineage graph one hop to the tables it reads (I built this)
  3. Add them to the candidates: at most 12 tables, with no LLM call (I built this)

Search ranked the needed table 90th of 219 candidates; the named model’s SQL reads it directly.

I builtBefore the lineage step

Ways to find the tables a named model reads
DesignWhat happened
Do nothingThe ranker keeps dropping tables no word in the ticket points at
Search the repo for files like the ticket and add their tablesA search always has a best match, so it fired on almost every ticket: 87 of 99, adding 126 tables no answer wanted, against 27 for lineage
Parse the model the ticket names and follow its inputs ShippedFires only when a ticket names a model, and adds what that model reads

A table in the candidates can still be dropped by the ranker, so I tested four ways to hand lineage tables to it.

Four ways to hand lineage tables to the ranker, missed tables on 103 tickets. This is the ablation run; the headline 79 to 24 is a separate before-and-after run on the same tickets.
VariantMissed tables
No lineage tables71
Tell the ranker what the model reads41
Put back lineage tables the ranker dropped25
Both Shipped20

I shipped both: telling the ranker is enough on 93 of the 103 tickets, and putting tables back catches the 10 where the ranker ignored the hint. The headline figure comes from a separate run on the same tickets, before and after the whole change: missed source tables went from 79 to 24, about 70% fewer, and no ticket lost a table it needed.

Semantic catalog search on Pinecone

For Iceberg tables in a Polaris catalog (an open table format and its catalog service), the agent had only keyword matching, and a first attempt at similarity search took about 14 s a query. I built a semantic search path on Pinecone, a vector database, behind the same interface as the Databricks path:

  • One index namespace per warehouse, catalog and schema, so a search covers exactly the schemas a project uses and two warehouses never mix.
  • Each table’s embedding weights its name 3 to 1 against its columns, matching how the Databricks path embeds, so results from the two paths rank alike.
  • Indexing is incremental: each table’s schema is hashed, so only changed tables are re-embedded.
  • If embedding fails, the search falls back to keywords, and an unreachable catalog is skipped.

On 188 queries from real tickets, recall@10 was 0.68 against 0.54 for Databricks Vector Search, and mean latency 0.18 s against 4.0 s.

Moving two stages to a smaller model

Retrieval and drafting ran on a larger model at high reasoning effort. I moved both to a smaller reasoning model, rewrote their prompts and set reasoning effort for each model tier separately, because the model that writes code rejects the lowest setting.

Over five runs of 102 tickets, recall was 0.931 on the larger model and 0.944 on the smaller, within the 0.012 spread between runs, and the two stages became 7.6 times cheaper. Effort also sets latency: one ranking call took 31 s at high effort and 4 s at low.

Checking the code it writes

The code team reviews every draft before it ships. I built several of the checks and the logic that decides what ships when every draft fails.

The code stage’s review loop

Each draft

  1. Write the code: then fix what can be fixed mechanically (the team’s)
  2. Six checks in parallel:
    • Syntax and runtime, with AST lint rules for Databricks (I reworked this)
    • dbt sources match what the repo declares (I built this)
    • Requirements met, judged by an LLM (I reworked this)
    • Three more: output, refs and joins (the team’s)
  3. When a check fails: Regenerate with the errors: up to two times, then reviewed again (the team’s)
  4. all pass: Ship it (the team’s)

If every draft fails the syntax and runtime check

  1. One recovery attempt with each draft’s errors, grouped: told to change approach (I built this)
  2. reviewed: The six checks run once more (the team’s)
  3. still fails: Ship the draft with the fewest kinds of failed checks, never an empty one (I reworked this)

A failed draft is regenerated and reviewed again, at most twice. When every draft has failed, one recovery attempt is reviewed like the others before anything ships.

I builtI reworkedThe team’s

What I changed in the review, and what happened before
CheckBeforeNow
Lint rules for code that parses but fails on a clusterA draft that parsed could still fail on the cluster: pyspark.sql.functions helpers that don’t exist, or syntax the cluster’s Python 3.11 rejectsEach such failure became a rule that matches on the syntax tree (AST). A rule stays quiet when unsure, because a false alarm sends a correct draft back
dbt sources the repo declaresThe LLM guessed source names differently on each run, and dbt failed to parseThe prompt lists the exact source() call for every declared table, and a check rejects any other
Objections from the LLM checkAn objection vanished when the LLM reworded it, and contradictory requirements drove drafts back and forthEach objection gets an identifier the next round must rule on, and contradictory requirements are reported once
When every draft failsThe agent shipped the latest, broken draftOne more attempt with every draft’s errors and an instruction to change approach. If that fails too, the draft with the fewest kinds of failed checks ships

Smaller pieces of retrieval

Checking against the warehouse

Some candidates named tables that don’t exist: misspellings, guesses, or one table name tried under several catalogs when only one of them holds it. Before the LLM ranks anything, a check fetches each candidate’s schema and drops anything the warehouse doesn’t have.

The check is cheap because the agent needs those schemas anyway: they’re cached by full name and reused when the kept tables load. If the warehouse can’t be read, the check passes every candidate through. Wrong tables in context fell from 8.6% to 5.3% on 95 tickets, with recall about the same (0.965 to 0.969).

Searching the code repo

Existing code shows the model how a team writes SQL. GitHub’s code search returned fewer results for more keywords and hit rate limits at random, so I replaced it with a BM25 (keyword ranking) index per repo, cached by commit: a search takes under 1 ms and makes no API calls.

An LLM then scores the best matches, and the files it keeps share one budget of lines instead of a fixed snippet each. If the ranker fails, the BM25 files are kept; if it rejects every file, none are.

Fitting the context

Every source has a budget, so one large attachment can’t crowd out the tables.

What each source may add to the research prompt
SourceLimit
Attachments, anything the ticket names, whole; the rest ranked by BM25 within its own file60,000 characters ranked, 240,000 at most
Lineage tables, the tables a named model reads12 tables per ticket
Candidate tables, those the LLM ranker keeps, and any lineage table it droppedA score of 70 or more
Repo files, the top 20 BM25 matches that an LLM scores 65 or more2,000 lines shared, at least 80 per file
The whole prompt100,000 tokens

Truncated attachments raise no error: a requested table once arrived with 48 of its 117 columns, and a partial list reads like a complete one. So I cut files along their own structure, a CSV at record boundaries and a catalog into one table per chunk, and a note at the end names every file that arrived incomplete.

The agent also sees a few sample rows per table. I sample them ahead of time from customers’ Databricks tables, and each project can turn on Presidio to mask personal data.

How I measured it

Each benchmark is built from real tickets with a known list of the tables each needs. The benchmarks ran at different times on different builds of the agent, and the ticket set changed between them (95 to 103 tickets), so each result is compared with its own run’s baseline.

The agent’s Langfuse traces (the record of each run) dropped spans from worker threads and failed steps. I fixed that, so every run can be read back afterwards.

Results, each against its own run’s baseline
ChangeMetricBeforeAfterSample
Following dbt lineageMissed source tables, about 70% fewer7924103 tickets
Catalog search on Pinecone, against Databricks Vector SearchRecall@100.540.68188 queries from real tickets
Mean latency, about 20 times faster4.0 s0.18 s
Schema check before rankingWrong tables in context, about 40% fewer8.6%5.3%95 tickets
Recall0.9650.969
Two stages on a smaller modelRetrieval recall0.9310.944Five runs of 102 tickets
Cost of the two stages, 7.6 times cheaper7.6×1×

What this doesn’t show

  • The numbers here measure retrieval. For the review I describe the design, and I didn’t measure whether the generated code got more correct end to end.
  • Lineage follows one hop, so tables two models away still depend on search.