Case brief
Understand the scenario, task, and constraints.
Answer the business question the user means
Executives and analysts want to ask a business question in plain words, such as "What's Q3 revenue?", and get a number they can put on a slide. Today an analyst hand-translates each of those questions into SQL (Structured Query Language, the language used to query warehouse tables), runs it and sanity-checks the result, often for the same handful of questions every week.
Generating the SQL is the easy part. The hard part is meaning. "Revenue" can mean booked, recognised or collected revenue, and a model can write perfectly valid SQL that answers the wrong one. That failure is more dangerous than an error message, because the query ran, the chart rendered and the number looks plausible. The model cannot choose that definition on the business's behalf.
A few terms carry the case. A semantic layer, or metric registry, is the store of business definitions: each metric has an approved definition, its allowed dimensions and grain (the level of detail, such as daily or per customer), a named owner and a version. A KPI (key performance indicator) is one of those watched numbers. An AST (abstract syntax tree) is a query parsed into its structure, so a checker can see which tables, columns and joins it really touches. RLS and CLS (row-level and column-level security) are warehouse rules that decide which rows and columns a given user may see. A golden case is a reviewed test that pairs a question with its approved SQL and expected result shape.
The design anchors every question to a versioned, owner-approved metric before it exposes any physical schema. When a term fits more than one approved meaning, the system asks the user or sends the question to an analyst. The LLM (large language model) proposes SQL; a parser checks the query tree against policy and a scan budget, and a read-only gateway runs it under the warehouse's row and column security. The answer carries the SQL, lineage (where each number came from) and freshness, the prose is checked against the numbers, and every run is audited so it can be replayed later.
The core idea fits in one sentence: the metric registry defines the business answer, and the LLM only translates the question and explains a validated, read-only result. The figure shows the decision every question passes through.
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.
- We resolve who the executive is and which rows they may see, before looking at any schema or data.
- We pin "revenue" to Finance's versioned metric rather than a guess about which column looks right.
- If the question is unclear, for example whether an "active customer" means 30-day or 90-day activity, we ask or send it to an analyst. The system does not pick.
- We generate SQL, parse it, cap the scan, then run it read-only.
- We return the number with the SQL, lineage and freshness. Any prose summary is checked against the numbers in the result.
- Next quarter, we can replay who asked, which metric version answered and which SQL hash ran.
The path is metric first, then permitted SQL, then a bounded run, then an explanation built from the result. Writes and invented KPIs stay out of it. The human boundary sits in two places: metric owners decide what a word means, and analysts take the questions the system cannot resolve or the explanations that are board-facing or would trigger an action.
What you need to design
Design a governed natural-language interface to business data. The dangerous constraint comes first: valid SQL must never answer the wrong business question. This case covers one slice, mapping the question to an approved metric and running a read-only query with a paper trail. It does not cover "chat with every table".
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.
The anchor case and the variants built on the same governed query path.
| Case | Shared foundation | What changes |
|---|---|---|
| NL-to-SQL analytics assistant | Governed metric, then permitted schema, then a 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 |
The source's full design pulls these cases together and says what each one contributes. The anchor case supplies the design, requirements, validation, failure drills, evaluation, rollout and delivery. The Executive Dashboard Assistant adds the executive persona, variance explanation and its escalate-to-analyst rule. The Retail Demand Forecast Explanation Assistant adds the planner persona, driver attribution and the correlation-versus-causation risk. The insurer engagement, titled "From Supervisor to Deep Agent", adds the governed metric views, the split between a managed text-to-SQL service and a multi-tool worker, the clarify-below-60% gate and the project story. A self-drill supplies the cost pivot.
This case is for engineers preparing for Forward Deployed, solutions or applied-AI engineering interviews, especially a round that asks you to design a natural-language-to-SQL or analytics assistant. It assumes comfort with SQL and data warehouses, row and column access control, and LLM prompting and evaluation. After working through it, you should be able to explain the system end to end at interview depth, starting from the wrong-answer risk, and answer follow-ups on metric ownership, ambiguity handling, SQL validation, read-only execution, evaluation, cost and rollout.
Read the Design walkthrough first; it is the spoken answer and stands on its own. The Technical deep dives hold the mechanisms behind the follow-up questions: SQL validation, the failure drills, evaluation detail, the insurer engagement and cost. Practise in the Practice section without the page open, and return to the Quick review the night before an interview. The source also links a separate "Natural-Language-to-SQL Analytics Assistant" worksheet for a blank-page attempt; it is not imported here, and the practice prompt covers the same task.
Next: build the answer in interview order.
Start the walkthroughDesign walkthrough
Follow the reasoning from discovery to delivery.
1. Name the wrong-answer risk before drawing anything
Begin with the business-definition risk. A model can generate valid SQL for booked revenue when Finance expects recognised revenue. The query succeeds, but the executive receives the wrong number without an error to warn them. The design therefore needs a governed definition and a check that the proposed query implements it, as well as SQL generation.
Treat the assistant as governed decision support. It translates questions into business definitions that named owners have approved. That requires 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.
The source grades three answers to show what the reframe buys. The weak answer lets an LLM write SQL against the schema and run it. It ignores who owns metric definitions, allows an unapproved reading of revenue, and has no AST validation, no cost bound and no way to notice a confident wrong answer. The average answer adds a semantic layer, validates before running, executes read-only with row limits and logs every query. It still never says what happens when the question is ambiguous, when the schema drifts, or when the prose summary disagrees with the table. The strong answer consults the metric registry before any physical table and turns ambiguity into a clarifying question. It parses SQL into a tree and checks it against policy and a scan budget before a read-only gateway sees it, re-checks entitlements at execution, and proves the design on ten governed metrics with golden cases before any executive sees output.
Declare the non-goals early, as a scope fence. Users cannot author write queries or modify data. The system answers a governed set of business questions; it is not a general-purpose exploration tool for every table in the warehouse. And it does not define what "revenue" means. The business decides that and 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 question below decides a component, so the answers change the architecture rather than decorate it. The first table is the interview-guide version: it says what each question is really probing and what you decide from the answer.
Questions to ask the interviewer, what each is really asking, and what you then decide.
| 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 revenue and Sales means booked, who wins? Or does that dictionary already exist? | Registry scope, owners, and whether you wire to an existing layer or build one. |
| Which warehouse, dialect and approved datasets are in scope? | Are we on 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 (access control lists), or build the missing layer. |
| When a term maps to two metrics or grains, should we clarify, refuse, or send it to an analyst? | If "active customer" could mean 30-day or 90-day, do we ask, refuse, or hand it to an analyst? | Ambiguity gate and review queue. |
| What are the latency and scan-cost limits? Are large requests allowed to run asynchronously? | If a question would scan a year of events, do we block it, queue it, 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? | Is this an FYI chart, or will someone change prices from this answer? | Extra checks and the human-review line. |
The full design asks a slightly different set and ties each answer to a scope decision. Two of its questions are worth adding to the list above: how often definitions change and who approves a change, and which ten metrics matter most.
The full design's discovery questions and the decision each answer drives.
| Question to ask | What the answer decides |
|---|---|
| Who owns each metric definition, how often do definitions change, and who approves a change? | Whether a metric registry exists as a product, and who is the named owner per domain |
| Is there already a semantic layer or metrics catalog, or must this system 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 |
| What is the tolerance for latency versus cost? Synchronous, or async and cached? | Where the sync/async boundary sits |
| Is row-level and column-level security already enforced by the warehouse, or would the assistant reimplement it? | Whether authorisation is reused or rebuilt, which is the classic bug |
| What happens when the assistant is 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 (minimum viable product) scope and the first golden cases |
| What audit evidence must exist so someone can reconstruct why a number was produced? | The query-run record's schema |
Then map the people. Four groups want different things, and the architecture has to satisfy all of them at once. That tension is why the semantic layer and the policy and cost validator are first-class components rather than afterthoughts bolted onto a chat interface.
Users, what they want, the failure each notices first, and what the assistant gives them.
| User | Wants | Failure they notice first | What the assistant gives them |
|---|---|---|---|
| Executive | Fast, correct answers with minimal back-and-forth, never "let me check with analytics" | A plausible number that turns out to be the wrong definition | Governed answers with the definition shown, variance explained, uncertain cases escalated |
| Analyst | Repetitive definitional lookups taken off their plate, without the assistant inventing new interpretations | The assistant redefines a metric they maintain | Golden cases they review; escalation queue; the analyst stays the source of truth during shadowing |
| Data / platform engineer | Bounded blast radius: no whole-warehouse scans, no restricted-column leaks, no company-wide 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 arrive from the practice worksheets. The Executive Dashboard Assistant user asks natural-language KPI questions; the assistant translates them to governed metrics, retrieves dashboard and data context, explains variance, cites metric definitions and escalates uncertain answers to analysts. The Retail Demand Forecast Explanation Assistant user is a planner reviewing forecast variance who asks why demand changed; the assistant explains drivers using sales history, promotions, weather, inventory and events, and recommends planning actions that a person reviews. Neither changes the architecture. Both add a variance-explanation step after the query, which step 9 covers.
3. State requirements as testable constraints
Correctness dominates every other axis. A fast, confidently wrong answer is the single worst outcome, because the executive cannot tell it is wrong, so the system trades latency for safety every time. Asking, narrowing scope or refusing all beat guessing, and depth on ten metrics beats shallow coverage of the whole warehouse.
In an interview, frame requirements in two halves. Functional requirements say what the system does; non-functional requirements say how well it does it and which constraints it must satisfy. The functional core is one pipeline, and the must-haves are its stages:
- Resolve the question to a governed metric first, before touching any physical schema.
- Retrieve only the permitted tables, joins and freshness context needed, never the whole schema.
- Detect ambiguity and ask, rather than silently picking between two approved meanings.
- Produce dialect-specific SQL from the narrowed context only.
- Parse the SQL into an AST and enforce policy against the tree, not the text: tables, columns, joins, query shape and 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 any prose from the structured result and check it against the numbers.
- Audit each query run: actor, decision, SQL hash, bytes scanned, and the metric, schema and policy versions used.
The figure draws those must-haves as the single path a question takes, including the branch where ambiguity stops it.
The should-haves come from the copilot personas: show confidence, missing evidence and the escalation reason when uncertain; collect user feedback and reviewer corrections for evaluation, never for ungoverned training; and give admins controls over source inclusion, freshness thresholds, policy rules, blocked actions and audit export. Richer query planning, human approval for ambiguous cases, learned query ranking, federated sources and semantic search over data dictionaries can wait.
"Good" for the MVP has one definition: the system reliably answers ten governed metrics with full lineage and explainability. If it cannot do that, it is not ready to become a general interface to the warehouse.
The interview guide states the non-functional side as targets.
Non-functional requirements with example targets.
| 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 a suspicious scan does not 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 (time to live); narrow credentials; redacted logs. |
The full design words the same constraints so a test can fail them, and adds compliance and reliability rows. The 3 to 8 second figure comes from the copilot personas, so treat it as an example to confirm with the customer.
Constraints stated so they can be tested.
| Constraint | Stated so it can be tested |
|---|---|
| Correctness | A fast, confidently wrong answer is the worst outcome, so the system trades latency for safety every time |
| Latency | The user-facing path stays synchronous. Anything that only improves future answers moves to background queues. Interactive answers 3 to 8 s for the copilot personas; longer workflows async with progress state |
| Security | A read-only identity that reaches only approved datasets, with warehouse-native row and column policies reused rather than reimplemented. SSO (single sign-on), encryption in transit and at rest, secrets management, no training on customer data unless the contract allows |
| Compliance | Append-only query runs recording actor, SQL hash, policy decision, bytes scanned, and the schema and metric versions used |
| Reliability | Fail closed on policy evaluation, planner timeouts and suspicious scan volume. Degrade on formatting or explanation failures |
| Cost | Scan budgets, row limits, timeouts and bounded date windows, because an unbounded query is a reliability problem as well as a bill. Token budgets and small models for routing |
Every must-have then needs an owner in the architecture. If a requirement has no component, it will not happen.
Each requirement and the component that implements it.
| Requirement | Primary component(s) |
|---|---|
| Anchor on a governed definition | Semantic metric registry, consulted first |
| Retrieve only what is 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 is 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 warehouse table, a write-query tool, or a machine that defines business metrics.
If the interviewer asks "What are the requirements?", the source's short answer is: "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 exist here, and each has one owner. The warehouse catalog owns physical schema truth. The semantic metric registry, maintained by metric owners, owns business definitions. The identity provider owns authentication, and the policy store owns access decisions. Caches hold schema snippets, metric lookups and recent plans only as a performance layer, with TTLs and version stamps so the system can explain what it used; a cache owns none of this truth.
A fourth kind of state belongs to one request only: the question interpretation, the candidate SQL, its AST, the validation result and the execution trace. That workflow state is short-lived and must not quietly become hidden durable state.
The table lists every source the assistant may touch, who owns it, how fresh it is, how access is decided and what goes wrong with it.
Data sources, owners, freshness, permission models and risks.
| 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 (business intelligence) dashboards | Dashboard owners | Refresh time per dashboard | Dashboard sharing | Stale refresh presented as current |
| Financial planning, CRM, ERP | Finance and sales systems owners | Daily to weekly | Source-system roles | Numbers that disagree with the warehouse |
| Forecasting platform, POS sales, inventory, promotions calendar, pricing, weather and event feeds (retail persona) | Planning and merchandising | Daily; feeds hourly | Region and store scope | Stale promotions data; correlation read as causation |
Three core records hold the design together. Metric(id, name, definition, dimensions, owner, version) is the governed definition. SchemaAsset(id, engine, object, columns, sensitivity) describes a physical object and how sensitive it is. QueryRun(id, actor, sql_hash, policy_decision, bytes_scanned, result_ref) is the audit record; it also stamps the metric, schema, policy, prompt and model versions so a changed number can be reconstructed. The persona-specific records are in the lineage and variance deep dive.
State the versioning rules aloud, because they are what make "why did this number change?" answerable:
- Retain metric versions long enough to reconstruct why last quarter's dashboard produced a different number from today's. Also record the source-data snapshot or as-of time and retain the result or an approved reproducible reference. A metric version and SQL hash explain the requested computation, but cannot reproduce its old value after the underlying rows change.
- Make QueryRun write-once and append-only, because incident review and adoption analysis both start from query history.
- Version every artefact that influences behaviour (metric definitions, schema snapshots, policy bundles, generated plans). Without that, the system works in the happy path and fails at rollout.
- Put idempotency keys on question submission and feedback, so a retried submit does not create a duplicate, and optimistic concurrency on metric edits, so one team cannot silently overwrite another team's definition.
5. Draw the architecture end to end
Explain the architecture as a chain of trust boundaries in dependency order, not as a flat list of boxes. The interview-size view below keeps the organising idea visible: the LLM interprets and explains, while the registry, policy, warehouse and analysts keep authority.
Walk one question through it in eight steps:
- Authenticate the user and resolve entitlements before any schema or data lookup.
- Use an LLM-assisted resolver against the versioned metric registry. If "revenue" has several supported meanings, clarify or escalate; do not guess.
- Retrieve only the allowed schema, join path, lineage and freshness facts needed for the selected metric.
- Generate dialect-specific SQL from that narrow context. The model proposes a query; it does not approve one.
- Parse the SQL into an AST, enforce table, column, join and read-only rules, recheck entitlements and estimate scan cost. Reject or narrow anything unsafe or over budget.
- Execute through a bounded read-only gateway, running the query as the user (on-behalf-of) so warehouse-native row and column security applies to them, with timeout and row limits.
- Summarise the structured result and verify every number against the table. On a mismatch, return the table alone and alert reviewers.
- Return the definition, SQL, lineage, freshness caveats and answer; record the versions, decision and bytes scanned for replay.
The full design draws the same flow in more detail and adds the organising split: the control plane holds definitions, policies, schedules and evaluation rules, which change through releases, while the data plane handles each question as a request.
The background lane sits beside the request path. Its jobs improve future answers, so none of them blocks a question.
Four operating rules go with the diagram:
- Version metric definitions, table/column/join policy, scan budgets, native RLS/CLS, crawl schedules, prompts, models, golden cases and dashboards.
- Recheck entitlement at execution. Enforce narrow credentials, timeouts, row limits and 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 source's component view renders the same flow with its systems of record and queues, and the table after it says what each box is for.
Read the components in dependency order. Every box should answer who owns its state, how fresh it is and why it exists; a box without those answers was premature.
Components, responsibilities, state owners, boundary types and when each is needed.
| Component | Responsibility | State owner | Boundary type | MVP or later |
|---|---|---|---|---|
| Catalog crawler | Ingest warehouse schema, comments, freshness, lineage | Warehouse metadata source | Async background | MVP if warehouse is small; later if manually seeded initially |
| 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 and execution rules | Policy store | Sync | MVP |
| Read-only execution gateway | Submit approved queries with limits and audit | Warehouse credentials / gateway | Sync | MVP |
| Result summariser | Convert rows into 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 |
Point at three boundaries while the diagram is up.
- Sync/async. One rule decides it: anything that must be correct before one answer is returned stays synchronous; anything that improves future answers can be asynchronous.
- Trust. The trust boundary sits at the read-only gateway, which holds the narrowest credentials and no write path. Nothing the model generates reaches the warehouse except through it.
- Consistency. Entitlement and policy are checked at planning and again at execution, so a user who loses access between the two is refused. A material registry version change never silently reuses an old interpretation.
One rule sits beside the three boundaries: the partitioning key for queues follows the natural isolation boundary, usually tenant, warehouse, region or dataset family, so one noisy customer or one large catalog refresh cannot starve unrelated work.
One more decision belongs on the board: is this an agent? The default design is 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, where it routes among a managed text-to-SQL service, a restricted SQL/RAG worker, deterministic analysis and visualisation. Neither that agent nor its LLMs may define metrics or bypass the query gate. The insurer deep dive explains when that extra hop paid for itself.
6. Anchor every question on a governed metric
The semantic layer is the product, and the model is a translator into it. "Revenue last week" must anchor on the governed definition of revenue before the system starts searching for tables, because a model cannot infer a business definition the business has not written down. The system consults the registry before any physical table. Raw schema access is an escape hatch for approved exploratory workflows, never the default.
The insurer engagement made the same choice: a handful of governed metric views instead of raw fact tables. Suppose the agent and a human analyst compute "claims by region" differently, with different date logic or different exclusions. Trust in the whole system collapses the first time someone notices. A metric view makes the KPI definition one versioned artefact every consumer shares.
The interview guide condenses this step into three decisions you should be ready to defend.
Three decisions to defend, with the default, its reason and the failure it avoids.
| Decision | Default and reason | Failure to avoid |
|---|---|---|
| Semantic layer before schema | Resolve a named, versioned business metric before searching physical tables | Valid SQL using 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 | Use reviewed operations or curated text-to-SQL views for common questions; allow hand-generated SQL only in a narrower approved path | Invented columns, excessive scans and permission drift |
Put a router in front of retrieval, because a real deployment mixes 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". For mixed questions, route each subtask to the right source: semantic search finds related prose, structured queries compute counts and sums, and direct lookup resolves IDs. The interview guide's routing table applies that to four questions.
Question routes in the governed assistant.
| Question | Route | Reason |
|---|---|---|
| "Revenue last week" | Versioned metric view and structured query | A financial definition and grain must be selected. |
| "How many high-priority tickets?" | Structured count/filter | Semantic search does not 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 its content. |
The full design's version adds the case where semantic search is the right tool, and says why plain search fails in each of the others.
Question shape, the right tool, and why plain search fails.
| 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 does not fail here; this is the question semantic search is for |
| "How many high-priority tickets did they file last week?" | A 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 ordinary text is wasteful and imprecise |
| "Summarise the pattern across all high-priority billing tickets this quarter" | Both: filter first, then summarise the filtered set | A filter cannot summarise prose; search cannot reliably scope to "this quarter's high-priority billing tickets" |
The structured path itself is a choice between two mechanisms. The first generates a query from natural language and runs it against a small, fixed, well-documented view. That is fast and flexible, but the model can invent fields, so the query must be validated or its result sanity-checked before anyone trusts it. The second calls a small set of fixed, well-defined operations, such as "metric by period and region". That is safer, because what can happen is a reviewed set of operations rather than an open-ended language. Fixed operations are usually the better default in an enterprise. The insurer design made the decision per specialist: a managed text-to-SQL service over curated tables was the safe default, and one deliberately narrower place allowed hand-generated SQL for ad-hoc questions outside the curated scope.
Two rehearsed answers live in this step. When asked how to handle "revenue" with three definitions, 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, and if users ask it often, put it in the semantic layer with explicit aliases. When the interviewer pushes on the riskiest assumption, that the model can infer the right business meaning from the prompt, the source's answer is:
"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
If a question could map to several governed metrics or grain levels, the system stops and asks. A valid query that answers the wrong business question is still a failure, and the costs are lopsided: a clarifying question costs one round trip, while a guess costs an executive decision. The gate has three modes, agreed with the customer in discovery: ask a clarifying question, 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 into simple_kpi, deep_analysis, document_lookup, visualization or conversational with a confidence score, and its clarify node fires only below 60%. "Show me the numbers" therefore gets a clarifying question, not a guess. A threshold makes the behaviour testable and tunable, while "the model will ask when unsure" does not. The 60% is an example from that engagement, not a universal value. A model-reported score of 0.60 is not automatically a calibrated 60% probability of correctness. Compare scores with reviewed intent labels and measure wrong-route and unnecessary-clarification rates before choosing the threshold with the customer. Even a high score must not override two conflicting approved metric definitions.
Ambiguity is also a freshness signal. When the catalog is stale beyond a threshold, the retriever refreshes through the async queue before allowing generation, falls back to a narrower supported question set, or asks. It never silently generates against an unknown schema. A stale schema and an ambiguous definition are different reasons to stop, and both mean the system should not pretend precision. For a business-definition conflict the failure policy is human intervention, because a wrong answer is worse than a slower one.
8. Treat SQL as an untrusted proposal, then execute read-only
The LLM proposes SQL from a narrow, authorised metric and schema context. Treat that SQL as untrusted input. Valid SQL is not safe SQL: a query can parse, run and still touch a hidden column, scan a year of events or multiply rows through a bad join.
A dialect-aware parser builds the AST, and policy checks the tree rather than the text: the statement type, physical tables, columns, functions, joins, aggregate semantics, limits, date filters and cross-join or fan-out risk. A hidden-column request must fail even if the SQL is syntactically valid. Then a cost estimator checks bytes, time and row limits before the query is admitted, and a live timeout cancels any overrun.
Authorisation is several independent controls, so one failing does not expose data:
- least-privileged, read-only credentials;
- warehouse-native row and column policies evaluated for the end user (on-behalf-of), not for 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 cannot rewrite access predicates, the filters that restrict which rows a user sees. Execution is risk-based: auto-run only when confidence is high, the query fits an approved pattern, the user has permission and the 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. And never retry a policy denial with a stronger model: a denial means the request is not allowed, not that the model was too weak.
The SQL policy deep dive shows 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 executive reads the prose, not the rows. So the summary must be generated from the structured result, and its key values cross-checked against the table. Reject any summary whose numbers do not match: return the table alone and alert the review queue. If the summary generator is down or untrusted, degrade to the table rather than fabricate confidence.
Take an illustrative case: the table says Q3 recognised revenue is 41.2 million, and the draft summary says "revenue rose to 42 million". The cross-check finds 42 nowhere in the result, so the executive sees the table, SQL and lineage without the sentence, and a reviewer sees the rejected draft.
The two copilot personas extend the summary into an explanation, and the same rule holds: every driver named must trace to a query. The executive copilot explains variance against the governed definition, cites the metric definition it used and escalates uncertain answers to analysts. The retail explainer attributes a forecast variance to drivers from sales history, promotions, weather, inventory and events, then recommends planning actions that a person reviews before any order changes. Its red-team list names the risks: confusing correlation with causation, hallucinated drivers, stale promotions data, recommendations biased against stores or regions, and over-ordering because an explanation sounded confident.
Keep the statistics deterministic. The insurer design's analysis agent computes Z-score anomalies and trend statistics rather than reasoning about them, so the model cannot invent a plausible but wrong number. The explanation layer then narrates computed drivers; it never produces them. Correlation is not proof of causation, and the assistant may not turn one into the other. Show confidence, missing evidence and the escalation reason whenever the drivers are weak, and route board-level narratives through an analyst before they leave the system.
10. Fail closed on policy, degrade on everything else
A strong answer says exactly what fails open, what fails closed, what degrades, what queues and what escalates to a person. Incidents deserve different reactions: a policy engine outage is not a visualisation glitch, and a scan that explodes cost is not a benign cache miss. Memorise the pattern by category: authorisation closed, connectivity degrade or queue, ambiguity human, suspicious scan closed and alert.
Failure situations, the preferred policy and why.
| Situation | Preferred policy | Why |
|---|---|---|
| Authorisation or policy evaluation fails | Fail closed | Better to deny than to expose data accidentally |
| Warehouse connection is briefly unavailable | Degrade or queue, depending on 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 may still get a safe, reduced answer path |
| Ambiguous metric mapping or business-definition conflict | Human intervention | A wrong answer is worse than a slower answer |
| Execution produces a suspicious row count or scan volume | Fail closed and alert | Treat unexpected scale as a probable correctness or cost issue |
The interview guide's playbook turns those policies into responses to symptoms you can observe.
Failure playbook: symptom and 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. Do not substitute an unrestricted service account. |
| Warehouse or summary service unavailable | Queue if freshness permits; return a 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. |
Notice the row about the policy engine. When the check that protects data is down, the tempting shortcut is to run the query through a broad service account so the user still gets an answer. That shortcut is exactly the leak the design exists to prevent. A suspicious row count or scan volume is also more than a billing issue; treat it as a sign the query may be wrong. The five failure drills walk each failure from detection to prevention, with the source's flow for each.
11. Keep the answer path synchronous and scale the rest
Keep metric resolution, authorisation, validation and execution synchronous, because together they determine the one answer the user gets. Crawl catalogs, refresh caches and replay evaluations asynchronously, partitioned by tenant or warehouse so background jobs do not stampede query traffic. Cache only with the tenant, permission signature, metric and schema version, and freshness in mind; 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 warehouses), token spend and p95 latency by stage. The source flags warehouse compute more than 20% above the seven-day baseline as a cost warning.
The cheapest levers are narrower metric context, approved templates, dry-run cost checks, bounded windows and safe caching. Repeatedly asking a stronger model to repair invalid SQL raises both bills and can still answer the wrong question. The cost deep dive and the cost pivot develop this.
12. Gate the release on semantic correctness, not execution success
A query that runs can still be wrong, so the evaluation separates two measures. Execution accuracy asks whether the SQL runs and matches the expected result; the golden-set replay proves it. Semantic correctness asks whether the query answers the governed business question; only analyst review against the governed definition proves it, and it is the release gate. Zero escaped policy violations is a separate gate, owned by Security.
Golden cases pair the user's natural-language question, the approved SQL and the expected result shape. They include easy examples, ambiguous paraphrases, edge cases with filters, grain and date windows, unauthorised columns, large scans, join fan-out, and 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.
The table sets a threshold, a method and an owner for every measure. The 4.2/5 trust target and the copilot percentages are source examples to agree with the customer, not product standards.
Evaluation metrics, thresholds, methods and owners.
| 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 scanned 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 plus 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 |
Falling trust matters even while usage rises. An answer that users still ask analysts to recheck has not solved the workflow. The evaluation deep dive covers the four measurement buckets, the layered dashboard and the red-team list.
13. Roll out ten metrics at a time
The rollout must prove three things in order: the assistant answers a narrow set of governed questions correctly; it does so safely under policy; and real users adopt it because it improves their workflow rather than impressing them in a demo. The rollout runs in five stages: ten governed metrics with owners, golden replay on every change, shadow analysts on live questions, a small executive release, then domain-by-domain expansion with a named metric owner. Each stage widens the blast radius, and the assistant advances only when the previous stage's exit criteria are met.
The week-by-week plan below gives each stage its gate.
The week-by-week rollout and the gate for each stage.
| Week | Gate |
|---|---|
| 0 to 1 | Ten governed metrics with stable definitions, known owners and visible impact (revenue, active customers, pipeline, churn, support backlog); non-goals documented |
| 1 to 2 | Metric 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 and 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, wrong definition, wrong segment filter) |
| 6 to 8 | Executive release once the assistant 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. The metric owner approves definitions and golden cases. The application owner owns the runtime, prompt assembly, generation and API contracts. The data owner owns warehouse tables, the semantic layer and policy mappings. The security owner reviews access control, audit logging and blocked-query handling. The support owner receives escalations and coordinates rollback.
Roll back on a spike in policy violations, a drop in semantic correctness, a jump in bytes scanned, or users routing around the assistant because they stopped trusting it. Rollback keeps a partial success from becoming an incident.
Decide what is configuration, adapter, shared service and core product, because a Forward Deployed Engineer (FDE) system pays off only when the next customer inherits the stable core and swaps the edges:
- Configuration: metric definitions, allowed domains and rollout thresholds.
- Adapters: warehouse and identity integrations.
- Shared services: query validation, policy enforcement, tracing and audit logging.
- Core product: question understanding, explanation behaviour and safe query orchestration.
Five delivery items make the rollout stick: a canary on a small user group or metric set; staged migration of governed questions from analyst workflows; user training on what the assistant can and cannot answer and how it signals uncertainty; documented escalation paths; and a maintained metric catalog with known limitations. The source closes with three standing risks, each with an owner and a trigger.
Standing delivery risks, owners, mitigations and triggers.
| 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 |
Technical deep dives
Examine mechanisms, alternatives, and operational consequences.
SQL policy is a separate enforcement system
Regex can spot an obvious DROP TABLE string. It cannot understand aliases, nested selects, CTEs (common table expressions, the WITH clauses that name a subquery), comments, obfuscation, or a harmless-looking subquery that becomes unsafe after a rewrite. A parser inspects structure instead: which statements are allowed, which tables, columns, joins and functions appear, whether limits are present and whether aggregate semantics are acceptable. Safety depends on syntax trees and policy rules, not pattern-matching theatre.
Four controls make up the execution boundary. Each stops a different abuse, so together they give defence in depth: if the parser misses something, the read-only identity and the warehouse policies still hold.
Four controls at the execution boundary and the abuse each stops.
| Control | What it does | Abuse it stops |
|---|---|---|
| Least privilege | A read-only identity that can inspect only approved datasets and only the operations needed for analysis | A prompt injection or bad plan becoming a write, delete or privilege escalation. A request for hidden customer emails is rejected because the identity cannot read that column, not because the model probably refuses |
| Warehouse-native row and column policies | Let the warehouse enforce which tenant, region or role sees which slice, instead of reimplementing it in application code | The classic bug where the application filters one path and forgets another; an error in one tenant's policy exposing another tenant |
| Parse, do not regex | Inspect the AST for writes, unbounded cross joins, unauthorised tables, unexpected functions, missing limits and 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 instead of raw data | A second leakage channel through logs; a replayable copy of sensitive output |
The warehouse must receive the intended caller context. In Snowflake, a row access policy executes with the policy owner's privileges so it can consult protected mapping tables. Its expression can use session context, such as CURRENT_ROLE() or CURRENT_USER(), to decide which rows the querying user may see (Snowflake row access policies). Policy-owner privileges and caller identity serve different purposes. A shared service account does not automatically carry the executive's identity. Use a supported on-behalf-of flow or another explicitly validated identity mapping, recheck entitlements at execution, and test the policy with two users whose permitted rows differ. Filter schema metadata to the caller's access too.
The source proves the hidden-column invariant with a small test sketch. A marketing actor may read customer_id, country and plan. The query SELECT email FROM customers is perfectly valid SQL, and the test asserts it is rejected because email is 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_columns splits strings, which is the very approach the rest of this section rejects; it refuses anything beyond a simple SELECT ... FROM and wildcards so the sketch stays honest about its limits. The code also omits its imports (dataclass, pytest). The source says what changes in production: a dialect-aware parser, a policy source from the warehouse or a central registry, and a logged decision with redacted evidence. The test itself is the part worth keeping, run against the real parser and policy path.
After policy, 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, but it need not bound the work needed to produce them. For example, BigQuery warns that LIMIT does not reduce scan cost for non-clustered tables. Use dry-run estimates and an engine-enforced budget such as maximum bytes billed where supported, together with bounded date windows and pre-aggregations (BigQuery cost controls). Cancellation after work begins cannot recover cost already incurred. When a request would scan beyond the configured 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 as well as the bill: a permitted query can still slow other tenants by consuming the warehouse.
Five failure drills and the safeguards around them
Five drills cover the failures that survive unit tests. Each follows the same shape: how the failure shows itself, how to detect it, how to contain it, what evidence to keep and how to prevent it. Containment is scoped by tenant, workflow and metric family, never "all analytics is broken".
Drill 1: the wrong business question
The headline drill. A user asks for "active customers", and the assistant quietly uses login activity where the definition requires paid activity. The SQL returns rows and the chart renders, so nothing looks broken. Detect it by comparing the generated query against governed metric metadata and approved aliases. Contain it by blocking publication and marking the run. Preserve the prompt hash, SQL text, policy decision, asset versions and rejection reason. Recover by routing to a clarified metric choice or human review, and prevent a repeat by tightening the 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, and a previously good template still produces something that looks reasonable. Detect it during plan validation, against catalog versions, not after a failed warehouse call. Fail closed on the affected template, refresh the schema cache, and queue a review if the business definition itself changed. Prevention is a version-stamped cache and regression replay whenever the schema changes.
Drill 3: join fan-out
A join multiplies rows and inflates totals while remaining syntactically valid and passing every SQL check. For example (illustrative), joining orders to a table with one row per shipment counts a two-shipment order's revenue twice. Validate join cardinality assumptions, compare expected row counts against heuristics for the metric's grain, and block suspicious fan-out unless the user explicitly asked for a detailed expansion. If the join cannot be proven safe, refuse or downgrade; never hope the aggregate still looks plausible. Reviewed join paths and golden cases prevent most of it.
Drill 4: excessive scans
Cost is a reliability issue here, because one query can exhaust concurrency and slow other tenants. Estimate before executing. Where the estimate exceeds the threshold, rewrite to a bounded date window or a pre-aggregation if one exists; otherwise fail closed and ask the user to narrow the question or confirm. Per-metric scan budgets and trend alerts catch the slow creep.
Drill 5: the summary contradicts the table
The table is right and the prose misstates it. The response is the summary check from step 9: reject the prose, return the table, SQL and lineage, and notify the review queue. A numeric cross-check against the structured result prevents it from reaching the executive.
The drills at a glance
Each drill: how to detect and contain it, and how to prevent it.
| Drill | Detect and contain | Prevent |
|---|---|---|
| "Active customers" mapped to login activity 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 and add a semantic golden case. |
| Schema drift | Validate plans against catalog versions before the warehouse call; stop affected template and refresh. | Version-stamped cache and regression replay on schema change. |
| Join fan-out | Compare cardinality and row counts with expected grain; refuse unrequested expansion. | Reviewed join paths, heuristics and golden cases. |
| Excessive scan | Estimate before running; use bounded date window or pre-aggregation, otherwise stop and ask. | Per-metric scan budgets and trend alerting. |
| Prose summary disagrees with table | Reject prose and return table, SQL, lineage; notify review queue. | Numeric cross-check against structured result. |
Operational safeguards and backpressure
Around all five drills sit the operational safeguards:
- a bounded timeout on every warehouse query;
- limited, idempotent retries, only when the failure is likely transient;
- no indefinite retry of a policy failure, because a bad prompt is not a network glitch;
- a dead-letter path, holding enough redacted context for support, when a queued request keeps failing;
- a human escalation route for any ambiguous mapping or repeated semantic mismatch.
Treat human escalation as a designed path with an owner and a queue, not an apology. Backpressure belongs to the background lane: crawler and registry refresh jobs sit behind a queue with rate-limited bursts, so they never stampede the warehouse during peak query traffic. The query API degrades gracefully when metadata confidence drops. The compact failure policy reads as one flow.
Measure in four buckets and red-team the definitions
Measure in four buckets, so model quality is never confused with operational health or business value:
- 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 has not solved the problem. The dashboard is layered the same way: 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, or policy blocks that feel arbitrary.
Red-team the definitions as well as the SQL. The source's list:
- Semantic substitution, where 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, where the table is right and the prose misstates the trend.
For the copilot personas, add fabricated business reasons, leakage across regions or business units, stale dashboard refreshes presented as current, and an overconfident board-level narrative.
The source's trust example is 4.2/5 or 80% positive, and a decline across two consecutive review periods is a bad signal even if usage rises. Feedback and analyst corrections feed evaluation only after review; they never flow straight into training.
Lineage, versions and the variance records
The core records (step 4) let you answer "the executive says the number changed since last quarter. Why?" Metric versions are retained, and each QueryRun stamps the metric, schema, policy, prompt and model versions it used, so the two runs are diffed by definition rather than by guesswork.
The executive copilot adds four records:
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 the queries that support it;UserAccess(user_id, metric_id, dimension_scope): which metrics and dimension slices a user may see.
The retail persona adds SKU (stock-keeping unit), Store, Forecast(id, sku_id, store_id, horizon, prediction, confidence), ActualSales, DriverSignal(id, type, value, source, timestamp) and Explanation(forecast_id, top_drivers, confidence, caveats). The shape of those records enforces the rule from step 9. Forecast drivers from promotions, weather, inventory or events are computed from data into DriverSignal rows first, and the Explanation only narrates them, with confidence and caveats attached. The assistant cannot infer a causal claim from a correlation in those signals.
When a supervisor is justified: the insurer engagement
This section is an engagement story from the source, not the default architecture for every NL-to-SQL product. The source author tells it in the first person, as a project they led; the quoted phrases below are theirs. Use it as an attributed reference unless the work is your own.
At a large Asian life insurer, actuaries, claims managers and regional analysts needed answers over governed data, but every question went through a BI queue. An ad-hoc question took days; a new dashboard took weeks. The team built a governed self-service assistant, a minimum viable product in about two months on a short build engagement, and its architecture changed twice.
First pivot: the monolith
One agent, one prompt and twenty-plus tools with full conversation history broke on two axes in real testing. Context bloat: every tool schema sat in context on every turn. Tool confusion: with that many tools competing, the agent picked the wrong one often enough to be unusable. If asked why it broke specifically, the precise answer is that stuffing 20-plus tool schemas plus full history into one prompt measurably degrades tool-selection accuracy. It is a context-bloat effect, not vague confusion; RAG-MCP reports tool-selection accuracy falling as the tool pool grows (Gan and Sun 2025), and OpenAI's function-calling guidance recommends keeping the tools per turn small (OpenAI docs). The fix was architectural rather than a bigger model or better prompting: split deciding what to do from doing it.
The supervisor that shipped
The supervisor is a fixed eight-node LangGraph state machine. Its eight nodes are classify intent, clarify or disambiguate, resolve assets, the four specialists and compose. Routing is a conditional edge, not a node: the diagram draws it as its own box, and it draws clarification on every path, although the clarify edge fires only below 60% confidence.
Intent is classified with a confidence score, and clarification fires only below 60%. The supervisor, and only the supervisor, resolves assets against a 16-asset Context Index of curated text-to-SQL spaces, metric views, tables and document indexes, with endorsed assets ranked first. It passes the resolved list to one of four specialists through shared state. Centralising resolution costs one hop of latency. It buys a single auditable source of truth for what data any answer is based on, which matters because two workers resolving to different tables for the same question is a governance nightmare in insurance.
The four specialists, their tools, and the trade-off each embodies.
| Agent | Role | Tools | The trade-off it embodies |
|---|---|---|---|
| Text-to-SQL | BI specialist | Managed text-to-SQL conversation API | A managed service over a hand-rolled text-to-SQL chain: less flexible, with read-only execution as a required deployment contract. Verify which principal the integration uses: a managed API does not 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 text-to-SQL service's 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 cannot invent a plausible but 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 |
Why LangGraph? Three requirements decided it, and the table records the source's reasoning. CrewAI Flows' @router also gives deterministic branching (CrewAI docs); the source's claim is only that a LangGraph conditional edge states the confidence rule most directly.
The supervisor's requirements and why LangGraph fit them.
| 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 LangGraph 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. In this build the author wrote a custom checkpointer over a table |
| Deterministic composition | A governed insurance environment cannot 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 has 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 (personally identifiable information) filtering on the model endpoints the agent calls. The source notes that, as of 2026, it could not guardrail the agent endpoint itself; verify that against the current platform rather than treating it as a lasting product fact.
A managed multi-agent feature was not 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. So the same fix was applied one level up, as a deep-agent pattern. An orchestrator delegates to fully self-contained sub-agents, one per analytics domain: customer, distribution channels, policy and underwriting, and 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 of preference, fact, decision, project and feedback entries. The cost was more infrastructure surface. The design reduced the tools and history visible to each specialist. That can reduce the original selection problem, but domain routing can still fail and a specialist can accumulate too many tools. Evaluate both routing and within-domain tool selection as domains grow.
Results, stated honestly
In that engagement, the team reported time-to-insight going from days to minutes, and dashboard delivery going from weeks to governed self-serve. Adoption grew after rollout, but the author "can't attribute it cleanly", and the source advises saying exactly that before being asked. These are reported, correlational results from one engagement. The "if rebuilt today" lessons: instrument resolution-time and accuracy metrics from day one rather than relying on tracing for post-hoc debugging, and invest earlier in the offline evaluation dataset.
The design lesson for the main case is narrow. 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.
Cost and scale: measure, route, bound, cache
On this system, the two bills climb for the same reasons: retries on invalid or wrong SQL, and the full schema carried as input tokens on every call. Measure SQL retries, context tokens, warehouse compute (bytes scanned or compute time), first-try success, p95 latency and cost per answer before changing models.
Model cost and warehouse cost need separate budgets because they use different units. Warehouse compute per answer is the cost metric that matters on the warehouse side: bytes scanned on BigQuery on-demand pricing (BigQuery pricing), credit time on Snowflake and similar warehouses. Scan budgets and bounded date windows are the lever, and a rising seven-day average is the alert; the source's example threshold is more than 20% above that baseline.
Every strong cost answer comes from four verbs, in order:
- Measure: trace and attribute spend first, per stage and per answer.
- Route: match the model and the 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, that means shrinking context to metric definitions and a few permitted tables, using reviewed operations or managed SQL for common paths, dry-running cost, caching versioned metric metadata and recurring executive questions, and capping scans and date windows. A stronger-model retry loop cannot repair a missing business definition. Background 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.
Sources and provenance
The November review corrects the Snowflake policy description and separates result limits from scan budgets using the linked Snowflake and BigQuery documentation. The engagement's architecture, timings and reported outcomes remain attributed source material. They are not measurements reproduced by this reader.
The source checked these references on 27 September 2026. Each supports a specific claim above: Snowflake for the distinction between policy-owner privileges and querying-session context (SQL policy); OpenAI and RAG-MCP for keeping tool counts small (insurer engagement); CrewAI for deterministic branching in Flows; BigQuery for on-demand queries billing by bytes processed (cost).
- Snowflake docs: Understanding row access policies: policy expressions execute with owner privileges and can inspect querying-session context to determine visible rows.
- OpenAI API docs: Function calling: guidance to keep the tool count per turn small.
- Gan and Sun 2025, RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection: tool-selection accuracy falls as the tool pool grows.
- CrewAI docs: Flows:
@routergives CrewAI deterministic branching. - BigQuery pricing: on-demand queries bill by bytes processed.
The numbers in this case 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 and the copilot percentages. Confirm each with the customer, and check current warehouse documentation for execution identity, policy coverage and cost estimation before implementing.
Practice
Attempt the case before revealing the worked reasoning.
Attempt the design on a blank page
Design a natural-language assistant that lets executives and analysts ask governed business questions and get an answer they can put on a slide. Close the page and take "What was revenue last week?" from question to answer: discovery questions, the metric it resolves to, the permitted schema, the SQL proposal, the AST and cost checks, read-only execution and the table-to-prose check. Then handle four changes: "revenue" has two approved meanings; the user loses access between planning and execution; a join key changed overnight; and the scan estimate is ten times the budget. Finish with a ten-metric release plan and say who owns a wrong definition.
The self-checks, follow-ups and drills below come from the source. Try each answer aloud before opening it.
Work through your answer
This local worksheet is a prototype addition. Notes save in this browser. Nothing is submitted or scored.
Check your reasoning
Reveal the self-assessment rubric
This checklist is an authored addition. Assess what you can explain without reopening the walkthrough.
0 of 9 reasoning checks covered.
Check yourself
Why is a wrong-definition answer more dangerous than a failed query?
The SQL ran, the chart rendered and the number looks plausible, so the executive cannot tell it is wrong and acts on it. A failed query at least announces itself.
What is consulted before any physical table, and why?
The semantic metric registry, because "revenue" must anchor on the governed definition before the system searches for tables the model thinks look relevant. The registry fixes meaning, grain, dimensions and owner first.
What number makes "ask when unsure" testable?
A confidence threshold on intent classification. The insurer supervisor clarifies below 60%. That figure is one engagement's number to calibrate with the customer, not a universal default.
Why parse SQL instead of regex-filtering it?
Regex cannot understand aliases, nested selects, CTEs, comments or obfuscation. A parser inspects statements, tables, columns, joins, functions, limits and aggregate semantics, so policy is enforced on the structure the warehouse will actually run.
Where is row-level security enforced, and what is re-checked at execution?
In the warehouse, natively, with the read-only query run as the user so the policies apply to them, not to a shared service account. Entitlement and policy are re-checked at execution, so a user who lost access between planning and execution is refused.
How is a summary that contradicts its table handled?
The summary is generated from the structured result and cross-checked against it. A mismatch returns the table alone and alerts the review queue.
State the fail-open versus fail-closed pattern by category.
Authorisation closed; connectivity degrade or queue; ambiguity human; suspicious scan closed and alert. A low-risk formatting or explanation failure degrades to the table.
What is the release gate, and what is it not?
Semantic correctness against the governed definition, judged by analyst review. It is not execution success on the golden set, which only proves the SQL ran. Zero escaped policy violations is a separate gate.
Name the five rollout stages and the exit of the third.
Ten governed metrics, golden cases, shadow analysts, a small executive release, domain-by-domain expansion. The assistant leaves shadowing when it consistently matches analyst-reviewed answers and escalation works; that opens the executive release.
Why did the insurer monolith fail, and why did the same fix apply twice?
Context bloat and tool confusion from 20-plus tool schemas and full history in one prompt. The supervisor's own tool list later re-approached the same bloat, so specialisation was applied again at the next level, as domain sub-agents with small toolsets.
What is the sixty-second cost answer?
The semantic layer and validation remove retries and the schema from every prompt, so the fix is not a stronger model retrying until the SQL runs. Measure first-try success, retry rate and cost per query, and bound the warehouse side with scan budgets.
Answer the follow-up probes
How do you handle "revenue" with three definitions?
Name the ambiguity and force clarification. Show the supported definitions, default only where the business has an approved canonical meaning, and surface the definition used. If it is asked often, put it in the semantic layer with explicit aliases.
What if the SQL is valid but catastrophically expensive?
Valid is not safe. A cost-estimation and policy step before execution looks for unbounded scans, missing date filters, explosive joins and table-specific budget breaches. If it is too expensive, narrow the question, propose a cheaper rewrite, or require a privileged approval.
What is the riskiest assumption in this design?
That the model can infer business meaning from the prompt. The rehearsed line: "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."
How do you keep a service account from reading unrestricted data on a user's behalf?
Run the query as the user (on-behalf-of login) so warehouse-native RLS/CLS applies to them, not to the service account. Resolve entitlements per request and re-check them at execution, and filter schema metadata to what the user may see.
Two queries look different but should return the same number. How do you know?
Golden cases pair the question, approved SQL, expected result shape and expected values on a fixed test dataset. Compare both queries on that fixture, including nulls, duplicate join keys, date boundaries and grain. Matching SQL text is unnecessary, but matching shapes alone cannot establish the same number. Analyst review still checks that both computations implement the governed definition.
The executive says the number changed since last quarter. Why?
Metric versions are retained, and the query run records the metric and schema versions used, so the two runs are diffed by definition, not by guesswork.
How does an executive get an explanation as well as a table?
The summary is generated from the structured result and cross-checked against it; drivers are computed deterministically and narrated; uncertain explanations are escalated to an analyst. Step 9 of the walkthrough covers it.
Repair the weak answers
Each line below is a weak answer an interviewer will hear often. Say the repair before opening it.
Repair: "Let the LLM write the SQL."
Registry first, AST policy, read-only gateway. The metric registry fixes meaning before any table is seen, the parsed tree is checked against policy and a scan budget, and only the gateway touches the warehouse.
Repair: "The database handles permissions."
Warehouse-native policies reused, plus an entitlement re-check at execution, with the query run as the user rather than a shared service account.
Repair: "We'll test the SQL."
Golden cases judged for semantic correctness against the governed definition, not only for whether the SQL runs.
Repair: "It will ask when unsure."
A confidence threshold with a number, such as the insurer's clarify-below-60%, so the behaviour can be tested and tuned.
Repair: "We'll just run it and see."
Cost estimation before execution, with a bounded window, pre-aggregation, narrowing or privileged approval when the estimate breaches the budget.
Defend the trade-offs
Name each trade-off with a balanced verdict, then tie it back to the customer outcome.
Raw schema prompting or a semantic layer?
Default to the layer for governed metrics. Allow raw schema only for approved exploratory workflows, as an escape hatch.
Automatic execution or approval?
Risk-based execution: auto-run only on high confidence, an approved pattern, permission and low cost; otherwise show the draft and ask.
Flexibility or templates?
A hybrid: templates for common governed workflows, free-form for the long tail, and a policy gate deciding when free-form is allowed.
Speed or warehouse cost?
Bound the search space with the semantic layer and cache aggressively for repeat questions. Treat any large scan as a signal to narrow scope, not to optimise the query.
Deliver it in fifty minutes
Begin with the customer's pain, not a diagram: executives want governed natural-language answers with correct definitions and no unsafe queries. Then spend the minutes where the risk is.
The fifty-minute delivery plan.
| Minutes | Phase |
|---|---|
| 0 to 5 | Discovery: the questions in step 2, the ten metrics, the meaning of revenue |
| 5 to 10 | Success and failure in business language: correct interpretation, acceptable latency, low unsafe-query rate, adoption; and the failure modes: wrong business question, RLS leakage, harmless-looking expensive scans |
| 10 to 18 | Sketch the architecture with the semantic layer in the centre; raw schema access as an escape hatch |
| 18 to 28 | Trade-offs, each tied back to the customer outcome |
| 28 to 35 | Security and correctness end to end; the service account cannot query unrestricted data on behalf of users |
| 35 to 50 | One implementation slice (validation and approval for one metric), rollout gates, questions |
Give the 90-second architecture summary.
The source's spoken version, in the first person as an interview answer:
- We're building a governed natural-language-to-SQL assistant for executives and analysts who need fast answers but cannot afford incorrect metrics or unsafe queries.
- I'd put a semantic layer between the model and the warehouse so the assistant generates SQL from approved business definitions rather than raw table names.
- The service would accept a user question, classify intent and risk, resolve the relevant metric definitions, generate a constrained draft query, validate it for policy and cost, and then either execute automatically or route for approval depending on sensitivity and confidence.
- Row-level security must be enforced in the warehouse, not in the prompt.
- I'd log the question, the generated SQL, the metric mapping, the cost estimate, the execution result and the user identity for audit and debugging.
- The biggest trade-off is flexibility versus correctness: I'd optimise for governed answers first, then add templates and fallback pathways for the long tail.
- My first rollout gate would be a small set of executive metrics with a golden test corpus and a hard stop on ambiguous or expensive queries.
Give the 2-minute spoken answer.
- The naive pitch here is to let an LLM write the SQL, and that loses immediately, because generation is not the hard part.
- The hard part is that "revenue" might mean booked, recognised or collected, and a syntactically perfect query against the wrong definition is a governance failure dressed up as a working feature.
- So I would reframe the problem as building a governed decision-support system that only speaks in terms the business has already agreed to.
- That means three things from day one: a semantic layer of governed metric definitions, a safety boundary around the warehouse that is read-only and cost-bounded, and an explicit way to say "I don't know which definition you mean" instead of guessing.
- Architecturally, the query API authenticates and resolves entitlements, the metric registry is consulted before any physical table, the schema retriever pulls only what is needed, ambiguity triggers a clarifying question, and the generated SQL is parsed into an AST and checked against policy and a scan budget before a read-only gateway executes it with timeouts and row limits.
- I would prove it on ten governed metrics with golden cases pairing question, approved SQL and expected result, then shadow analysts before any executive sees output, then expand domain by domain with named metric owners.
- Success is not a fast answer; it is an answer nobody has to re-check.
Give the six-point interview answer from the interview guide.
- I would first ask who owns the metric definitions, because valid SQL against the wrong meaning of revenue is the worst failure here.
- I would resolve each question to a versioned governed metric, clarify ambiguity, retrieve only permitted schema, and let the LLM propose SQL from that small context.
- An AST policy and cost gate rechecks entitlements before a read-only warehouse gateway runs it as the user, under native row and column controls.
- The answer includes the definition, SQL, lineage and freshness; any prose is cross-checked against the table.
- I would prove ten metrics with golden cases and analyst shadowing before executives rely on it.
- At scale I would trim schema context, use reviewed routes, bound scans, and measure semantic correctness and cost per answer.
Memory line: "The semantic layer defines the answer; the LLM translates and explains it."
Recite the nine lines that carry the round.
- "The danger isn't failing to produce SQL. It's producing valid SQL that confidently answers the wrong business question."
- "Anchor on the governed metric before touching a table. The semantic layer is the product."
- "Ask rather than guess. A clarifying question costs a round trip; a guess costs a decision."
- "Parse, don't regex. Safety lives in the syntax tree, not in pattern matching."
- "Row-level security is enforced in the warehouse, not in the prompt."
- "Valid SQL is not safe SQL. Estimate cost before you execute."
- "Anything that must be correct before one answer is returned stays synchronous; anything that improves future answers can be asynchronous."
- "Ten metrics, golden cases, shadow analysts, then domain by domain. Trust is earned, not assumed."
- "Success is not a fast answer; it is an answer nobody has to re-check."
Score a dry run on six dimensions: estimation, architecture, depth (ambiguity, cost, failure paths), security (authorisation, RLS, validation, audit), delivery (gates, fallback, support) and communication. A miss in any one is a design gap to fix, not a phrase to memorise.
Tell it as something built
For "tell me about a project you led end to end", the source tells the insurer engagement as an architecture evolution with two real pivots. The story is the source author's. Use its structure for your own project, and never present someone else's engagement as yours.
How does the source structure the story, beat by beat?
Lead with one sentence, then stop talking: "At a large Asian life insurer, I built a multi-agent system to replace a BI queue that took days with natural-language, self-serve answers, and my first design broke down live in testing, which is actually the more interesting part of the story."
Problem beat: actuaries, claims managers and regional analysts needed answers over governed data; an ad-hoc question took days and a new dashboard took weeks.
First pivot: one agent with twenty-plus tools failed on context bloat and tool confusion; the fix split deciding from doing.
Supervisor beat: eight nodes, clarify below 60%, central asset resolution against a 16-asset index, four specialists.
Governance beat: governed metric views, thread-keyed short-term memory, overlay prompts with a five-minute cache, MLflow tracing on every node, and a model gateway for rate limits and PII filtering.
Second pivot: the supervisor's tool list re-approached the bloat, so domain sub-agents and a memory manager applied the same fix one level up.
Results: days to minutes, weeks to governed self-serve, an MVP in about two months, and adoption growth stated as not cleanly attributable, before anyone asks.
Close on whichever thread the conversation ended on. On the pivots: the same failure showed up twice at two scales, and both times the fix was the same instinct, specialise and keep each unit's context small. On governance: at an insurer, what counts is a system provably safe to hand to a regulated business user. On results: better to say exactly what can and cannot be claimed than to let a number go unquestioned.
Respond to the cost pivot
After a good design, the interviewer's pivot is "the warehouse bill and the model bill are both climbing". The weak move is to retry with a stronger model until the SQL runs. The strong move is the design already on the board.
Both bills are climbing. What do you do in ten minutes?
Name the driver, take the cheapest lever, prove it with a metric, and say what not to do. The table is the source's full answer.
The ten-minute cost pivot.
| Part | Answer |
|---|---|
| Dominant driver | Retries on invalid or wrong SQL, and the full schema carried as input tokens on every call |
| Cheapest lever first | Semantic layer so the prompt carries metrics not tables; validate and dry-run SQL before execution; cache metric definitions and recurring executive questions; small model for routing |
| Metric that proves it | First-try success rate; retry rate; cost per query; P95 latency |
| Do not | Retry with a stronger model until the SQL runs |
| The sixty-second line | "Valid SQL that answers the wrong question is the failure, so the fix is a semantic layer and validation, not more retries. That also removes the schema from every prompt." |
Add the warehouse side in the same breath: warehouse compute per answer (bytes scanned on BigQuery on-demand, credit time on Snowflake and similar), scan budgets and bounded date windows as the lever, and a rising 7-day average as the alert. Then name the four verbs: measure by tracing and attributing first; route by matching model and path to risk; bound steps, tokens, top-k, timeouts and budgets; cache safely with tenant, permission and version in the key.
Calibrate your answer to the level
On this design the levels separate on who owns the meaning of a number and how a wrong one gets caught. The quality of the generated SQL does not separate them.
How senior, staff and principal answers differ.
| Level | Sounds like | Missing |
|---|---|---|
| Senior | Resolves each question to a versioned metric before touching a table, asks when "revenue" fits two definitions, and checks the parsed AST against policy and a scan budget. Runs it read-only as the user under warehouse-native row and column security; authorisation fails closed, and a summary that disagrees with the table is dropped. | How a correct-looking wrong answer is caught and proved: who owns each definition, semantic correctness as the release gate, schema drift, join fan-out and a replayable query run. |
| Staff | Adds named metric owners who approve definitions and golden cases, analysts in shadow mode judging semantic correctness apart from execution success, and zero escaped policy violations as Security's gate. Rolls out ten metrics before executives, then domain by domain, with rollback on semantic mismatch, policy leakage, compute more than 20% above the seven-day baseline or falling trust. | What happens as domains and specialists multiply: tool bloat, when free-form SQL is allowed, and which parts the next customer inherits. |
| Principal | Treats the semantic layer as a product the business owns, versioned so a changed board number is diffed by definition, and splits configuration, adapters, shared services and core so the next customer swaps only the edges. Prefers fixed operations or managed SQL with one narrower free-form path, and keeps each specialist's toolset small, the lesson the insurer's 20-plus-tool monolith taught. | The clarify threshold, per-metric scan budgets and the canonical meaning of "revenue" wait for discovery; the insurer's 60% was one engagement's number, not a default. |
Return to the decisions you could not explain.
Review the essentialsQuick review
Recall the decisions, failure responses, and closing answer.
The one sentence and the flow
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 flow: identity, then governed metric, then the ambiguity gate, then permitted schema, then the LLM's SQL proposal, then the AST policy and scan-cost check, then the read-only warehouse with native security, then the numeric cross-check, then the answer with SQL, lineage and caveats.
Agent role: the default is a governed query workflow. Use a supervisor only for a real multi-specialist task; it routes, while 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?
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; do not 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. MVP: ten governed metrics, golden question/SQL/result cases, analyst shadowing. Copilot example: 3 to 8 s interactive. Asian life insurer example: clarify intent below 60%; a handful of governed metric views; eight-node supervisor; 16-asset index. Cost signal: warehouse compute per answer (bytes scanned or credit time) more than 20% above the seven-day baseline. Trust example: 4.2/5 or 80% positive. Copilot evaluation examples: at least 90% supported claims, 95% correct citations and 95% correct high-risk escalation. These are source examples to confirm with the customer.
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. |
Cost answer: measure retries, tokens and warehouse compute (bytes scanned or compute time). Send metric definitions rather than the full schema; prefer approved operations, dry-run SQL, cap scans, and cache only within tenant, permission and version scope. Do not retry a wrong definition with a stronger model.
The fourteen takeaways, in the order the walkthrough teaches them:
- The failure to design against is valid SQL that confidently answers the wrong business question, named in the first two minutes.
- Requirements are stated so a test can fail them: correctness over speed, ten governed metrics as the definition of good, and an owner for every constraint.
- State has one owner each: the catalog owns schema truth, the registry owns definitions, caches are performance only, and every behaviour-changing artefact is versioned.
- One end-to-end diagram splits control plane from data plane, and the trust boundary is the read-only gateway with entitlements re-checked at execution.
- Every question anchors on a governed metric before touching a table, with a router deciding structured, semantic or both, and fixed operations preferred over open generation.
- Ambiguity triggers a clarifying question, with a numeric confidence threshold, never a guess.
- SQL is validated as a tree against policy and a scan budget, and executed read-only under warehouse-native row and column security.
- Explanations are generated from the structured result, cross-checked against the table, and built on deterministic statistics.
- Authorisation fails closed and everything else degrades, with five rehearsed drills from wrong definition to summary drift.
- The release gate is semantic correctness judged by analysts, not execution success.
- Rollout runs ten metrics, golden cases, shadow analysts, a small executive release, then domain by domain with named owners.
- The fifty minutes are spent in proportion to risk, with the 90-second summary, the 2-minute answer and nine carrying lines ready.
- As a story, the same system is a two-pivot engagement: a monolith that failed on context bloat, a supervisor that shipped and 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: "Ten governed metrics, a clarifying gate, AST and cost checks, read-only execution, and analyst-reviewed semantic correctness before executive rollout."