Enterprise Data Asset Retrieval for Autonomous Coding Agents
Machine LearningModel answerLast updated
Design a multi-stage retrieval system that surfaces the right database tables and analytical notebooks for an internal AI coding assistant answering data queries.
An enterprise is building an internal LLM-powered coding agent capable of answering data-oriented questions (e.g., "Why did user retention dip in Q3?" or "How do we calculate net ARR?") and writing execution-ready SQL or Python scripts.
To answer these queries accurately, the agent needs to retrieve the relevant technical context from the organization's data platform—specifically database tables and jupyter/analytical notebooks.
Design an enterprise retrieval and reranking system that surfaces the most relevant data assets to the downstream coding agent.
Your design should address the following four key components:
- Asset Indexing & Representation: How to represent, enrich, and chunk tables and notebooks (combining structured metadata, schemas, execution logs, and textual documentation) to bridge the semantic gap between non-technical user queries and technical asset identifiers.
- Multi-Stage Retrieval & Reranking Architecture: How to implement a hybrid candidate generation layer (sparse + dense) combined with a cross-encoder reranker, including training label strategy and latency constraints.
- Quality Filtering, Freshness, & Permissioning: Mechanisms to handle low-quality artifacts (e.g., ad-hoc scratchpad notebooks, duplicate tables, stale schemas, or deprecated data assets) and strict security/permission filtering.
- Evaluation & Metrics Framework: Metrics for evaluation across the entire lifecycle, from stage-specific retrieval metrics (Recall@K, MRR) to downstream LLM code-generation accuracy and online performance monitoring.
Hints
Hint 1
Bridge the vocabulary gap between business concepts and technical schema names by synthesizing descriptions using an LLM or mining query logs.
Hint 2
Use a two-stage retrieval pipeline: lightweight hybrid search (BM25 + Dense vector embeddings) for broad candidate generation, followed by a heavier cross-encoder reranker.
Hint 3
Apply quality scores (e.g., query volume, upstream pipeline health, explicit deprecation flags) as hard pre-filters or soft rank modifiers to handle scratchpads and stale assets.
Hint 4
Ensure strict security compliance by applying permission-based access control filters directly during candidate retrieval or pre-filtering.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
System Overview
The goal is to design an enterprise search and retrieval engine that maps a user's natural language question to the most relevant database tables and analytical notebooks, passing these assets as context to a downstream coding agent.
+-----------------------------------------------------------------------------------+
| OFFLINE/ASYNC INDEXING |
| |
| Data Catalog / +--------------------+ +------------------+ +---------+ |
| Metastore / Logs | Doc Builder & |--->| Dense Embedder |--->| Vector | |
| - Table Schemas | LLM Summarizer | | (e.g., BGE/E5) | | DB | |
| - Notebooks (.ipynb) | +------------------+ +---------+ |
| - Query Logs | (Structured Text) | +------------------+ +---------+ |
| - Lineage/Owner +--------------------+--->| Inverted Index |--->| BM25 | |
| | (Elasticsearch) | | Engine | |
| +------------------+ +---------+ |
+-----------------------------------------------------------------------------------+
+-----------------------------------------------------------------------------------+
| ONLINE QUERY PIPELINE |
| |
| User Query --> [ Permission & Quality Filter ] |
| | |
| v |
| +------------------------------+ |
| | Stage 1: Hybrid Candidate | (Top ~100 Candidates) |
| | Retrieval (BM25 + Vector) | |
| +------------------------------+ |
| | |
| v |
| +------------------------------+ |
| | Stage 2: Cross-Encoder | + Usage / Quality / Lineage Features |
| | Reranker | |
| +------------------------------+ |
| | |
| v |
| Top 5-10 Ranked Assets --> Downstream LLM Coding Agent |
+-----------------------------------------------------------------------------------+
1. Asset Indexing & Representation
Raw schema names (tbl_usr_act_v2) and unformatted .ipynb files suffer from a vocabulary mismatch when matched against business queries like "What is our quarterly retention rate?". We must construct enriched document representations for both asset types.
Asset Chunking and Document Construction
A. Database Tables
For every database table, assemble a structured text document comprising:
- Structural Attributes: Fully qualified table name (
db.schema.table_name), database layer (e.g.,gold,raw), table owner, and creation date. - Schema Details: Column names, data types, standard column comments, and primary/foreign key relationships.
- SQL Query Logs Context: Extract historical query activity from the past 90 days. Parse aggregate usage patterns including common
WHEREpredicates, frequentJOINconditions, and standard metric calculation snippets. - LLM-Enriched Summary: Run an offline batch job using an LLM to generate an overview based on schema details, column distributions, and top executed SQL queries.
B. Jupyter Notebooks (.ipynb)
Notebooks contain interleaved markdown cells, code blocks, output traces, and metadata.
- Structural Parsing: Parse out execution count, output cell blobs, and boilerplate setup imports.
- Contextual Chunking: Pair each markdown cell with its directly following code block. Apply sliding window chunking (~512 tokens with 20% overlap) to maintain block-level continuity.
- Global Metadata & Abstract: Generate a global summary containing the notebook title, owner, imported data tables (parsed via AST), and a high-level overview generated by an LLM.
Index Freshness & Synchronization
- Event-Driven Updates: Listen to metastore and catalog events (e.g., OpenMetadata, AWS Glue, Unity Catalog via Kafka) to update schemas, additions, or deprecations immediately.
- Daily Aggregation Pipelines: Recompute table usage counters, query log features, and notebook execution histories every 24 hours.
- Triggered Re-summarization: Trigger LLM document re-generation only when schema structure alters significantly or underlying code updates.
2. Multi-Stage Retrieval & Reranking Architecture
To guarantee strict low-latency constraints (<300 ms) while maintaining high recall, we employ a standard multi-stage retrieval architecture.
[ User Query ]
|
v
+---------------------------+
| Permission & Hard Filter | <-- ACL Masking, Deprecated Assets Out
+---------------------------+
|
v
+---------------------------+
| Stage 1: Hybrid Retrieval | <-- BM25 + Vector Search (Top ~100)
+---------------------------+
|
v
+---------------------------+
| Stage 2: Feature Reranker | <-- Cross-Encoder + Metadata Feature Fusion
+---------------------------+
|
v
+---------------------------+
| Top K (5-10) to Agent |
+---------------------------+
Stage 1: Candidate Generation (Hybrid Search)
- Keyword Search (BM25): Index full technical descriptions, raw schema names, and exact column identifiers. Field boosting is applied (
table_name^3.0,column_name^2.0,summary^1.0). - Dense Vector Search: Use a domain-adapted bi-encoder model (e.g.,
bge-large-en-v1.5) fine-tuned on company data concepts to index semantic embeddings of asset documents. - Score Fusion: Combine top results from both methods using Reciprocal Rank Fusion (RRF): $$\text{RRF_Score}(d \in D) = \sum_{m \in {\text{BM25}, \text{Dense}}} \frac{1}{k + r_m(d)}$$ (where $k=60$ and $r_m(d)$ is the rank position in retriever $m$)
Stage 2: Reranking & Feature Integration
Top 100 candidates from Stage 1 pass to a fine-tuned Cross-Encoder model (e.g., ms-marco-MiniLM-L-6-v2 or bge-reranker-large).
The final score blends the semantic cross-encoder logit with static quality and context signals using a GBDT (Gradient Boosted Decision Tree) or lightweight MLP: $$\text{Final Score} = w_1 \cdot S_{\text{cross_encoder}} + w_2 \cdot \log(\text{Query Count} + 1) + w_3 \cdot S_{\text{freshness}} + w_4 \cdot S_{\text{quality}}$$
Training Data Strategy
- Implicit Feedback: Extract query-to-asset pairs from historical developer sessions (e.g., user asks a question $\rightarrow$ agent writes SQL referencing
table_A$\rightarrow$ user runs query successfully without edits $\rightarrow$ positive pair). - Synthetic Pair Generation: Prompt an LLM with table schemas and notebook chunks to generate realistic business questions that each asset would satisfy.
- Hard Negatives: Mine negative samples from top Stage 1 hybrid retrieval results that were not selected by users or downstream SQL execution steps.
3. Handling Noisy Assets, Quality Signals, & Security
Enterprise data systems often contain temporary tables, abandoned experimental notebooks, and duplicate schemas.
Quality Signals & Filtering Taxonomy
| Signal Type | Metric / Source | Action / Usage |
|---|---|---|
| Deprecation Tag | Explicit metastore flags (is_deprecated = true) | Hard Filter: Exclude immediately from retrieval. |
| Access Control (ACL) | User role permissions & database grants | Hard Filter: Applied pre-retrieval or via vector DB payload filters. |
| Data Platform Tier | Catalog environment (gold vs silver vs dev/sandbox) | Rank Boosting: Preference given to production (gold) tables. |
| Query Volume | 90-day execution count from query logs | Soft Rank Feature: Scaled log transform added to reranker. |
| Freshness / Activity | Days since last DML update or notebook commit | Soft Decay: Exponential decay factor $e^{-\lambda \cdot t}$ applied to score. |
| Deduplication | Near-identical schemas or cloned notebook content | Clustering: MinHash / LSH on schemas to collapse duplicates into a primary canonical asset. |
Resolving Description vs. Content Discrepancies
When written metadata contradicts physical schema layout (e.g., column labeled user_id storing encrypted UUID hashes), physical execution statistics take precedence:
- Automated profiling metrics (null percentages, cardinality ratios, sample values) override manual column comments.
- Verified automated query logs supersede outdated manual documentation.
4. Metrics & Evaluation Framework
Evaluating retrieval performance requires assessing both intermediate retrieval stages and downstream agent task completion.
+-------------------------------------------------------------------------------+
| EVALUATION PIPELINE |
| |
| +--------------------------------+ +--------------------------------+ |
| | Stage 1 & 2 Retrieval | ----> | Downstream Agent Performance | |
| | | | | |
| | - Recall@100 (Candidate Gen) | | - SQL Syntactic Correctness | |
| | - MRR & NDCG@10 (Reranker) | | - Code Execution Pass Rate | |
| +--------------------------------+ +--------------------------------+ |
+-------------------------------------------------------------------------------+
Component-Level Retrieval Metrics
- Recall@100 (Stage 1): Measures the percentage of true relevant assets surfaced in candidate generation.
- MRR (Mean Reciprocal Rank) & NDCG@10 (Stage 2): Evaluates if the most appropriate table/notebook appears at top positions (ranks 1–3).
Downstream Agent Metrics
- Code Execution Pass Rate: Percentage of generated SQL queries/Python scripts that execute without runtime syntax or schema errors.
- Data Context Precision: Ratio of schema columns referenced in generated code that were actually necessary for the task.
- End-to-End Task Success (LLM-as-a-Judge): Automated evaluation comparing agent outputs against expert gold-standard query answers.
Online Monitoring & Guardrails
- Zero-Recall Rate: Tracks queries returning zero candidates above threshold.
- Latency Budget Monitoring:
- Stage 1 Hybrid Search: $< 50\text{ ms}$
- Stage 2 Cross-Encoder Reranking: $< 150\text{ ms}$
- Downstream Code Generation: $< 2000\text{ ms}$
- Fallback Strategy: If top reranked scores fall below a minimum relevance threshold, the system prompts the user for clarification before sending low-confidence assets to the coding agent.