Natural Language over Governed Data
Design an assistant that answers business questions in plain language without letting the model decide what a metric means: governed definitions first, SQL checked as a tree, read-only execution and answers checked against the data.
- Kind
- Case study
- Level
- Core
- View
- Interview prep
- Sections
- 4
- By
- Sourav Banerjee
- Last updated
- 20 Nov 2026
Practise this as a worksheet: Natural-Language-to-SQL Analytics Assistant
Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.
Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.
Case brief
The case in one line: pin every business question to an owner-approved metric first, so valid SQL can never answer the wrong question.
30-Second Cheat Sheet
- The product: executives and analysts ask a business question in plain words ("What's Q3 revenue?") and get a number they can put on a slide.
- The easy part: generating SQL. The hard part: meaning.
- The trap: "revenue" can be booked, recognised or collected. Valid SQL can answer the wrong one, and the number still looks plausible.
- The anchor: a versioned, owner-approved metric in the metric registry, before any physical schema is exposed.
- Ambiguous term? Ask the user or route to an analyst. The model never picks the definition.
- SQL is a proposal: parsed against policy and a scan budget, then run by a read-only gateway under row and column security.
- The answer carries SQL, lineage and freshness; prose is checked against the numbers; every run is audited and replayable.
- Scope: one slice (question → approved metric → read-only query with a paper trail), not "chat with every table".
1. Answer the business question the user means
The situation today
- Executives and analysts want a slide-ready number from a plain-words question.
- Today an analyst hand-translates each question into SQL, runs it and sanity-checks the result.
- Often it's the same handful of questions every week.
SQL = Structured Query Language, the language used to query warehouse tables.
Why meaning is the hard part
- "Revenue" can mean booked, recognised or collected revenue.
- A model can write perfectly valid SQL that answers the wrong one.
- That failure is more dangerous than an error message: the query ran, the chart rendered and the number looks plausible.
- The model can't choose that definition on the business's behalf.
The terms that carry the whole case
| Term | Meaning |
|---|---|
| Semantic layer / metric registry | The store of business definitions. Each metric has an approved definition, allowed dimensions and grain, a named owner and a version. |
| Grain | The level of detail, such as daily or per customer |
| KPI | Key performance indicator: one of the numbers the business watches to judge success |
| AST | Abstract syntax tree: a query parsed into its structure, so a checker sees which tables, columns and joins it really touches |
| RLS / CLS | Row-level and column-level security: warehouse rules deciding which rows and columns a given user may see |
| Golden case | A reviewed test pairing a question with its approved SQL and expected result shape |
| LLM | Large language model |
| Lineage | Where each number came from |
The design in brief
- Anchor every question to a versioned, owner-approved metric before exposing any physical schema.
- A term with more than one approved meaning → ask the user or send it to an analyst.
- The LLM proposes SQL.
- A parser checks the query tree against policy and a scan budget.
- A read-only gateway runs it under the warehouse's row and column security.
- The answer carries SQL, lineage and freshness.
- The prose is checked against the numbers.
- Every run is audited so it can be replayed later.
The core idea: the metric registry defines the business answer, and the LLM only translates the question and explains a validated, read-only result.
business question → pin a governed metric → one approved meaning?
- No → clarify with the user, or analyst review.
- Yes → check the SQL and scan cost → read-only answer with lineage.
2. Follow "What's Q3 revenue?" through the system
- The source traces one executive question end to end.
- Each step is a separate check, and each can stop the request.
- Identity first. Resolve who the executive is and which rows they may see, before looking at any schema or data.
- Pin the metric. "Revenue" → Finance's versioned metric, not a guess about which column looks right.
- Unclear? Don't pick. Is an "active customer" 30-day or 90-day activity? Ask, or send it to an analyst.
- Generate, parse, cap, run. Generate SQL, parse it, cap the scan, then run it read-only.
- Return with evidence. The number plus SQL, lineage and freshness. Any prose summary is checked against the numbers in the result.
- Replay next quarter. Who asked, which metric version answered and which SQL hash ran.
- The path: metric first → permitted SQL → a bounded run → an explanation built from the result.
- Out of it: writes and invented KPIs.
- The human boundary sits in two places:
- Metric owners decide what a word means.
- Analysts take questions the system can't resolve, and explanations that are board-facing or would trigger an action.
3. What you need to design
The task
- Design a governed natural-language interface to business data.
- The dangerous constraint comes first: valid SQL must never answer the wrong business question.
- This slice: map the question to an approved metric and run a read-only query with a paper trail.
- Not covered: "chat with every table".
One query path, four cases
- The same governed query path anchors three related cases.
- Learn it once. Each variant changes the final explanation and the review workflow, not the query path.
| Case | Shared foundation | What changes |
|---|---|---|
| NL-to-SQL analytics assistant | Governed metric → permitted schema → validated read-only query | General business questions and SQL safety |
| Executive Dashboard Assistant | Same metric registry and query evidence | KPI variance narrative, dashboard freshness, analyst escalation |
| Retail Demand Forecast Explainer | Same governed evidence and result checks | Deterministic driver statistics from sales, promotions, inventory, weather and events; human review of planning actions |
| Insurer governed data assistant | Governed metric views and auditable asset resolution | A supervisor routes to a managed text-to-SQL service, a narrow SQL/RAG worker, deterministic analysis or visualisation; later, specialised domain agents |
What each source contributes
| Source | Contributes |
|---|---|
| Anchor case | Design, requirements, validation, failure drills, evaluation, rollout and delivery |
| Executive Dashboard Assistant | Executive persona, variance explanation, the escalate-to-analyst rule |
| Retail Demand Forecast Explanation Assistant | Planner persona, driver attribution, the correlation-versus-causation risk |
| Insurer engagement ("From Supervisor to Deep Agent") | Governed metric views, the managed text-to-SQL vs multi-tool worker split, the clarify-below-60% gate and the project story (in the deep dives) |
| A self-drill | The cost pivot (in the full casebook's Practice) |
Who it's for
- Engineers preparing for Forward Deployed, solutions or applied-AI interviews.
- Especially a round asking for a natural-language-to-SQL or analytics assistant.
What it assumes you know
- SQL and data warehouses
- Row and column access control
- LLM prompting and evaluation
By the end you should be able to
- Explain the system end to end at interview depth, starting from the wrong-answer risk.
- Answer follow-ups on:
- Metric ownership
- Ambiguity handling
- SQL validation
- Read-only execution
- Evaluation
- Cost and rollout
How the sections divide the work
- Design walkthrough: the spoken answer; it stands on its own. Read it first.
- Technical deep dives: SQL validation, the failure drills, evaluation detail, the insurer engagement and cost.
- Practice (full casebook): practise without the page open.
- Quick review: the card for the night before.
- The source also links a separate "Natural-Language-to-SQL Analytics Assistant" worksheet. It isn't imported here; the full casebook's practice prompt covers the same task.
Quick Recall: Lines to Say in the Interview
- "Generating SQL is the easy part; meaning is the hard part."
- "Valid SQL that answers the wrong question is worse than an error, because the number looks plausible."
- "The metric registry defines the answer. The LLM only translates the question and explains a validated result."
- "If a term has two approved meanings, I ask or route to an analyst. The model never picks."
- "Identity and row permissions resolve before any schema or data."
- "Every answer ships with its SQL, lineage and freshness, and every run can be replayed."
- "Metric owners decide what a word means; analysts take what the system can't resolve."
Design walkthrough
The goal: a governed, read-only analytics assistant where the metric registry defines the answer and the LLM only translates the question and explains a validated result.
30-Second Cheat Sheet
- Open with the risk: valid SQL for booked revenue when Finance expects recognised revenue. The query succeeds and nobody gets an error.
- Three controls from release one: a semantic layer, a read-only, cost-bounded warehouse boundary, and an explicit "I don't know which definition you mean".
- Correctness dominates: a fast, confidently wrong answer is the worst outcome. Ask, narrow or refuse beats guessing.
- Registry before schema: resolve a named, versioned metric before touching any physical table.
- Ambiguity gate with a number: the insurer's clarify node fires below 60% (an example, not universal).
- SQL is an untrusted proposal: AST policy check, scan budget, read-only gateway, on-behalf-of execution, entitlements rechecked.
- Fail closed on policy, degrade on everything else. Never swap in an unrestricted service account.
- Release gate = semantic correctness, not execution success. Roll out ten metrics at a time.
Short answer to "What are the requirements?" (source's version): "Functionally, pin the metric, generate checked read-only SQL, and explain from the result. Non-functionally, warehouse ACLs, scan budgets, 3 to 8 second interactive asks, and a replayable query-run record."
1. Name the wrong-answer risk before drawing anything
The risk
- A model generates valid SQL for booked revenue when Finance expects recognised revenue.
- The query succeeds. The executive gets the wrong number with no error to warn them.
- So the design needs a governed definition and a check that the query implements it, as well as SQL generation.
The reframe: governed decision support
- The assistant translates questions into business definitions that named owners have approved.
- Three controls from the first release:
- A semantic layer of governed metric definitions.
- A safety boundary around the warehouse that is read-only and cost-bounded.
- An explicit way to say "I don't know which definition you mean" instead of guessing.
Three graded answers
| Answer | What it does | What it misses, or proves |
|---|---|---|
| Weak | LLM writes SQL against the schema and runs it | Who owns metric definitions; allows an unapproved reading of revenue; no AST validation, no cost bound, no way to notice a confident wrong answer |
| Average | Adds a semantic layer, validates before running, executes read-only with row limits, logs every query | Never says what happens when the question is ambiguous, the schema drifts, or the prose disagrees with the table |
| Strong | Consults the metric registry before any physical table; turns ambiguity into a clarifying question; parses SQL into a tree and checks policy and a scan budget before a read-only gateway sees it; re-checks entitlements at execution | Proves the design on ten governed metrics with golden cases before any executive sees output |
Non-goals (the scope fence)
- Users can't author write queries or modify data.
- It answers a governed set of business questions. It's not a general exploration tool for every warehouse table.
- It doesn't define what "revenue" means. The business decides; the semantic layer records it; the assistant never decides it on the fly.
2. Ask the questions that change the design
- Ask before sketching a box. Each answer decides a component.
The interview-guide version
| Question to ask | What it's really asking | What you then decide |
|---|---|---|
| Who owns "revenue", "active customer" and the other first ten metrics? Is a semantic layer already approved? | If Finance means recognised and Sales means booked, who wins? Or does that dictionary exist? | Registry scope, owners, wire to an existing layer or build one |
| Which warehouse, dialect and approved datasets are in scope? | Snowflake over approved finance views, or every table in the lake? | SQL generator, catalog adapter, parser and policy rules |
| Where are row and column permissions enforced today? | If a regional manager asks for all salaries, does the warehouse already hide those rows? | Reuse warehouse ACLs, or build the missing layer |
| When a term maps to two metrics or grains: clarify, refuse, or send to an analyst? | "Active customer" as 30-day or 90-day: ask, refuse, or hand it over? | Ambiguity gate and review queue |
| What are the latency and scan-cost limits? May large requests run async? | A question scanning a year of events: block, queue, or blow the warehouse bill? | Query budget, timeouts, cache and async queue |
| Must users see SQL, lineage, freshness, and a reconstruction of past answers? | Next quarter, can we prove which SQL and metric version produced last month's board number? | Response format and the append-only QueryRun record |
| Which explanations are board-facing or action-triggering? | FYI chart, or will someone change prices from this answer? | Extra checks and the human-review line |
ACL = access control list: who may see or change a thing.
The full design's version
- Two of its questions are worth adding: how often definitions change and who approves a change, and which ten metrics matter most.
| Question to ask | What the answer decides |
|---|---|
| Who owns each metric definition, how often do definitions change, who approves a change? | Whether a metric registry exists as a product; the named owner per domain |
| Is there already a semantic layer or metrics catalog, or must we build one? | The largest single scope decision in the project |
| Which SQL dialects and warehouses are in scope? | Generation and validation breadth; one dialect or many |
| Tolerance for latency vs cost? Sync, or async and cached? | Where the sync/async boundary sits |
| Is row- and column-level security already enforced by the warehouse, or would the assistant reimplement it? | Reuse or rebuild authorisation; rebuilding is the classic bug |
| When unsure: ask, refuse, or escalate to an analyst? | The ambiguity gate's three modes |
| Which ten metrics matter most, and what does "revenue" mean: booked, recognised or collected? | The MVP scope and the first golden cases |
| What audit evidence must exist to reconstruct why a number was produced? | The query-run record's schema |
MVP = minimum viable product: the smallest version real users actually use.
Map the people
- Four groups want different things, and the architecture must satisfy all of them at once.
- That tension is why the semantic layer and the policy and cost validator are first-class components, not afterthoughts on a chat UI.
| User | Wants | Failure they notice first | What the assistant gives them |
|---|---|---|---|
| Executive | Fast, correct answers, never "let me check with analytics" | A plausible number with the wrong definition | Governed answers with the definition shown, variance explained, uncertain cases escalated |
| Analyst | Repetitive definitional lookups off their plate, no invented interpretations | The assistant redefines a metric they maintain | Golden cases they review; escalation queue; analyst stays source of truth during shadowing |
| Data / platform engineer | Bounded blast radius: no whole-warehouse scans, no restricted-column leaks, no budget blowups | One ambiguous question exhausting concurrency | Read-only gateway, scan budgets, warehouse-native policies reused |
| Metric owner | One versioned definition every consumer shares | Two answers to one question | The registry as the single artefact, with approval on change |
Two more personas (from the practice worksheets)
- Executive Dashboard Assistant user: asks KPI questions; the assistant maps to governed metrics, retrieves dashboard and data context, explains variance, cites definitions, escalates uncertain answers to analysts.
- Retail Demand Forecast Explanation Assistant user: a planner reviewing forecast variance who asks why demand changed. The assistant explains drivers from sales history, promotions, weather, inventory and events, and recommends planning actions a person reviews.
- Neither changes the architecture. Both add a variance-explanation step after the query (step 9).
3. State requirements as testable constraints
Correctness dominates
- A fast, confidently wrong answer is the single worst outcome: the executive can't tell it's wrong.
- So the system trades latency for safety every time.
- Asking, narrowing scope or refusing all beat guessing.
- Depth on ten metrics beats shallow coverage of the whole warehouse.
Functional must-haves (one pipeline, in order)
- Resolve to a governed metric first, before any physical schema.
- Retrieve only the permitted tables, joins and freshness context needed, never the whole schema.
- Detect ambiguity and ask, never silently pick between two approved meanings.
- Produce dialect-specific SQL from the narrowed context only.
- Parse into an AST and enforce policy against the tree, not the text: tables, columns, joins, query shape, estimated scan.
- Estimate cost and execute read-only, with limits, through a gateway.
- Return the result with the exact SQL, metric lineage and caveats such as snapshot staleness.
- Generate prose from the structured result and check it against the numbers.
- Audit each run: actor, decision, SQL hash, bytes scanned, and the metric, schema and policy versions used.
- The source's must-have pipeline figure: question → resolve governed definition → retrieve schema + freshness → ambiguous? (yes → clarifying question) → generate SQL → parse to AST + enforce policy → estimate cost + apply limits → execute read-only → answer with SQL, lineage, caveats.
Should-haves (from the copilot personas)
- Show confidence, missing evidence and the escalation reason when uncertain.
- Collect feedback and reviewer corrections for evaluation, never for ungoverned training.
- Admin controls: source inclusion, freshness thresholds, policy rules, blocked actions, audit export.
- Can wait: richer query planning, human approval for ambiguous cases, learned query ranking, federated sources, semantic search over data dictionaries.
"Good" for the MVP
- Reliably answers ten governed metrics with full lineage and explainability.
- If it can't, it isn't ready to become a general interface to the warehouse.
Non-functional targets (interview guide)
| Requirement | Example target / constraint |
|---|---|
| Correctness | Outranks speed; valid SQL for the wrong metric still fails |
| Security | Warehouse-native row/column policies and entitlements on every execution |
| Fail-closed | A policy failure or suspicious scan doesn't run |
| Latency | Interactive 3 to 8 s; longer work async and visible |
| Cost guards | Row limits, timeouts, date windows, scan budgets |
| Operability | Versioned metric/schema cache with TTLs; narrow credentials; redacted logs |
TTL = time to live: how long a cached item stays valid.
Constraints stated so a test can fail them (full design)
- The 3 to 8 second figure comes from the copilot personas: an example to confirm with the customer.
| Constraint | Stated so it can be tested |
|---|---|
| Correctness | A fast, confidently wrong answer is the worst outcome; trade latency for safety every time |
| Latency | User-facing path synchronous; anything that only improves future answers → background queues. Interactive 3 to 8 s for copilot personas; longer workflows async with progress state |
| Security | Read-only identity reaching only approved datasets; warehouse-native row/column policies reused, not reimplemented. SSO, encryption in transit and at rest, secrets management, no training on customer data unless the contract allows |
| Compliance | Append-only query runs: actor, SQL hash, policy decision, bytes scanned, schema and metric versions |
| Reliability | Fail closed on policy evaluation, planner timeouts and suspicious scan volume. Degrade on formatting or explanation failures |
| Cost | Scan budgets, row limits, timeouts, bounded date windows: an unbounded query is a reliability problem as well as a bill. Token budgets and small models for routing |
SSO = single sign-on: one company login, and the source of the user's identity for permissions.
Give every requirement an owner
- A requirement with no component won't happen.
| Requirement | Primary component(s) |
|---|---|
| Anchor on a governed definition | Semantic metric registry, consulted first |
| Retrieve only what's needed | Schema retriever with catalog cache, TTLs and version stamps |
| Ask rather than guess | Ambiguity check with a confidence threshold |
| Dialect-specific generation from narrowed context | SQL generator, stateless |
| Policy against the tree | AST parser, policy and cost validator |
| Bounded, read-only execution | Read-only execution gateway with the narrowest credentials |
| Answer with SQL, lineage, caveats | Result summariser with cross-check against the table |
| Reconstruct any number | Append-only query-run store, versioned metrics, schema snapshots and policy bundles |
The first release
- Deliberately small: ten owner-approved metrics, golden question/SQL/result cases, and analyst shadow review before a small executive audience.
- Out of scope: a general interface to every table, a write-query tool, a machine that defines business metrics.
Spoken answer: "Functionally, pin the metric, generate checked read-only SQL, and explain from the result. Non-functionally, warehouse ACLs, scan budgets, 3 to 8 second interactive asks, and a replayable query-run record."
4. Give every kind of state one owner
Three kinds of authoritative state
| Truth | Owner |
|---|---|
| Physical schema | Warehouse catalog |
| Business definitions | Semantic metric registry, maintained by metric owners |
| Authentication | Identity provider |
| Access decisions | Policy store |
- Caches (schema snippets, metric lookups, recent plans) are only a performance layer, with TTLs and version stamps so the system can explain what it used.
- A cache owns none of this truth.
The fourth kind: per-request workflow state
- Question interpretation, candidate SQL, its AST, the validation result, the execution trace.
- Short-lived. It must not quietly become hidden durable state.
Every source the assistant may touch
| Data source | Owner | Freshness | Permission model | Risk |
|---|---|---|---|---|
| Warehouse (fact and dimension tables, gold layer) | Data owner | Minutes to daily by table | Warehouse-native row and column security | Join fan-out, unbounded scans, renamed tables |
| Semantic layer / metrics store | Metric owners per domain | Changes on approval | Definition-level ownership, versioned | Two definitions of one word; silent overwrite by another team |
| Warehouse catalog and lineage | Data platform | Crawled on a schedule | Filtered to what the caller may see | Stale join paths after an overnight rename |
| BI dashboards | Dashboard owners | Refresh time per dashboard | Dashboard sharing | Stale refresh presented as current |
| Financial planning, CRM, ERP | Finance and sales system owners | Daily to weekly | Source-system roles | Numbers that disagree with the warehouse |
| Forecasting, POS sales, inventory, promotions, pricing, weather, events (retail persona) | Planning and merchandising | Daily; feeds hourly | Region and store scope | Stale promotions data; correlation read as causation |
BI = business intelligence dashboards. CRM = customer relationship management. ERP = enterprise resource planning (finance, orders, inventory).
Three core records
| Record | Fields | Role |
|---|---|---|
Metric |
id, name, definition, dimensions, owner, version |
The governed definition |
SchemaAsset |
id, engine, object, columns, sensitivity |
A physical object and how sensitive it is |
QueryRun |
id, actor, sql_hash, policy_decision, bytes_scanned, result_ref |
The audit record; also stamps metric, schema, policy, prompt and model versions so a changed number can be reconstructed |
- Persona-specific records are in the lineage and variance deep dive.
Versioning rules (say them aloud: they answer "why did this number change?")
- Retain metric versions long enough to reconstruct why last quarter's dashboard differs from today's.
- Also record the source-data snapshot or as-of time, and keep the result or an approved reproducible reference.
- A metric version and SQL hash explain the requested computation, but can't reproduce the old value after the underlying rows change.
QueryRunis write-once and append-only: incident review and adoption analysis both start from query history.- Version every behaviour-shaping artefact: metric definitions, schema snapshots, policy bundles, generated plans. Without that, the happy path works and rollout fails.
- Idempotency keys on question submission and feedback, so a retried submit doesn't duplicate.
- Optimistic concurrency on metric edits, so one team can't silently overwrite another's definition.
Idempotency key = an ID on a request so a retry is recognised and not processed twice. Optimistic concurrency = an edit succeeds only if the version hasn't changed since it was read.
5. Draw the architecture end to end
- Explain it as a chain of trust boundaries in dependency order, not a flat list of boxes.
- The organising idea: the LLM interprets and explains; the registry, policy, warehouse and analysts keep authority.
The interview-size view
- Governed control plane: versioned metric registry, entitlements and query policy, versioned catalog and lineage.
- Question path: user question → identity + entitlements → LLM-assisted metric resolver → one approved meaning? (no → clarify or analyst review) → permitted schema + freshness → LLM SQL generator on narrow context → parse SQL AST → policy + cost check (fail → deny or narrow) → read-only gateway → warehouse with native RLS/CLS → LLM result summary → numbers match table? (no → table only + review alert; yes → answer with SQL, lineage, caveats) → append-only query run.
One question in eight steps
- Authenticate and resolve entitlements before any schema or data lookup.
- LLM-assisted resolver against the versioned registry. Several supported meanings of "revenue" → clarify or escalate; don't guess.
- Retrieve only the allowed schema, join path, lineage and freshness facts for the selected metric.
- Generate dialect-specific SQL from that narrow context. The model proposes a query; it doesn't approve one.
- Parse into an AST; enforce table, column, join and read-only rules; recheck entitlements; estimate scan cost. Reject or narrow anything unsafe or over budget.
- Execute through a bounded read-only gateway, running as the user (on-behalf-of) so native row/column security applies to them, with timeout and row limits.
- Summarise the structured result and verify every number against the table. Mismatch → table alone + reviewer alert.
- Return definition, SQL, lineage, freshness caveats and answer; record versions, decision and bytes scanned for replay.
Control plane vs data plane
- Control plane: definitions, policies, schedules, evaluation rules. Changes through releases.
- Data plane: handles each question as a request.
- The full design's data-plane path: user → query API (authenticate, identify intent) → authorise entitlements → resolve versioned owner-approved metric → retrieve needed schema behind a freshness gate → ambiguous below threshold? (ask) → generate SQL → parse AST → validate policy + scan budget (reject → deny with reason) → read-only gateway → warehouse enforces RLS and CLS → results masked and summarised → summary cross-checked.
The background lane (never blocks a question)
- Catalog crawler → rate-limited refresh queue → catalog cache with TTL and version.
- Evaluation replay queue → golden-set replay on every change → regression report.
Four operating rules
- Version metric definitions, table/column/join policy, scan budgets, native RLS/CLS, crawl schedules, prompts, models, golden cases and dashboards.
- Recheck entitlement at execution. Narrow credentials, timeouts, row limits, cost estimates; cancel on a budget overrun and return a safe fallback.
- Partition background work by tenant, warehouse and dataset family.
- Append actor, SQL hash, policy decision, scanned bytes, metric version and schema version to every query run. Alert on escaped policy, scan drift and declining trust.
The component view
- Query API, AuthZ and entitlements, semantic metric registry, schema retriever and catalog cache, ambiguity check (asks a clarifying question), SQL generator, AST parser, policy and cost validator (denies with a reason), read-only execution gateway, result summariser.
- Systems of record: identity provider, warehouse catalog, policy store, warehouse, metric registry.
- Async lane: rate-limited metadata refresh queue and evaluation replay queue.
- Every box must answer who owns its state, how fresh it is and why it exists. A box without those answers was premature.
| Component | Responsibility | State owner | Boundary | MVP or later |
|---|---|---|---|---|
| Catalog crawler | Ingest schema, comments, freshness, lineage | Warehouse metadata source | Async background | MVP if warehouse is small; later if manually seeded first |
| Semantic metric registry | Governed metric definitions and allowed grains | Product/data governance | Sync read, async update | MVP |
| Schema retriever | Fetch relevant tables, joins, freshness, permissions | Cache with source-of-record fallback | Mostly sync | MVP |
| SQL generator | Produce dialect-specific candidate SQL | Stateless service | Sync | MVP |
| AST parser | Normalise and inspect candidate SQL | Stateless service | Sync | MVP |
| Policy and cost validator | Enforce entitlement, query shape, scan limits, execution rules | Policy store | Sync | MVP |
| Read-only execution gateway | Submit approved queries with limits and audit | Warehouse credentials / gateway | Sync | MVP |
| Result summariser | Rows → explanation, SQL, lineage, caveats | Stateless service | Sync | MVP |
| Evaluation harness | Replay prompts, compare outputs, detect regressions | Test corpus / telemetry store | Async | Later evolution, but useful early |
Three boundaries to point at
- Sync/async. Must be correct before this answer returns → sync. Improves future answers → async.
- Trust. Sits at the read-only gateway: narrowest credentials, no write path. Nothing the model generates reaches the warehouse except through it.
- Consistency. Entitlement and policy checked at planning and again at execution, so a user who loses access in between is refused. A material registry version change never silently reuses an old interpretation.
- Plus one rule: queue partitioning follows the natural isolation boundary (tenant, warehouse, region or dataset family), so one noisy customer or big catalog refresh can't starve unrelated work.
Is this an agent?
- Default: a governed LLM query workflow, a fixed sequence of checks.
- A supervisor agent is useful only when one question needs several approved specialists, as in the insurer variant: managed text-to-SQL service, restricted SQL/RAG worker, deterministic analysis, visualisation.
- Neither that agent nor its LLMs may define metrics or bypass the query gate.
- The insurer deep dive explains when the extra hop paid for itself.
6. Anchor every question on a governed metric
The semantic layer is the product
- The model is a translator into it.
- "Revenue last week" anchors on the governed definition before any table search: a model can't infer a definition the business hasn't written down.
- Raw schema access is an escape hatch for approved exploratory workflows, never the default.
The insurer made the same choice
- A handful of governed metric views instead of raw fact tables.
- If the agent and an analyst compute "claims by region" differently (date logic, exclusions), trust collapses the first time someone notices.
- A metric view makes the KPI definition one versioned artefact every consumer shares.
Three decisions to defend
| Decision | Default and reason | Failure to avoid |
|---|---|---|
| Semantic layer before schema | Resolve a named, versioned business metric before searching physical tables | Valid SQL with the wrong grain, exclusions or definition |
| Clarify before query | Show supported meanings; a numeric confidence gate can trigger clarification (the insurer supervisor used <60% for its own intent clarification) | A plausible answer to an unstated business interpretation |
| Fixed operations or managed SQL before open SQL | Reviewed operations or curated text-to-SQL views for common questions; hand-generated SQL only in a narrower approved path | Invented columns, excessive scans, permission drift |
Put a router in front of retrieval
- Real deployments mix structured and semantic questions freely.
- Semantic search answers "which things are like this". It never answers "how many", "which is most recent" or "sum this field".
- Route each subtask: semantic search for related prose, structured queries for counts and sums, direct lookup for IDs.
| Question | Route | Reason |
|---|---|---|
| "Revenue last week" | Versioned metric view + structured query | A financial definition and grain must be selected |
| "How many high-priority tickets?" | Structured count/filter | Semantic search doesn't count a complete set |
| "Status of ticket #4821?" | Exact ID lookup | Approximate retrieval is unnecessary |
| "Pattern in billing tickets this quarter?" | Structured filter, then summarise scoped prose | Filters establish the set; the LLM summarises it |
When semantic search is the right tool (full design)
| Question shape | Right tool | Why plain search fails |
|---|---|---|
| "Why did this customer's system break in March?" | Semantic search over documents and post-mortems | It doesn't fail here: this is what semantic search is for |
| "How many high-priority tickets did they file last week?" | Structured query (count/filter) | Search returns similar records, not a count |
| "What's the status of ticket #4821?" | Direct lookup by ID | Treating an ID as text is wasteful and imprecise |
| "Summarise the pattern across all high-priority billing tickets this quarter" | Both: filter first, then summarise | A filter can't summarise prose; search can't reliably scope to "this quarter's high-priority billing tickets" |
Two structured mechanisms
| Mechanism | Strength | Risk |
|---|---|---|
| NL → query on a small, fixed, documented view | Fast and flexible | Model can invent fields, so validate the query or sanity-check the result |
| A small set of fixed operations ("metric by period and region") | Safer: a reviewed set of operations, not an open-ended language | Less flexible |
- Fixed operations are usually the better enterprise default.
- The insurer decided per specialist: managed text-to-SQL over curated tables as the safe default, and one deliberately narrower place for hand-generated SQL on ad-hoc questions outside curated scope.
Two rehearsed answers
- "Revenue has three definitions. What do you do?"
- Name the ambiguity and ask a clarifying question. Show the supported definitions.
- Default only where the business has an approved canonical meaning for that context.
- If users ask it often, put it in the semantic layer with explicit aliases.
- "What's your riskiest assumption?" (that the model can infer the business meaning from the prompt):
Spoken answer: "I would not rely on the model to infer business definitions from raw text. I would anchor every answer to a governed semantic layer, and treat any question that falls outside that layer as an explicit ambiguity to resolve, not a guess to make."
7. Ask when ambiguous, never guess
The rule
- Several governed metrics or grain levels fit → stop and ask.
- A valid query answering the wrong business question is still a failure.
- Lopsided costs: a clarifying question costs one round trip; a guess costs an executive decision.
- Three modes, agreed in discovery: ask, refuse, or escalate to an analyst.
- A default is allowed only when a context-specific canonical definition has been approved.
Give the gate a number
- The insurer supervisor classifies each question with a confidence score into:
simple_kpideep_analysisdocument_lookupvisualizationconversational
- Its clarify node fires only below 60%. "Show me the numbers" → a clarifying question, not a guess.
- A threshold is testable and tunable. "The model will ask when unsure" isn't.
Caveats on the 60%
- It's an example from that engagement, not a universal value.
- A model-reported 0.60 isn't automatically a calibrated 60% probability of correctness.
- Calibrate first: compare scores with reviewed intent labels; measure wrong-route and unnecessary-clarification rates; choose the threshold with the customer.
- Even a high score must not override two conflicting approved metric definitions.
Ambiguity is also a freshness signal
- Catalog stale beyond a threshold → the retriever either:
- Refreshes through the async queue before allowing generation, or
- Falls back to a narrower supported question set, or
- Asks.
- Never silently generates against an unknown schema.
- A stale schema and an ambiguous definition are different reasons to stop; both mean don't pretend precision.
- For a business-definition conflict, the failure policy is human intervention: a wrong answer is worse than a slower one.
8. Treat SQL as an untrusted proposal, then execute read-only
Valid SQL isn't safe SQL
- The LLM proposes SQL from a narrow, authorised metric and schema context. Treat it as untrusted input.
- A query can parse, run and still touch a hidden column, scan a year of events or multiply rows through a bad join.
Check the tree, then the cost
- A dialect-aware parser builds the AST. Policy checks the tree, not the text:
- Statement type, physical tables, columns, functions
- Joins, aggregate semantics, limits, date filters
- Cross-join or fan-out risk
- A hidden-column request must fail even if the SQL is syntactically valid.
- A cost estimator checks bytes, time and row limits before admission; a live timeout cancels any overrun.
Authorisation is several independent controls
- So one failing doesn't expose data:
- Least-privileged, read-only credentials
- Warehouse-native row and column policies evaluated for the end user (on-behalf-of), not a shared service account
- Entitlements rechecked at execution
- Schema metadata filtered to what the user may see
- Redacted handling of results and logs
- The model can't rewrite access predicates (the filters restricting which rows a user sees).
Risk-based execution
- Auto-run only when all four hold: confidence is high, the query fits an approved pattern, the user has permission, estimated cost is below the threshold.
- Otherwise: show the draft SQL and ask for confirmation, or request analyst or privileged review.
- Full auto-execution feels magical and is dangerous when a query may touch sensitive rows, incur high cost or answer an ambiguous request.
- Never retry a policy denial with a stronger model. A denial means the request isn't allowed, not that the model was too weak.
- The SQL policy deep dive has the four controls side by side, the hidden-column test sketch and the cost-admission rules.
9. Explain variance from the data, not from memory
The summary check
- The executive reads the prose, not the rows.
- Generate the summary from the structured result; cross-check its key values against the table.
- Numbers don't match → reject the summary, return the table alone and alert the review queue.
- Summary generator down or untrusted → degrade to the table rather than fabricate confidence.
structured result table → generate summary → cross-check numbers vs table
- Match → table + summary.
- Mismatch → reject summary, table only, alert review queue.
- Generator down or untrusted → table only.
Illustrative case
- The table says Q3 recognised revenue is 41.2 million.
- The draft summary says "revenue rose to 42 million".
- The cross-check finds 42 nowhere in the result.
- The executive sees table, SQL and lineage without the sentence; a reviewer sees the rejected draft.
The copilot personas extend it into explanation
- Rule: every driver named must trace to a query.
- Executive copilot: explains variance against the governed definition, cites the metric definition used, escalates uncertain answers to analysts.
- Retail explainer: attributes forecast variance to drivers (sales history, promotions, weather, inventory, events), then recommends planning actions a person reviews before any order changes.
- Its red-team list:
- Confusing correlation with causation
- Hallucinated drivers
- Stale promotions data
- Recommendations biased against stores or regions
- Over-ordering because an explanation sounded confident
Keep the statistics deterministic
- The insurer's analysis agent computes Z-score anomalies and trend statistics rather than reasoning about them, so the model can't invent a plausible wrong number.
- The explanation layer narrates computed drivers; it never produces them.
- Correlation isn't proof of causation, and the assistant may not turn one into the other.
- Weak drivers → show confidence, missing evidence and the escalation reason.
- Board-level narratives go through an analyst before leaving the system.
Z-score = how many standard deviations a value sits from the mean; a simple deterministic anomaly flag.
10. Fail closed on policy, degrade on everything else
- Say exactly what fails open, fails closed, degrades, queues and escalates to a person.
- A policy engine outage isn't a visualisation glitch. A cost-exploding scan isn't a benign cache miss.
- Memorise by category: authorisation → closed; connectivity → degrade or queue; ambiguity → human; suspicious scan → closed and alert.
Failure policies
| Situation | Preferred policy | Why |
|---|---|---|
| Authorisation or policy evaluation fails | Fail closed | Better to deny than expose data accidentally |
| Warehouse connection briefly unavailable | Degrade or queue, by freshness needs | Preserve request intent if the use case tolerates delay |
| Query planner exceeds a safe timeout | Fail closed with a retry suggestion | Prevent runaway cost and long-tail blocking |
| Low-risk formatting or explanation service fails | Degrade | User still gets a safe, reduced answer path |
| Ambiguous metric mapping or business-definition conflict | Human intervention | A wrong answer is worse than a slower one |
| Suspicious row count or scan volume | Fail closed and alert | Unexpected scale is a probable correctness or cost issue |
The playbook: symptom → response
| Symptom | Response |
|---|---|
| Correct-looking number uses the wrong metric | Block publication, preserve the query run and versions, clarify or send to an analyst, then add a golden case |
| Schema drift or a dropped join key | Stop the affected template, refresh the catalog, review any changed definition before resuming |
| Join fan-out inflates totals | Check cardinality and expected row count before execution; refuse or show the expansion explicitly |
| Scan estimate or live scan exceeds budget | Narrow the date range or use an approved pre-aggregation; cancel and explain rather than "try it" |
| Policy engine or entitlement check unavailable | Fail closed. Don't substitute an unrestricted service account. |
| Warehouse or summary service unavailable | Queue if freshness permits; safe table-only result when only the explanation fails |
| Summary contradicts the table | Reject the prose, serve the table and lineage, alert the review queue |
Two rows to point at
- Policy engine down: the tempting shortcut is a broad service account "so the user still gets an answer". That shortcut is exactly the leak the design exists to prevent.
- Suspicious row count or scan volume is more than billing: treat it as a sign the query may be wrong.
- The five failure drills (deep dives) walk each from detection to prevention.
11. Keep the answer path synchronous and scale the rest
Sync vs async
- Synchronous: metric resolution, authorisation, validation, execution. Together they decide the one answer the user gets.
- Asynchronous: catalog crawls, cache refreshes, evaluation replays, partitioned by tenant or warehouse so background jobs don't stampede query traffic.
- Cache keys include tenant, permission signature, metric and schema version, and freshness.
- A cached answer computed for one user's permissions must never be served to another.
Measure before changing anything
- First-try semantic correctness
- SQL retry rate
- Warehouse compute per answer (bytes scanned on BigQuery, credit time on Snowflake and similar)
- Token spend
- p95 latency by stage
- Cost warning: warehouse compute more than 20% above the seven-day baseline.
p95 = the latency 95% of requests finish within.
Cheapest levers
- Narrower metric context, approved templates, dry-run cost checks, bounded windows, safe caching.
- Anti-pattern: repeatedly asking a stronger model to repair invalid SQL. It raises both bills and can still answer the wrong question.
- The cost deep dive and the full casebook's cost pivot develop this.
12. Gate the release on semantic correctness, not execution success
Two measures, two gates
| Measure | Question | Proven by | Role |
|---|---|---|---|
| Execution accuracy | Does the SQL run and match the expected result? | Golden-set replay | Regression check |
| Semantic correctness | Does the query answer the governed business question? | Analyst review against the governed definition | The release gate |
| Escaped policy violations | Did any get through? | Query-run audit | Separate gate: zero, owned by Security |
Golden cases
- Pair the NL question, the approved SQL and the expected result shape.
- Include:
- Easy examples and ambiguous paraphrases
- Edge cases with filters, grain and date windows
- Unauthorised columns, large scans, join fan-out
- Known traps where a valid query answers the wrong question, including a summary that misstates a correct table
- Analysts judge the subtle wrong answers in shadow mode.
Metrics, thresholds and owners
- The 4.2/5 trust target and the copilot percentages are source examples to agree with the customer, not product standards.
| Metric | Good threshold | Bad threshold | Dataset / method | Owner |
|---|---|---|---|---|
| Semantic correctness | Matches analyst review on scope | Any silent mismatch | Golden question/SQL/result cases | Analytics lead |
| Execution accuracy | No unexplained regression on the golden set | Any unexplained regression | Golden-set replay on every change | Application owner |
| Policy violations | 0 escaped | > 0 escaped; investigate repeated blocks (more than five identical blocked attempts in a day) | Policy decisions in the query-run audit | Security |
| Warehouse compute per answer (bytes or credit time) | Within the 7-day baseline | > 20% above baseline | Warehouse telemetry | Data platform |
| User trust score | ≥ launch target (4.2/5 or 80% positive) | Two consecutive review periods of decline, even if usage rises | In-product feedback and periodic survey | Product |
| p95 latency and escalation volume | Within target; escalations trending down | Breach or rising escalations | Request traces + analyst ticket counts | Platform / SRE |
| Groundedness and citation accuracy (copilot personas) | ≥ 90% supported claims; ≥ 95% correct citations | Below | Golden Q&A with SME review; source-span audit | ML / eval |
| Escalation quality (copilot personas) | ≥ 95% correct escalation on high-risk cases | Missed high-risk case | Risk-labelled scenarios | Product / support |
SRE = site reliability engineering. SME = subject-matter expert. ML = machine learning.
- Falling trust matters even while usage rises. An answer users still ask analysts to recheck hasn't solved the workflow.
- The evaluation deep dive covers the four buckets, the layered dashboard and the red-team list.
13. Roll out ten metrics at a time
What the rollout must prove, in order
- It answers a narrow set of governed questions correctly.
- It does so safely under policy.
- Real users adopt it because it improves their workflow, not because it impressed them in a demo.
Five stages
ten governed metrics with owners → golden replay on every change → shadow analysts on live questions → small executive release → domain-by-domain expansion with a named metric owner
- Each stage widens the blast radius; advance only when the previous stage's exit criteria are met.
- The source's four-phase diagram (rollback gate at every stage; it folds the executive release into the shadowing → expansion step):
| Phase | Exit when |
|---|---|
| 1. Ten governed metrics | Definitions documented and policy checks pass |
| 2. Golden question/SQL/result cases | Regressions detectable, every failure explainable |
| 3. Shadow analysts | Matches analyst review, escalation path works |
| 4. Expand domain by domain | Each domain has a named metric owner |
Week by week
| Week | Gate |
|---|---|
| 0 to 1 | Ten governed metrics with stable definitions, known owners, visible impact (revenue, active customers, pipeline, churn, support backlog); non-goals documented |
| 1 to 2 | Definitions documented, query templates reviewed; the assistant can explain which metric it used and why |
| 2 to 3 | Golden cases built, including ambiguous paraphrases and known traps |
| 3 to 4 | Golden set replayed on every change; execution accuracy vs semantic correctness compared; every failure explained |
| 5 | Shadow analysts on real questions; users still see the analyst's answer as truth; analysts mark correct, merely plausible, or wrong for subtle reasons (wrong grain, definition or segment filter) |
| 6 to 8 | Executive release once it consistently matches analyst-reviewed answers and escalation works |
| After | Expand domain by domain, each with a named metric owner who approves definitions, reviews golden cases and owns semantic-layer changes |
Name the owners
| Owner | Owns |
|---|---|
| Metric owner | Approves definitions and golden cases |
| Application owner | Runtime, prompt assembly, generation, API contracts |
| Data owner | Warehouse tables, the semantic layer, policy mappings |
| Security owner | Access control, audit logging, blocked-query handling |
| Support owner | Receives escalations, coordinates rollback |
Roll back on
- A spike in policy violations
- A drop in semantic correctness
- A jump in bytes scanned
- Users routing around the assistant because they stopped trusting it
- Rollback keeps a partial success from becoming an incident.
What the next customer inherits (FDE reuse split)
- A Forward Deployed Engineer (FDE) system pays off only when the next customer inherits the stable core and swaps the edges.
| Layer | Contents |
|---|---|
| Configuration | Metric definitions, allowed domains, rollout thresholds |
| Adapters | Warehouse and identity integrations |
| Shared services | Query validation, policy enforcement, tracing, audit logging |
| Core product | Question understanding, explanation behaviour, safe query orchestration |
Five delivery items
- A canary on a small user group or metric set.
- Staged migration of governed questions from analyst workflows.
- User training on what it can and can't answer and how it signals uncertainty.
- Documented escalation paths.
- A maintained metric catalog with known limitations.
Three standing risks
| Risk | Owner | Mitigation | Trigger |
|---|---|---|---|
| Correct SQL answers the wrong business question | Analytics lead | Golden cases, semantic review, approved metric catalog | A valid query passes execution but fails analyst review |
| Policy block frustrates users | Security + product | Better clarifying prompts and explanation text | Repeated blocked attempts on the same workflow |
| Warehouse cost spikes | Platform owner | Query limits, result caching, scan monitoring | Warehouse compute per answer drifts upward |
Quick Recall: Lines to Say in the Interview
- "Valid SQL for booked revenue when Finance means recognised revenue succeeds, and nobody gets an error. That's the risk I design for."
- "The semantic layer is the product; the model is a translator into it."
- "A clarifying question costs one round trip; a guess costs an executive decision."
- "The insurer's clarify node fired below 60%, and I'd calibrate that against reviewed labels before adopting it."
- "Valid SQL isn't safe SQL: policy checks the tree, not the text, and the query runs on behalf of the user."
- "Never retry a policy denial with a stronger model."
- "If the policy engine is down, fail closed. Never swap in an unrestricted service account."
- "Execution accuracy is a regression check; semantic correctness against analyst review is the release gate."
- "Ten governed metrics, golden replay, shadow analysts, a small executive release, then domain by domain."
Technical deep dives
What this part covers: the mechanisms behind the follow-up questions. SQL policy, the five failure drills, evaluation, lineage records, the insurer engagement and cost.
30-Second Cheat Sheet
- Parse, don't regex: safety depends on syntax trees and policy rules, not pattern-matching theatre.
- Four controls, defence in depth: least privilege, warehouse-native row/column policies, AST inspection, result hygiene.
- Caller identity must reach the warehouse: a shared service account doesn't carry the executive's identity. Use on-behalf-of and test with two users.
- A row limit isn't a scan budget:
LIMITneedn't reduce scan cost. Dry-run and cap bytes billed. - Five drills: wrong business question, schema drift, join fan-out, excessive scans, summary contradicts table. Contain by tenant, workflow and metric family.
- Four measurement buckets: technical health, model quality, adoption, business outcome. Red-team the definitions, not only the SQL.
- Insurer story: monolith with 20+ tools failed → eight-node supervisor shipped (clarify below 60%, 16-asset index) → deep agent per domain.
- Cost in four verbs: measure, route, bound, cache safely.
1. SQL policy is a separate enforcement system
Why a parser, not regex
- Regex can spot an obvious
DROP TABLEstring. - It can't understand: aliases, nested selects, CTEs, comments, obfuscation, or a harmless-looking subquery that turns unsafe after a rewrite.
- A parser inspects structure: allowed statements; which tables, columns, joins and functions appear; whether limits are present; whether aggregate semantics are acceptable.
CTE = common table expression: a
WITHclause that names a subquery.
Four controls at the execution boundary
- Each stops a different abuse. If the parser misses something, the read-only identity and the warehouse policies still hold.
| Control | What it does | Abuse it stops |
|---|---|---|
| Least privilege | A read-only identity that inspects only approved datasets with only the operations analysis needs | A prompt injection or bad plan becoming a write, delete or privilege escalation. A request for hidden customer emails fails because the identity can't read that column, not because the model probably refuses |
| Warehouse-native row and column policies | The warehouse enforces which tenant, region or role sees which slice, instead of app code reimplementing it | The classic bug: the app filters one path and forgets another; one tenant's policy error exposing another tenant |
| Parse, do not regex | Inspect the AST for writes, unbounded cross joins, unauthorised tables, unexpected functions, missing limits, scan-budget violations | Obfuscated or nested SQL that passes a string filter |
| Result hygiene | Mask sensitive fields on the response path; log hashes or redacted fingerprints, not raw data | A second leak channel through logs; a replayable copy of sensitive output |
The warehouse must receive the caller's context
- In Snowflake, a row access policy runs with the policy owner's privileges, so it can consult protected mapping tables.
- Its expression can use session context (
CURRENT_ROLE(),CURRENT_USER()) to decide which rows the querying user may see. - Policy-owner privileges and caller identity serve different purposes.
- A shared service account doesn't automatically carry the executive's identity. So:
- Use a supported on-behalf-of flow or another explicitly validated identity mapping.
- Recheck entitlements at execution.
- Test the policy with two users whose permitted rows differ.
- Filter schema metadata to the caller's access too.
The hidden-column test sketch
- A marketing actor may read
customer_id,countryandplan. SELECT email FROM customersis perfectly valid SQL.- The test asserts it's rejected, because
emailis outside the actor's permitted columns.
class PolicyError(Exception):
pass
@dataclass(frozen=True)
class Actor:
name: str
permitted_columns: frozenset[str]
marketing_user = Actor(name="marketing", permitted_columns=frozenset({"customer_id", "country", "plan"}))
def parse_selected_columns(sql: str) -> list[str]:
normalized = " ".join(sql.strip().split())
upper = normalized.upper()
if not upper.startswith("SELECT ") or " FROM " not in upper:
raise PolicyError("Only simple SELECT queries are allowed in this sketch")
select_part = normalized[7 : upper.index(" FROM ")].strip()
if select_part == "*":
raise PolicyError("Wildcard selects are not allowed")
columns = [c.strip() for c in select_part.split(",")]
if any(not c for c in columns):
raise PolicyError("Malformed column list")
return columns
def approve(sql: str, actor: Actor) -> bool:
columns = parse_selected_columns(sql)
denied = [col for col in columns if col not in actor.permitted_columns]
if denied:
raise PolicyError(f"actor {actor.name} may not access columns: {', '.join(denied)}")
return True
def test_rejects_hidden_column_exfiltration():
sql = "SELECT email FROM customers"
with pytest.raises(PolicyError):
approve(sql, actor=marketing_user)
- Read it for the invariant, not the parser.
parse_selected_columnssplits strings, the very approach this section rejects.- It refuses anything beyond a simple
SELECT ... FROMand wildcards, so it stays honest about its limits. - It omits its imports (
dataclass,pytest).
- What changes in production (source): a dialect-aware parser, a policy source from the warehouse or a central registry, a logged decision with redacted evidence.
- Keep the test itself, run against the real parser and policy path.
Then estimate cost
- Approved queries get a cost estimate, a timeout and a row limit, then run through the read-only gateway.
- A row limit bounds returned results, not necessarily the work to produce them.
- BigQuery warns that
LIMITdoesn't reduce scan cost for non-clustered tables.
- BigQuery warns that
- Use: dry-run estimates, an engine-enforced budget such as maximum bytes billed where supported, bounded date windows, pre-aggregations.
- Cancellation after work begins can't recover cost already incurred.
- Over the scan threshold: ask the user to narrow it, propose a cheaper rewrite, or require approval from a more privileged role.
- Never let the model "just try it".
- Cost control protects shared concurrency too: a permitted query can still slow other tenants.
Soundbite: "The identity can't read that column, so it doesn't matter whether the model would have refused."
2. Five failure drills and the safeguards around them
- These cover the failures that survive unit tests.
- Same shape each time: how it shows → detect → contain → evidence to keep → prevent.
- Containment is scoped by tenant, workflow and metric family, never "all analytics is broken".
Drill 1: the wrong business question
- The headline drill. "Active customers" quietly uses login activity where the definition requires paid activity.
- The SQL returns rows, the chart renders. Nothing looks broken.
- Detect: compare the generated query against governed metric metadata and approved aliases.
- Contain: block publication, mark the run blocked, stop downstream sharing.
- Preserve: prompt hash, SQL text, policy decision, asset versions, rejection reason.
- Recover: route to a clarified metric choice or human review.
- Prevent: tighten the metric mapping, the test case or the disambiguation prompt.
Drill 2: schema drift
- A column disappears, a table is renamed overnight or a join key shifts. A previously good template still produces something reasonable-looking.
- Detect during plan validation, against catalog versions, not after a failed warehouse call.
- Fail closed on the affected template and refresh the schema cache.
- Business definition itself changed? Queue a review. Otherwise resume once the cache is refreshed.
- Prevent: a version-stamped cache and regression replay whenever the schema changes.
Drill 3: join fan-out
- A join multiplies rows and inflates totals while staying valid and passing every SQL check.
- Illustrative: joining orders to a one-row-per-shipment table counts a two-shipment order's revenue twice.
- Validate join cardinality assumptions.
- Compare the row count against heuristics for the metric's grain.
- Within expectation → allow.
- Suspicious fan-out → allow only if the user explicitly asked for a detailed expansion, with an explicit expansion caveat; otherwise refuse or downgrade.
- Can't prove the join safe? Refuse or downgrade. Never hope the aggregate still looks plausible.
- Prevent: reviewed join paths and golden cases.
Drill 4: excessive scans
- Cost is a reliability issue: one query can exhaust concurrency and slow other tenants.
- Estimate before executing.
- Under the threshold → execute with limits and timeouts.
- Over it, and a bounded date window or pre-aggregation exists → rewrite to that form.
- Otherwise → fail closed; ask the user to narrow the question or confirm.
- Prevent: per-metric scan budgets and trend alerts for the slow creep.
Drill 5: the summary contradicts the table
- The table is right; the prose misstates it.
- Response: the step 9 summary check. Reject the prose, return table, SQL and lineage, notify the review queue.
- Prevent: a numeric cross-check against the structured result, before it reaches the executive.
The drills at a glance
| Drill | Detect and contain | Prevent |
|---|---|---|
| "Active customers" mapped to login instead of paid activity | Compare chosen metric and SQL with governed metadata; block sharing, mark run, retain prompt hash, SQL, policy and asset versions | Tighten aliases; add a semantic golden case |
| Schema drift | Validate plans against catalog versions before the warehouse call; stop affected template and refresh | Version-stamped cache; regression replay on schema change |
| Join fan-out | Compare cardinality and row counts with expected grain; refuse unrequested expansion | Reviewed join paths, heuristics, golden cases |
| Excessive scan | Estimate before running; bounded date window or pre-aggregation, otherwise stop and ask | Per-metric scan budgets and trend alerting |
| Prose disagrees with table | Reject prose; return table, SQL, lineage; notify review queue | Numeric cross-check against structured result |
Operational safeguards and backpressure
A bounded timeout on every warehouse query.
Limited, idempotent retries, only when the failure is likely transient.
No indefinite retry of a policy failure: a bad prompt isn't a network glitch.
A dead-letter path with enough redacted context for support, when a queued request keeps failing.
A human escalation route for any ambiguous mapping or repeated semantic mismatch.
Human escalation is a designed path with an owner and a queue, not an apology.
Backpressure lives in the background lane: crawler and registry refresh jobs sit behind a queue with rate-limited bursts, so they never stampede the warehouse at peak.
The query API degrades gracefully when metadata confidence drops.
Dead-letter path = a holding queue for requests that keep failing, so they stop retrying but aren't lost.
The compact failure policy as one flow
- Request → authenticate → authorise tenant, role and metric.
- Parse the SQL AST → validate tables, columns, joins, limits and query shape.
- Policy or semantic failure → reject and log redacted evidence.
- Pass → execute read-only as the user with native RLS and CLS.
- Scan or time budget exceeded → cancel and return a safe fallback.
- Otherwise → check results and mask sensitive fields → summarise the structured result.
- Summary doesn't match → table only + review alert. Matches → return the result.
3. Measure in four buckets and red-team the definitions
Four buckets (so model quality is never confused with ops health or business value)
| Bucket | Measures |
|---|---|
| Technical health | Bytes scanned, p95 latency, availability |
| Model quality | Execution accuracy, semantic correctness, clarification rate, policy violations |
| Adoption | The trust score |
| Business outcome | Answer turnaround before and after, analyst escalation volume, executive self-service rate |
A successful assistant changes behaviour
- If executives keep asking analysts to re-check, the product hasn't solved the problem.
- Layered dashboard: business outcome on top, model quality in the middle, system health at the bottom.
- Each business metric is wired to the component that can move it, so a trust drop points somewhere specific:
- Slow answers
- Too many clarifications
- Broken mapping
- Policy blocks that feel arbitrary
Red-team the definitions as well as the SQL (source's list)
- Semantic substitution: login activity stands in for paid activity.
- Schema drift that keeps a template plausible.
- Join explosions that pass every SQL check.
- Excessive scans that slow other tenants.
- Summary drift: the table is right, the prose misstates the trend.
- Copilot personas add: fabricated business reasons, leakage across regions or business units, stale dashboard refreshes presented as current, an overconfident board-level narrative.
Trust and feedback
- Trust example: 4.2/5 or 80% positive. A decline across two consecutive review periods is bad even if usage rises.
- Feedback and analyst corrections feed evaluation only after review; they never flow straight into training.
4. Lineage, versions and the variance records
"The number changed since last quarter. Why?"
- Metric versions are retained.
- Each
QueryRunstamps the metric, schema, policy, prompt and model versions it used. - So the two runs are diffed by definition, not by guesswork.
Executive copilot: four records
| Record | Holds |
|---|---|
KPIValue(metric_id, period, dimension, value, source_table) |
A computed KPI value and where it came from |
Dashboard(id, owner, metric_ids, refresh_time) |
Which governed metrics a dashboard shows and how fresh it is |
Insight(id, metric_id, explanation, supporting_queries, confidence) |
A cited explanation, tied to its supporting queries |
UserAccess(user_id, metric_id, dimension_scope) |
Which metrics and dimension slices a user may see |
Retail persona records
- SKU (stock-keeping unit), Store, ActualSales
Forecast(id, sku_id, store_id, horizon, prediction, confidence)DriverSignal(id, type, value, source, timestamp)Explanation(forecast_id, top_drivers, confidence, caveats)
The record shape enforces step 9's rule
- Drivers from promotions, weather, inventory or events are computed from data into
DriverSignalrows first. - The
Explanationonly narrates them, with confidence and caveats attached. - The assistant can't infer a causal claim from a correlation in those signals.
5. When a supervisor is justified: the insurer engagement
Framing (say this honestly)
- An engagement story from the source, not the default architecture for every NL-to-SQL product.
- The source's author tells it in the first person, as a project they led; quoted phrases are theirs.
- Use it as an attributed reference unless the work is your own.
The situation
- A large Asian life insurer: actuaries, claims managers and regional analysts needed answers over governed data.
- Every question went through a BI queue: an ad-hoc question took days; a new dashboard took weeks.
- Built a governed self-service assistant: an MVP in about two months on a short build engagement.
- The architecture changed twice.
| Stage | Shape | Result |
|---|---|---|
| 1. Monolithic agent | One agent, 20+ tools, full history | Failed: degraded accuracy |
| 2. Supervisor pattern | LangGraph supervisor, 8 nodes, four specialists | Shipped |
| 3. Deep agent | Orchestrator, four domain subagents (customer, channels, policy, claims), long-term categorised memory manager | Evolved |
First pivot: the monolith
- One agent, one prompt, twenty-plus tools, full conversation history. Broke on two axes in real testing:
- Context bloat: every tool schema in context on every turn.
- Tool confusion: with that many tools, it picked the wrong one often enough to be unusable.
- The precise answer if asked why: stuffing 20-plus tool schemas plus full history into one prompt measurably degrades tool-selection accuracy. A context-bloat effect, not vague confusion.
- RAG-MCP (Gan and Sun 2025) reports tool-selection accuracy falling as the tool pool grows.
- OpenAI's function-calling guidance recommends keeping tools per turn small.
- The fix was architectural, not a bigger model or better prompting: split deciding what to do from doing it.
The supervisor that shipped
- A fixed eight-node LangGraph state machine.
- The eight nodes: classify intent, clarify or disambiguate, resolve assets, the four specialists, compose.
- Routing is a conditional edge, not a node. The diagram draws it as a box, and draws clarification on every path, though the clarify edge fires only below 60% confidence.
- Flow: classify intent → clarify or disambiguate (below 60%) → resolve assets from the context index → route to one specialist → compose the answer.
Centralised asset resolution
- Only the supervisor resolves assets, against a 16-asset Context Index: curated text-to-SQL spaces, metric views, tables and document indexes, endorsed assets ranked first.
- It passes the resolved list to one of four specialists through shared state.
- Cost: one hop of latency.
- Buys: a single auditable source of truth for what data any answer is based on.
- Why it matters: two workers resolving to different tables for the same question is a governance nightmare in insurance.
The four specialists
| Agent | Role | Tools | The trade-off it embodies |
|---|---|---|---|
| Text-to-SQL | BI specialist | Managed text-to-SQL conversation API | Managed service over a hand-rolled chain: less flexible, with read-only execution as a required deployment contract. Verify which principal the integration uses: a managed API doesn't automatically impersonate the end user. Analysts curate the space's tables, instructions and example SQL without code |
| Multi-Tool | Generalist | LLM-generated SQL + vector search RAG over policy docs | The one place hand-generated SQL was allowed, for ad-hoc questions outside the curated scope, under deliberately narrower governance |
| Data Analysis | Statistical | Z-score anomaly detection, trend statistics | Kept deterministic: thresholds are computed, not "reasoned about", so the model can't invent a plausible wrong number |
| Visualisation | Dashboard creator | Dashboard REST API | Publishes real, clickable dashboards rather than a static chart image, closing the loop on the weeks-long dashboard pain |
RAG = retrieval-augmented generation: fetch the relevant documents first, then answer only from them.
Why LangGraph
- CrewAI Flows'
@routeralso gives deterministic branching. The source's claim is only that a LangGraph conditional edge states the confidence rule most directly.
| Requirement | Why LangGraph fit |
|---|---|
| Conditional routing on confidence | Explicit conditional edges: classify_intent routes to clarify_or_disambiguate only when confidence < 60%. Role-based crews delegate by conversation; CrewAI Flows now add @router branching, but a conditional edge states it most directly |
| Durable, resumable state | Multi-turn conversations backed by table checkpoints, a governance requirement: every conversation state must be auditable. The author wrote a custom checkpointer over a table |
| Deterministic composition | A governed insurance environment can't tolerate open-ended agent-to-agent chat deciding its own flow. The graph is inspectable and fixed at build time: eight nodes, each nameable |
The governance underneath (five pieces)
- A handful of governed metric views instead of raw fact tables.
- Short-term memory in a table keyed by thread, with short retention, so conversations survive a restart and stay auditable.
- Base-plus-overlay prompts in a governed table with a five-minute cache, so behaviour is tunable without a redeploy.
- MLflow tracing on every node, so a wrong answer traces to the exact node and tool call.
- A model gateway for rate limits and PII filtering on the model endpoints the agent calls.
- The source notes that, as of 2026, it couldn't guardrail the agent endpoint itself.
- Verify that against the current platform; don't treat it as a lasting product fact.
PII = personally identifiable information: name, email, phone, account number.
- A managed multi-agent feature wasn't an option for this customer at the time, so the author hand-built the supervisor.
Second pivot: the deep agent
- As domains grew, the supervisor's own tool list re-approached the original bloat.
- Same fix, one level up: an orchestrator delegates to fully self-contained sub-agents, one per analytics domain:
- Customer
- Distribution channels
- Policy and underwriting
- Claims
- Each has its own prompt, small toolset, context window and curated text-to-SQL space.
- A memory-manager sub-agent owns long-term memory in a categorised table: preference, fact, decision, project and feedback entries.
- Cost: more infrastructure surface.
- Caveat: fewer tools and less history per specialist can reduce the selection problem, but domain routing can still fail and a specialist can still accumulate too many tools.
- Evaluate both routing and within-domain tool selection as domains grow.
Results, stated honestly
- Reported: time-to-insight days → minutes; dashboard delivery weeks → governed self-serve.
- Adoption grew after rollout, but the author "can't attribute it cleanly". The source advises saying exactly that before being asked.
- These are reported, correlational results from one engagement.
- "If rebuilt today" lessons:
- Instrument resolution-time and accuracy metrics from day one, rather than relying on tracing for post-hoc debugging.
- Invest earlier in the offline evaluation dataset.
The narrow design lesson
- A supervisor earns its extra hop and infrastructure only when one question genuinely needs several approved specialists.
- Even then, the specialists inherit the same governed query path: no agent or model defines a metric or bypasses the query gate.
- The spoken version of this story is a practice exercise in the full casebook.
Soundbite: "We split deciding what to do from doing it, and kept every specialist on the same governed query path."
6. Cost and scale: measure, route, bound, cache
Why both bills climb
- Retries on invalid or wrong SQL.
- The full schema carried as input tokens on every call.
- Measure first: SQL retries, context tokens, warehouse compute (bytes scanned or compute time), first-try success, p95 latency, cost per answer. Then consider changing models.
Two budgets, two units
| Bill | Unit | Levers and alert |
|---|---|---|
| Model | Tokens | Narrow context, token budgets, small models for routing |
| Warehouse | Bytes scanned (BigQuery on-demand), credit time (Snowflake and similar) | Scan budgets and bounded date windows; alert on a rising seven-day average, with the source's example threshold more than 20% above that baseline |
Four verbs, in order
- Measure: trace and attribute spend first, per stage and per answer.
- Route: match the model and path to the risk; a small model for routing, reviewed operations or managed SQL for common questions.
- Bound: limit steps, tokens, top-k, timeouts and budgets; cap scans and date windows.
- Cache safely: put tenant, permission and version in the cache key.
Applied here
- Shrink context to metric definitions and a few permitted tables.
- Reviewed operations or managed SQL for common paths.
- Dry-run cost.
- Cache versioned metric metadata and recurring executive questions.
- Cap scans and date windows.
- A stronger-model retry loop can't repair a missing business definition.
- Catalog crawling and evaluation replay run on partitioned, rate-limited queues.
- Query-time authorisation and policy never move off the hot path to save money.
Soundbite: "Measure, route, bound, cache safely, and never move authorisation off the hot path to save money."
7. Sources and provenance
What the November review changed
- Corrected the Snowflake policy description.
- Separated result limits from scan budgets, using the linked Snowflake and BigQuery documentation.
- The engagement's architecture, timings and reported outcomes remain attributed source material, not measurements reproduced by this reader.
References (checked by the source on 27 September 2026)
| Reference | Supports |
|---|---|
| Snowflake docs: Understanding row access policies | Policy expressions run with owner privileges and can inspect querying-session context to decide visible rows (SQL policy) |
| OpenAI API docs: Function calling | Keep the tool count per turn small (insurer engagement) |
| Gan and Sun 2025, RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection | Tool-selection accuracy falls as the tool pool grows (insurer engagement) |
| CrewAI docs: Flows | @router gives CrewAI deterministic branching |
| BigQuery pricing | On-demand queries bill by bytes processed (cost) |
The numbers are source examples, not defaults
- The 3 to 8 s interactive target
- The 60% clarification threshold
- The 16-asset index
- The 20% cost drift
- The 4.2/5 trust target
- The copilot percentages
- Confirm each with the customer. Check current warehouse docs for execution identity, policy coverage and cost estimation before implementing.
Quick Recall: Lines to Say in the Interview
- "Safety depends on syntax trees and policy rules, not pattern-matching theatre."
- "A request for hidden emails fails because the identity can't read that column, not because the model probably refuses."
- "A shared service account doesn't carry the executive's identity. I'd test the policy with two users whose rows differ."
- "A row limit bounds the result, not the scan. I dry-run and cap bytes billed."
- "Contain by tenant, workflow and metric family, never 'all analytics is broken'."
- "Red-team the definitions, not only the SQL: login activity standing in for paid activity is the headline drill."
- "Twenty-plus tool schemas in one prompt degrade tool selection, so we split deciding from doing."
- "Adoption grew, but I can't attribute it cleanly."
- "Never move authorisation off the hot path to save money."
Quick review
One sentence: the metric registry defines the business answer; the LLM translates the question and explains a validated, read-only result.
30-Second Cheat Sheet
- Memory line: "The semantic layer defines the answer; the LLM translates and explains it."
- Default is a workflow, not an agent. A supervisor only for a real multi-specialist task.
- Semantic correctness is the release gate, because valid SQL can answer the wrong question.
- Ask about "revenue" when more than one approved definition fits.
- Parse the AST. Regex and prompt rules don't stop unsafe SQL.
- Read-only, rechecked, native, budgeted: credentials, entitlements at execution, row/column security, scan budget.
- Summary contradicts the table? Return the table alone.
- Close: ten governed metrics, a clarifying gate, AST and cost checks, read-only execution, analyst-reviewed correctness.
1. The one sentence and the flow
The one sentence
- The metric registry defines the business answer; the LLM translates the question and explains a validated, read-only result.
- Memory line: "The semantic layer defines the answer; the LLM translates and explains it."
The whiteboard flow
identity → governed metric → ambiguity gate → permitted schema → LLM SQL proposal → AST policy + scan-cost check → read-only warehouse with native security → numeric cross-check → answer with SQL, lineage and caveats
Agent role
- Default: a governed query workflow.
- Supervisor only for a real multi-specialist task. It routes; policy and warehouse controls remain authoritative.
Ask first
- Who owns the first ten metrics?
- Does a semantic layer exist?
- Which warehouse and dialect?
- Is row and column security native?
- Which ambiguity needs clarification?
- What are the scan and latency budgets?
- Where is the analyst review threshold?
- What audit evidence is required?
2. Rules and numbers to recall
Five rules
- Valid SQL can answer the wrong business question; semantic correctness is the release gate.
- Ask about "revenue" when more than one approved definition fits.
- Parse the AST; don't rely on regex or prompt rules to stop unsafe SQL.
- Read-only credentials, an execution-time entitlement check, warehouse-native row and column security, and a scan budget.
- Reject a summary that contradicts the table; return the table alone.
Case numbers, with context
- These are source examples to confirm with the customer.
| Item | Value | Context |
|---|---|---|
| MVP | Ten governed metrics, golden question/SQL/result cases, analyst shadowing | The definition of "good" |
| Interactive latency | 3 to 8 s | Copilot example |
| Clarify threshold | Intent below 60% | Asian life insurer example |
| Metric views | A handful of governed views | Asian life insurer example |
| Supervisor | Eight nodes | Asian life insurer example |
| Context Index | 16 assets | Asian life insurer example |
| Cost signal | Warehouse compute per answer (bytes or credit time) more than 20% above the seven-day baseline | Source's alert |
| Trust | 4.2/5 or 80% positive | Trust example |
| Copilot evaluation | ≥ 90% supported claims, 95% correct citations, 95% correct high-risk escalation | Copilot evaluation examples |
3. Failures, cost and the closing answer
Failure triggers and responses
| Trigger | Response |
|---|---|
| Wrong metric or grain | Block and clarify/analyst review; add golden case |
| Schema drift or join fan-out | Stop affected query/template; refresh and validate cardinality |
| Hidden column or policy failure | Fail closed |
| Excessive scan | Narrow window or pre-aggregate; cancel if unsafe |
| Summary mismatch | Table only, alert review queue |
The cost answer
- Measure retries, tokens and warehouse compute (bytes scanned or compute time).
- Send metric definitions, not the full schema.
- Prefer approved operations; dry-run SQL; cap scans.
- Cache only within tenant, permission and version scope.
- Don't retry a wrong definition with a stronger model.
The fourteen takeaways (in walkthrough order)
- The failure to design against: valid SQL that confidently answers the wrong business question, named in the first two minutes.
- Requirements a test can fail: correctness over speed, ten governed metrics as the definition of good, an owner for every constraint.
- One owner per state: the catalog owns schema truth, the registry owns definitions, caches are performance only, every behaviour-changing artefact is versioned.
- One diagram: control plane split from data plane; the trust boundary is the read-only gateway, with entitlements re-checked at execution.
- Anchor on a governed metric before touching a table; a router decides structured, semantic or both; fixed operations over open generation.
- Ambiguity → clarifying question, with a numeric confidence threshold, never a guess.
- SQL validated as a tree against policy and a scan budget, executed read-only under warehouse-native row and column security.
- Explanations from the structured result, cross-checked against the table, built on deterministic statistics.
- Authorisation fails closed, everything else degrades, with five rehearsed drills from wrong definition to summary drift.
- Release gate: semantic correctness judged by analysts, not execution success.
- Rollout: ten metrics, golden cases, shadow analysts, a small executive release, then domain by domain with named owners.
- The fifty minutes spent in proportion to risk, with the 90-second summary, the 2-minute answer and nine carrying lines ready.
- As a story: a two-pivot engagement. A monolith that failed on context bloat, a supervisor that shipped, a deep agent that scaled, with results stated as correlational.
- The cost pivot is answered by the design itself: the semantic layer and validation remove retries and the schema from every prompt.
Interview close (source's version): "Ten governed metrics, a clarifying gate, AST and cost checks, read-only execution, and analyst-reviewed semantic correctness before executive rollout."
Flashcard Drill
Quick Recall: Lines to Say in the Interview
- "The semantic layer defines the answer; the LLM translates and explains it."
- "The default is a governed query workflow. A supervisor only routes; policy and the warehouse stay authoritative."
- "Valid SQL can answer the wrong business question, so semantic correctness is the release gate."
- "Parse the AST; regex and prompt rules don't stop unsafe SQL."
- "Hidden column or policy failure: fail closed."
- "If the summary contradicts the table, the executive gets the table alone and the review queue gets an alert."
- "Send metric definitions, not the full schema, and never retry a wrong definition with a stronger model."
- "Ten governed metrics, a clarifying gate, AST and cost checks, read-only execution, and analyst-reviewed semantic correctness before executive rollout."
Where next
- Practise this as a worksheet
- Natural-Language-to-SQL Analytics Assistant
- Revise the concepts