Module 5 · Case studies II · Chapter 21 · Free
Case study: a data analysis copilot over a warehouse
- Analysts ask in plain English. The copilot writes SQL, runs it, and answers with a chart, the numbers, and the SQL.
- Safety lives in the database, not the prompt: a read-only role, row filters, and cost caps.
- Money words mean one thing: a governed metrics layer defines revenue once.
The picture: a junior analyst with a library card. Approved shelves only, workings always shown, and the library decides what stays locked.
Company: Kestrel Retail Group, a made-up retail chain invented for this chapter.
Product: A data analysis copilot over a sales warehouse. Plain English in, SQL run, chart plus numbers plus SQL out.
Users: Analysts and merchandisers, about 3,000 questions a month (illustrative).
Hard constraints: Read-only access enforced by the database. Row-level permissions per region. A cost cap on every query. Metrics from a governed layer.
Kestrel Retail Group is invented. Version one launched with one prompt rule: "never change any data." A merchandiser then asked it to "clean up the test rows while you are in there."
- The model wrote a data-changing statement. Only a lucky database error stopped it.
- The same week, one question scanned a raw events table and ran up a large bill (illustrative). Analysts went back to hand-written SQL for two months.
The lesson: a prompt is advice. A database role is a lock.
- Start from requirements, then walk the architecture.
- See which patterns appear, and why each one earns its place.
- Read the tradeoffs, then what broke in production style failures.
- Do the cost and latency maths, all illustrative.
- Break a guardrail config, fix it, then redesign for store managers.
Next: the requirements that shaped every choice.
Step 1: Context and requirements, the design method in brief
Use the design method from Chapter 4: requirements, constraints, patterns, tradeoffs, eval plan. Kestrel did it in one page.
- Job: answer questions like "why did trainer sales dip in the north last month?" in under a minute.
- Trust: every answer shows its SQL, so an analyst can check it.
- Safety: no writes, no cross-region rows, no runaway scans.
- Truth: revenue and margin come from the metrics layer, defined once by finance.
Think of the metrics layer as the one recipe book in a busy kitchen. Every cook uses the same recipe for the house sauce.
Where the picture breaks down:
- A recipe book cannot invent a new dish. New metrics wait for a definition.
- Cooks can still plate badly. The layer fixes definitions, not chart choices.
Next: the architecture, walked one question at a time.
Step 2: The architecture, from words to a checked answer
Press Next. Follow the trainer question from words to SQL to a checked, auditable answer.
- A merchandiser asks why trainer sales dipped in the north last month. The app adds who is asking, so region rules can apply.
- Retrieval fetches the metric definitions for trainer sales and revenue, plus the schema docs for the sales tables. The model works from those, not from memory.
- The model returns SQL in a fixed shape, plus the metrics it used. Money questions must call the metrics layer.
- Code parses the SQL, checks the table allowlist, estimates scan cost, and rejects anything over the cap or off the list.
- The warehouse runs it as a read-only role. Row filters add the asker's region inside the database, where the model cannot remove them.
- The reply shows a chart, the numbers, and the exact SQL. Anyone can rerun it and get the same result.
Predict first:
Validation rejects it. Valid SQL can still use the wrong definition. Money questions must go through the metrics layer, and the answer always shows its SQL, so hiding it is never an option.
Next: the pattern map, then the worked numbers.
Step 3: Worked example, one question end to end
All figures in this section are illustrative. Follow the trainer question:
- Retrieval returns 3 metric definitions and 2 table docs, about 900 tokens.
- The model drafts SQL on the governed sales view, by week, north only.
- The validator estimates a 0.4 GB scan. The cap is 10 GB, so it passes.
- The warehouse returns 8 rows. The answer shows a week 3 dip, the numbers, and the SQL.
Cost maths (illustrative): 2,400 input tokens and 300 output tokens. At an illustrative price of $3 per million input and $15 per million output: 2,400 / 1,000,000 x $3 = $0.0072, plus 300 / 1,000,000 x $15 = $0.0045, about $0.012. The scan adds about $0.002. Total: roughly 1.4 cents.
Next: which patterns carry this design.
Patterns used and why
| Pattern | Where it appears, and why |
|---|---|
| Structured generation (Chapter 6) | The model returns SQL in a fixed shape, then a validation pass parses it before anything runs. |
| Retrieval (Chapter 5) | Metric definitions and schema docs are fetched per question, so answers use governed meanings. |
| Guardrails (Chapter 10) | Read-only role, table allowlist, row filters. Strong checks sit below the model, not in its prompt. |
| Eval loop (Chapter 11) | Golden questions with hand-computed expected results run on every change. |
| Caching and cost (Chapter 12) | Approved common queries are cached. Every query carries a scan cost cap. |
| Provenance | Every answer shows its SQL and metrics used. Trust comes from being able to check. |
Left out on purpose: no agent loop (Chapter 8), since one question needs one query, and no long memory (Chapter 9), since saved questions live in the app.
Next: what Kestrel gave up, on purpose.
Tradeoffs taken
- The metrics layer slows new questions down. A new metric needs a governed definition first. In return, definition arguments end.
- Cost caps refuse some real work. A deep dive over a year of raw events may be legitimate and still get refused. Those route to an analyst with a bigger budget.
- Showing SQL scares some users. Kestrel kept it under a "show workings" toggle, because auditability beat tidiness.
- Caching risks stale answers. Approved queries cache for one hour (illustrative). Freshness loses a little; cost and speed gain a lot.
Next: the three failures that forced fixes.
What broke
- Refunds crept into revenue. One query bypassed the metrics layer and summed gross sales, so "revenue" quietly included refunded money. Fix: validation rejects money questions that skip the metrics layer, and a golden question covers refunds.
- One question, one large bill. A question scanned a raw events table end to end before cost caps existed. Fix: scan estimates, a hard cap, and raw events left the allowlist.
- A region leak after a schema change. The change dropped the row filter, and a regional manager briefly saw another region's rows. Fix: filters moved into the database role, plus a daily leak test per region.
Next: what a question costs, and how fast it feels.
Cost and latency
All figures here are illustrative. Volume: 3,000 questions a month.
- Per question: about $0.014 all in, from the worked example. Monthly model plus scan cost: 3,000 x $0.014 = $42 (illustrative).
- With caching: if 40 percent hit cached queries, paid questions fall to 1,800, and the bill to about $25 a month (illustrative).
- Scan cost, no cap: one 800 GB raw scan at an illustrative $5 per TB costs about $4, more than 280 normal questions.
- Scan cost, with cap: the 10 GB cap bounds one scan to about $0.05 (illustrative).
- Latency: about 6 seconds (illustrative): 1 retrieval, 2 model, 2 warehouse, 1 chart. Cached answers: under 1 second.
Next: break the guardrail, then redesign the product.
Hands-on lab: break-it, the guardrail that only looks safe
Why this exercise: text filters feel like security and fail like string matching.
The config Kestrel almost shipped (illustrative):
# guardrail config, illustrative, BROKEN
def check(sql):
if "DROP" in sql.upper():
return "blocked"
return "allowed" # then run it as a full-access role
allowlist = None # any table is fine
cost_cap_gb = None # no cap
metrics_layer = "optional"
Lab: Kestrel almost shipped the guardrail in the starter: a function that blocks a query when the word DROP appears in it, allows everything else, and runs it all as a full-access role, with no allowlist and no cost cap. This lab runs in your browser and needs JavaScript enabled.
Next: the redesign exercise.
Redesign exercise: store managers get access
New requirement: store managers, who are not analysts, get self-serve access, with stricter templates and plainer answers. Redesign first: what gets stricter, what gets simpler, what stays?
Model answer
Keep every database control unchanged: read-only role, row filters scoped to their store, cost caps, metrics layer. Get stricter at the edges: managers pick from approved templates with slots (store, week, product line); free text stays analyst-only. Get plainer at the surface: one sentence, one chart, SQL behind the workings toggle, jargon explained in one line. Add golden questions from real manager questions, and route off-template asks to an analyst. Widen the audience by narrowing the input, never by loosening the locks.
In production practice, text-to-SQL tools tend to earn trust in this order: show the SQL, cap the scan, then widen access. Treat that as a common pattern, not a measured statistic.
Mix-ups to avoid
- A prompt rule is a permission. No: permissions live in the database role. Prompts guide behaviour; roles enforce it.
- Valid SQL means a correct answer. No: valid SQL over the wrong table or definition is still wrong. Validate meaning, not just syntax.
- Blocking bad words is security. No: it blocks
drop_rateand misses a write hidden in a CTE. Parse the query and lock the role. - Row filters belong in the app. No: app-side filtering runs after data has moved. Filter inside the database.
- Cost caps are just about money. No: they are also a safety valve against loops and honest mistakes.
Chapter quiz
Five questions. Score 70% or more to mark this chapter complete.
Review this chapter in 5 minutes
Watch the whole chapter recapped: a warehouse copilot where safety lives in the database: metrics layer, read-only role, cost caps, and golden evals.
- Shape: question, retrieval, structured SQL, validation, read-only run, answer with chart, numbers and SQL.
- Locks live low: read-only role and row filters in the database, allowlist and cost cap in code, guidance in the prompt.
- Money words come from the metrics layer, defined once. The model never invents a definition.
- Cost: about $0.014 per question, about $42 a month at 3,000 questions, all illustrative. A 10 GB cap bounds one scan to about $0.05.
- Three breaks, three fixes: refunds in revenue (metrics layer required), huge scan (caps, allowlist), region leak (filters in the role).
- Widen access by narrowing input: templates for store managers, locks unchanged.
Decision rule: if a rule must hold even when the model misbehaves, enforce it below the model, in the database or in code.
Review
Glossary
- Data warehouse
- A database built for analysis over lots of history. Example: Kestrel's sales warehouse.
- Metrics layer
- One governed place where measures like revenue are defined once. Example: revenue net of refunds.
- Read-only role
- A database login that can read but never write. Example: the copilot's warehouse role.
- Row-level permissions
- Rules so a user sees only their rows. Example: a north manager sees north stores only.
- Table allowlist
- The short list of tables a query may touch. Example: governed sales views, not raw events.
- Cost cap
- A limit on scan size or spend per query. Example: refuse scans over 10 GB.
- Golden questions
- Test questions with hand-computed expected answers. Example: trainer sales for a known week.
- Provenance
- Showing where an answer came from. Example: the SQL printed under every answer.
- CTE
- A named sub-query inside one SQL statement, starting with WITH. Example: a hidden step inside a longer query.
Next: "Case study: a regulated-industry assistant with governance built in".