Deployed Lab

Module 5 · Case studies II · Chapter 21 · Free

Case study: a data analysis copilot over a warehouse

15 min1 clickable picture1 break-it lab1 predict, 2 quick quizzes, 5-question final quiz5-min video review
In 30 seconds

The picture: a junior analyst with a library card. Approved shelves only, workings always shown, and the library decides what stays locked.

Case file

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.

The cold open

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 lesson: a prompt is advice. A database role is a lock.

The plan for this chapter
  1. Start from requirements, then walk the architecture.
  2. See which patterns appear, and why each one earns its place.
  3. Read the tradeoffs, then what broke in production style failures.
  4. Do the cost and latency maths, all illustrative.
  5. 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.

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:

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.

Data analysis copilot architecture A question is grounded in the metrics layer and schema docs, turned into SQL, validated, run under a read-only role with row filters and a cost cap, then answered with chart, numbers and SQL. Questionplain English Metrics layerplus schema docs Write SQLstructured output Validateallowlist, cost Warehouseread-only role Answer + SQL
  1. A merchandiser asks why trainer sales dipped in the north last month. The app adds who is asking, so region rules can apply.
  2. 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.
  3. The model returns SQL in a fixed shape, plus the metrics it used. Money questions must call the metrics layer.
  4. Code parses the SQL, checks the table allowlist, estimates scan cost, and rejects anything over the cap or off the list.
  5. 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.
  6. 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:

  1. Retrieval returns 3 metric definitions and 2 table docs, about 900 tokens.
  2. The model drafts SQL on the governed sales view, by week, north only.
  3. The validator estimates a 0.4 GB scan. The cap is 10 GB, so it passes.
  4. 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

PatternWhere 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.
ProvenanceEvery 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

Next: the three failures that forced fixes.

What broke

Next: what a question costs, and how fast it feels.

Cost and latency

All figures here are illustrative. Volume: 3,000 questions a month.

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.

Field note, November 2026

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

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.

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".