▚ The AI Engineer's Field Manual
Module 01 · Act I — The Bridge

The Working Stack — Python, SQL & Statistics for AI

"Before you build the engine, master the workshop tools."

~6 hours Builds on: Module 00 Tools: uv · duckdb · pandas · Pydantic v2 · scipy · asyncio · httpx Job-spec line it unlocks: "Production-grade Python (async) · strong SQL"

01 · The hookThe CFO Wants Numbers, Not Stories

The three tools you will use every single day: Python for the work, SQL for getting the data, and enough statistics to know whether a difference you are looking at is real.

Field report · Client memo

"I need a revenue dashboard on my desk by EOD. I want MRR — the predictable subscription money we earn every month — broken down by customer cohort, meaning everyone who signed up in the same month.

I want month-over-month retention, and I want to know which product tier is bleeding the most revenue. And please: actual numbers, not your gut feeling.

While you're at it, someone tell the product team their 'huge checkout win' from last week needs to survive more scrutiny than a round of applause."

— Diana Chen, CFO, SaaSify

This memo is the whole module in three sentences.

Before any model gets trained and before any prompt gets written, someone has to do three things:

At Google, Amazon, JPMorgan and every AI team you would want to join, these three are the silverware. Used at breakfast, lunch and dinner — and tested in the first interview round, before anyone lets you near a GPU.

The stakes are not abstract. Later in this module you'll meet the A/B test that almost cost SaaSify $180K: a "3% conversion lift" the VP of Product was ready to ship company-wide, killed in one meeting by a single number — a p-value. The same arithmetic that saved that money is, quite literally, how you'll compare two prompts in Module 07. Different nouns, identical math.

DIANA'S MEMO, LINE BY LINE, AND THE TOOL THAT ANSWERS EACH LINE MRR by customer cohort month-over-month retention which tier is bleeding revenue 1 the 'huge checkout win' 55 of 420 → 66 of 410 = 13.1% → 16.1% 2 3 SQL, the forklift answers lines 1 to 3 in the warehouse toy: 5 rows · real: 10,000,000+ rows 4 Statistics, the lie detector line 4: p = 0.22, luck explains 1 in 5 $180K at risk if shipped on that 5 Python, the precision lathe: wraps every query and test in code a teammate can run (uv · Pydantic v2 · async)
Fig. 1.0b — The seed of this module, drawn. Three of Diana's lines are warehouse questions, one is a luck-or-real question, and all of it has to run as code by end of day. The numbers on the checkout line are the ones the whole statistics section will work on.
  1. Three warehouse questions. MRR by cohort, retention, and the bleeding tier are all 'summarize the rows' questions. None of them needs a row to leave the warehouse; they need SQL that groups, joins and ranks. Section 03 builds exactly those queries on a five-row copy of the table.
  2. The checkout claim. 55 conversions out of 420 visitors on the old page, 66 out of 410 on the new one. That is 13.1% against 16.1%, a three-point gap, and the VP wants to ship on it. Whether three points is real or luck is section 04's whole job.
  3. SQL, the forklift. It moves and stacks the rows inside the warehouse and hands back a few tidy rows. On the toy table the answers can be checked by hand; on the real table the same queries run unchanged.
  4. Statistics, the lie detector. The p-value for the checkout claim came out at 0.22: if the new page changed nothing, one test in five would still show a gap this size. The downside of shipping anyway was estimated at $180K. That one number stopped the rollout.
  5. Python, the lathe. Diana's dashboard runs every night, so the queries and the test have to be code that a teammate can install and run identically. That is uv for the environment, Pydantic for the rows entering the code, and async for the model calls, all in section 05.
You already know this

Nine years of shipping software gave you most of this module for free. You're not learning new ideas — you're re-badging old ones:

Your SWE reflexes, re-badged for AI work
You know coldThis module's version
ORM queries (ActiveRecord, Prisma, Hibernate)Raw SQL against a columnar warehouse — ORMs stop at the analytics door
Unit tests asserting the happy pathHypothesis tests asserting against the null — "prove this isn't luck"
package.json + lockfilepyproject.toml + uv.lock
TypeScript interfaces at API boundariesPydantic v2 models at data boundaries
Node's event loop and await fetch(...)asyncio's event loop and await client.post(...)

02 · The intuitionOne Stack, Three Tools

Diana's memo asks for three dashboard numbers by end of day and a verdict on the checkout claim, and every one of them starts as rows in SaaSify's warehouse: tens of millions of event rows, five of which we will keep on the table as our toy copy. Nobody can read tens of millions of rows, so the first thing the team needs is a picture of the path those rows travel to become three numbers on a dashboard. That path has three tools on it, and the rest of this module walks it in order.

Picture the path data travels before it ever reaches a model. It starts as tens of millions of raw rows in a warehouse.

SQL is the forklift: it moves, joins, filters, and stacks that data inside the warehouse, handing you back a few thousand tidy rows.

Those rows land in a pandas DataFrame — Python's workbench — where they become features, training sets, and eval sets.

And standing at every hand-off is statistics, the lie detector, asking one rude question: is that number real, or did you get lucky?

Data warehouse Postgres · Snowflake 10⁷ raw rows SQL query the forklift 10³ tidy rows DataFrame pandas features · eval sets Model / LLM app Acts II & III statistics — "is that number real?" — gates every hand-off 1 2 3 4
Fig. 1.1 — The working stack: SQL condenses warehouse-scale data into DataFrame-scale data, and statistics decides which numbers are allowed to drive decisions.
  1. Into the forklift. Ten million raw rows sit in the warehouse (10⁷ is ten million). The SQL query runs there, next to the rows, and none of them travel. This is the arrow the whole of section 03 is about.
  2. The hand-off. A few thousand tidy rows (10³ is a thousand) cross into pandas. In this module's code that crossing is one call, con.sql(...).df(). Everything that crosses has already been filtered, grouped and joined.
  3. The workbench. Inside pandas the rows become features for a model, prompts for a language model, and the eval sets that score both. Section 05 is about making this stage typed and fast.
  4. The gate. The dashed bar sits under every arrow because a number can be wrong at any hand-off: a biased join, a lucky A/B split, a 20-example eval. Statistics asks "is that number real?" before anything is built on it. Section 04 builds the asker.

Now the same picture a second time, with this module's actual files in the boxes. If a stage in Fig. 1.1 feels abstract, find its row here: every stage is a script on this page, and the middle column names the line that does the work.

Fig. 1.1 again, concretely: each stage as it exists in this module's code
StageIn this module's scriptsAt SaaSify's real scaleWhat flows out
Data warehousewarehouse_sim.py seeds five rows into saasify.duckdbSnowflake or BigQuery holding tens of millions of event rows, loaded nightlyTables you query, and never pull whole
SQL query, the forkliftlevel_1_filter.sql through level_5_cohorts.sql, run through con.sql(...)The same SQL saved as a warehouse view or a scheduled job, with a month-offset join for the retention triangleA few thousand tidy rows: one per customer, cohort or rank
The hand-offcon.sql(...).df(), the comment on the last line of warehouse_sim.pypd.read_sql(...) against the warehouse, or Parquet files the warehouse exports and DuckDB reads directlyA pandas DataFrame that fits in memory
DataFrame, the workbenchSubscription.model_validate(raw) in subscription_contract.py checks each rowThe same Pydantic model at every service boundary, then feature engineering in pandasTyped rows ready to become features, prompts and eval sets
Statistics, the lie detectorrun_ab_test(420, 55, 410, 66) in ab_test_engine.py; eval_variance.py; latency_percentiles.pyThe same z-test on prompt v1 against v2 in Module 07, sized with required_sample_size() before the test startsA verdict with a confidence interval, not a bare percentage
Model / LLM appconcurrent_summaries.py sends three tickets to a local model at onceActs II and III: features into scikit-learn, context into an LLM, fan-out capped by a semaphorePredictions, summaries and eval scores
🧠 Brain power

Before reading on: your product database has 40 million event rows. Diana wants average revenue per contract type — three numbers. Your app-engineer instinct says SELECT *, stream the rows into your service, and aggregate in a loop. What actually happens if you do that, and where does the time go?

Reveal the answer

Almost all the time goes into moving data that never needed to move: serializing 40M rows in the database, shipping them across the network, deserializing them into Python objects (each tuple costing ~10× the raw bytes in memory), then looping in an interpreter that executes bytecode per row. The warehouse could have answered from its columnar storage — reading only the two relevant columns, in parallel, close to the data — and shipped back three rows, which is marker 1 and marker 2 of Fig. 1.1 done properly. The rule that falls out: push compute to the data, not data to the compute. You'll feel this with a stopwatch in the next section.

The whole intuition fits in four lines. Say them until they are reflex; each one is a hand-off in Fig. 1.1.

Push the compute to the data.

Bring back the small result.

Shape it on the workbench.

Before you act on a number, ask if it is real.

Push the compute to the data: marker 1 in Fig. 1.1, the query runs inside the warehouse next to the ten million rows. Bring back the small result: marker 2, a few thousand rows cross into pandas through .df(). Shape it on the workbench: marker 3, those rows become features, prompts and eval sets. Real: marker 4, the dashed gate where statistics asks whether a number is luck before anything is built on it.

The stack, and why

Before the lab, here is every tool this module leans on, and what you would pick instead. Each row is a choice you will be asked to defend in an interview.

The stack, and why

The one question that decides it: how big is the data, and who else touches it? As of October 2026.

What this module uses, what else you could use, and when to switch (October 2026)
LayerWe useAlternativesWhy this oneSwitch when
SQL engineDuckDB (the 1.x line)SQLite, PostgreSQL, ClickHouse, SparkRuns inside your Python process, so there is nothing to install or connect to, and it scans columns fast. Weakness: it is built for one analyst at a time, not many people writing at once.Many people must write at the same time, or the data passes a few hundred GB on one machine: PostgreSQL or a cloud warehouse.
Workbench tablepandas, reached through .df()Polars, plain Python listsEvery tutorial, library and interviewer knows it. Weakness: it holds everything in memory and is slow on big tables.The result you pull back is more than a few million rows: keep it in DuckDB or switch to Polars.
Statisticsnumpy and scipy, written by hand in ab_test_engine.pystatsmodels, pingouin, a hosted experiment toolWriting the z-test yourself shows where every number comes from. Weakness: you must keep the formula correct yourself.You need regression, repeated measures or a test beyond comparing two rates: use statsmodels instead of rolling your own.
Python and packagesPython 3.12 with uvpip + venv, Poetry, condaOne tool installs Python, pins versions and builds the environment in seconds. Weakness: younger than pip, so some team docs still say pip.Your team already standardises on conda for GPU or scientific stacks.
Data checkingPydantic v2dataclasses, attrs, marshmallow, hand-written if checksIt rejects bad data at the edge, with an error that names the field. Weakness: a small cost on every check.Millions of objects per second in a hot loop: use plain dataclasses and validate at the boundary only.
Concurrency and HTTPasyncio with httpxthreads, requests, aiohttpWaiting on a slow model call costs nothing while other calls run. Weakness: one blocking call freezes everything.The work is CPU-heavy number crunching rather than waiting: use processes, not asyncio.

Start with the tool that needs no server and has the most tutorials, and leave it only when you can name the size or the team situation that forces you out.

03 · The data forkliftSQL — Move the Data Without Carrying It Yourself

The path in Fig. 1.1 starts in the warehouse, and Diana's first three lines (MRR by cohort, retention, the bleeding tier) are all questions the warehouse can answer without a single row leaving it. The team needs the SQL that asks those questions: filtering, grouping, joining, ranking, and then a readable pipeline for the cohort table. We will build it on a five-row copy of SaaSify's subscriptions table, so every answer can be checked by hand, and then race it against the app-layer habit on ten million rows.

The database your app talks to and the database analytics runs on are different beasts. Your Postgres serves transactions — thousands of tiny reads and writes per second, one row at a time. A warehouse serves analysis — a handful of huge queries that each scan millions of rows. To practice warehouse-grade SQL without provisioning Snowflake, we'll use DuckDB: an in-process analytical database ("SQLite for OLAP") that speaks the same dialect family — window functions, CTEs, DATE_TRUNC — so everything you write here transfers verbatim.

"Why DuckDB? I already have Postgres, and Postgres has window functions and CTEs too. This looks like a new toy for the sake of it."

— a backend engineer with eleven years of Postgres, right about now

Postgres will run every query in this section, and if your data already lives there, write the first version there. The difference is not the language. It is the storage. Postgres keeps each row together on disk. That is ideal for reading one customer's record and slow for averaging one column across ten million rows, because it has to read the other columns too.

DuckDB stores each column separately and processes values in batches, so the ten-million-row race below reads two columns and skips the rest. Fig. 1.1b, just below, draws the difference on the five toy rows: to average one column, the row store at marker 1 has to read all 30 cells, the column store at marker 2 reads 5 and skips 25. It also needs no server: one pip install, one file, and it reads CSV and Parquet files directly. That makes it an honest stand-in for Snowflake or BigQuery on a laptop, which is the only reason it is here.

The downside is real. DuckDB is one process on one machine, with no user accounts, no concurrent writers and no replication. It is the wrong choice for the store behind a running application. Keep Postgres for serving requests. Run analytics on something columnar, and not on the production database, whose job is answering users.

1 ROW STORE (POSTGRES): EACH ROW KEPT TOGETHER id signup charge contract churn tier C101 Jan 15 120.00 M2M 1 Pro C102 Jan 20 85.50 1-Yr 0 Basic C103 Feb 1 145.00 M2M 0 Pro C104 Feb 10 45.00 2-Yr 0 Basic C105 Mar 5 110.00 M2M 1 Pro to average one column: read every cell, 30 of 30 (shaded = bytes read off disk) 2 COLUMN STORE (DUCKDB): EACH COLUMN KEPT SEPARATELY id C101 C102 C103 C104 C105 signup Jan 15 Jan 20 Feb 1 Feb 10 Mar 5 charge 120.00 85.50 145.00 45.00 110.00 contract M2M 1-Yr M2M 2-Yr M2M churn 1 0 0 0 1 tier Pro Basic Pro Basic Pro to average one column: read 5 cells, skip 25 (unshaded = never touched) 3 AVG(monthly_charges) = (120.00 + 85.50 + 145.00 + 45.00 + 110.00) ÷ 5 = 101.10, the same answer either way the difference is how much must be read to get there; at ten million rows, seconds against milliseconds
Fig. 1.1b — Why the analytics database is a different animal. Same five rows, same question (average charge), same answer 101.10; the row store reads 30 cells to get it, the column store reads 5. Multiply by two million and you have the ten-million-row race below.
  1. The row store. Postgres keeps each customer's six values side by side on disk, which is perfect for 'show me C103' and wasteful for 'average the charge column': to reach the five charges it reads the other 25 cells too. Every cell is shaded because every cell is read.
  2. The column store. DuckDB, Snowflake and BigQuery keep each column as its own block. The average touches only the shaded charge block; the five unshaded columns are never read. That is where the tens of milliseconds in the race come from.
  3. Same answer. Both engines return 101.10. Storage changes the cost of a question, never the answer, which is why you can write the query in Postgres first and move it to a warehouse later without changing a word.

First, seed a miniature SaaSify warehouse. Every query in this section runs against it.

You have not been taught DuckDB or the VALUES syntax yet. That is on purpose. Guess first, then check. Every line in this table is explained in the step-by-step list under it, and the SQL itself is taught level by level over the rest of this section.

Sharpen your pencil

Below are eleven lines lifted from warehouse_sim.py, the file you are about to read. Three are annotated for you. In the blank rows, write what you think each line does, in plain English, before you open the answers. Wrong guesses are welcome; they are the point of the exercise.

import duckdbbring in the DuckDB library, a database engine that runs inside this Python process
con = duckdb.connect("saasify.duckdb")
con.execute("""
CREATE OR REPLACE TABLE subscriptions ASmake a table called subscriptions from whatever the next SELECT produces; if it already exists, throw it away and rebuild it
SELECT * FROM (VALUES
('C101', DATE '2025-01-15', 120.00, 'Month-to-Month', 1, 'Pro'),
) AS t(customer_id, signup_date, monthly_charges, contract_type, churn, signup_tier)
CREATE OR REPLACE TABLE support_tickets AS
('C101', DATE '2025-03-02'),
print(con.sql("SELECT * FROM subscriptions"))ask for every row of subscriptions and print the result: proof that the seeding worked
# con.sql(...).df() hands the result to pandas -- that's the
Check your answers
import duckdbbring in the DuckDB library, a database engine that runs inside this Python process
con = duckdb.connect("saasify.duckdb")open a database stored in one file on disk, creating the file if it is missing, and keep the connection in con. Every later command goes through it
con.execute("""send the SQL text between the triple quotes to the database and run it. execute is for statements that change the database; sql is for ones that return rows
CREATE OR REPLACE TABLE subscriptions ASmake a table called subscriptions from whatever the next SELECT produces; if it already exists, throw it away and rebuild it
SELECT * FROM (VALUESVALUES lets you type rows in by hand as a literal table. The SELECT * turns those typed rows into a query result, which is what CREATE TABLE ... AS captures
('C101', DATE '2025-01-15', 120.00, 'Month-to-Month', 1, 'Pro'),one customer row: id, signup date (DATE '...' makes it a real date rather than text), monthly charge, contract type, churn flag (1 means the customer left), and tier
) AS t(customer_id, signup_date, monthly_charges, contract_type, churn, signup_tier)give the typed-in table a temporary name, t, and name its six columns in order. These become the column names of subscriptions
CREATE OR REPLACE TABLE support_tickets ASa second table, same recipe: a ticket id, the customer who raised it, and the issue type
('C101', DATE '2025-03-02'),one activity row: customer C101 was active on 2 March 2025. The user_activity table is just a customer id and a date
print(con.sql("SELECT * FROM subscriptions"))ask for every row of subscriptions and print the result: proof that the seeding worked
# con.sql(...).df() hands the result to pandas -- that's thea comment pointing at the hand-off. Adding .df() to any query result turns it into a pandas DataFrame, which is the warehouse-to-workbench arrow in Fig. 1.1

Do not worry if you got half of these. If you guessed that connect opens a file and that VALUES types rows in by hand, you already understand the script. The rest of this section teaches the SQL that runs against these tables, one level at a time.

Step-by-step: what warehouse_sim.py does, in plain English
  1. Bring in the DuckDB library — a small database engine that runs inside your Python program, so there is no server to install and nothing to log into.
  2. Open a database stored in a single file called saasify.duckdb (DuckDB creates the file if it does not exist yet). The con variable is your phone line to that database — every later command goes through it.
  3. Create a table named subscriptions and fill it with five hand-written customer rows: an id, a signup date, a monthly charge, a contract type, a churn flag (1 = the customer left), and a tier. The words CREATE OR REPLACE mean "if this table already exists, throw it away and build it fresh" — so you can re-run the script as many times as you like without errors.
  4. In exactly the same way, create a support_tickets table with three ticket rows (which customer raised it, and what kind of issue it was).
  5. Again the same way, create a user_activity table with five rows recording a date on which each customer was active.
  6. Finally, ask the database for every row of subscriptions ("SELECT * FROM" means "give me everything from") and print the result — proof that the seeding worked, and the table you see printed below.
warehouse_sim.pyruns offline
# pip install "duckdb>=1.3,<2"
"""Mini SaaSify warehouse. Every query in this chapter runs against it.

DuckDB is in-process: no server, no credentials, one file on disk.
Its SQL dialect matches the Snowflake/BigQuery family, so what you
practice here is what you'll write at work.
"""
import duckdb

con = duckdb.connect("saasify.duckdb")

con.execute("""
CREATE OR REPLACE TABLE subscriptions AS
SELECT * FROM (VALUES
    ('C101', DATE '2025-01-15', 120.00, 'Month-to-Month', 1, 'Pro'),
    ('C102', DATE '2025-01-20',  85.50, 'One-Year',       0, 'Basic'),
    ('C103', DATE '2025-02-01', 145.00, 'Month-to-Month', 0, 'Pro'),
    ('C104', DATE '2025-02-10',  45.00, 'Two-Year',       0, 'Basic'),
    ('C105', DATE '2025-03-05', 110.00, 'Month-to-Month', 1, 'Pro')
) AS t(customer_id, signup_date, monthly_charges, contract_type, churn, signup_tier)
""")

con.execute("""
CREATE OR REPLACE TABLE support_tickets AS
SELECT * FROM (VALUES
    ('T-01', 'C101', 'Billing Dispute'),
    ('T-02', 'C101', 'Outage Report'),
    ('T-03', 'C103', 'Feature Request')
) AS t(ticket_id, customer_id, issue_type)
""")

con.execute("""
CREATE OR REPLACE TABLE user_activity AS
SELECT * FROM (VALUES
    ('C101', DATE '2025-03-02'),
    ('C102', DATE '2025-06-11'),
    ('C103', DATE '2025-06-28'),
    ('C104', DATE '2025-06-30'),
    ('C105', DATE '2025-02-20')
) AS t(customer_id, activity_date)
""")

print(con.sql("SELECT * FROM subscriptions"))
# con.sql(...).df() hands the result to pandas -- that's the
# warehouse -> DataFrame hand-off from Fig. 1.1, in one method call.
What the script prints — the seeded subscriptions table (support_tickets and user_activity are seeded the same way). Keep these 5 rows in view: every query below runs against them, so you can verify each result by hand.
customer_idsignup_datemonthly_chargescontract_typechurnsignup_tier
C1012025-01-15120.00Month-to-Month1Pro
C1022025-01-2085.50One-Year0Basic
C1032025-02-01145.00Month-to-Month0Pro
C1042025-02-1045.00Two-Year0Basic
C1052025-03-05110.00Month-to-Month1Pro

Level 1 — filtering — is muscle memory after nine years, so one look and we move on: which Month-to-Month customers pay more than $100?

Step-by-step: what level_1_filter.sql does, in plain English
  1. FROM subscriptions — start with the five-row table we just seeded.
  2. WHERE — keep only the rows that pass both tests: the contract type is exactly 'Month-to-Month' and the monthly charge is more than $100. Rows failing either test are discarded.
  3. SELECT — from each surviving row, keep just three columns: the customer id, the charge, and the contract type.
  4. ORDER BY monthly_charges DESC — sort what is left from the highest charge to the lowest (DESC is short for "descending").
  5. Result: three rows come back — C103 ($145), C101 ($120), C105 ($110) — exactly the table below.
level_1_filter.sql
-- Run inside warehouse_sim.py:  print(con.sql(open('level_1_filter.sql').read()))
SELECT customer_id, monthly_charges, contract_type
FROM   subscriptions
WHERE  contract_type = 'Month-to-Month'
  AND  monthly_charges > 100.00
ORDER BY monthly_charges DESC;
-- returns C103 (145.00), C101 (120.00), C105 (110.00)
Output of level_1_filter.sql — only the three Month-to-Month customers above $100, highest first
customer_idmonthly_chargescontract_type
C103145.00Month-to-Month
C101120.00Month-to-Month
C105110.00Month-to-Month
5 ROWS IN C101 · Month-to-Month · 120.00 C102 · One-Year · 85.50 C103 · Month-to-Month · 145.00 C104 · Two-Year · 45.00 C105 · Month-to-Month · 110.00 1 WHERE keep or drop 3 ROWS SURVIVE C101 · Month-to-Month · 120.00 C103 · Month-to-Month · 145.00 C105 · Month-to-Month · 110.00 2 C102 fails: One-Year C104 fails: Two-Year, 45 < 100 3 ORDER BY charge DESC 3 ROWS OUT, HIGHEST FIRST C103 · 145.00 C101 · 120.00 C105 · 110.00 the WHERE test: contract_type = 'Month-to-Month' AND monthly_charges > 100, applied to one row at a time
Fig. 1.1c — Level 1 drawn on the five rows: WHERE looks at one row at a time and keeps or drops it; ORDER BY only changes the order of what survived. Nothing here is summarized, which is what level 2 adds.
  1. WHERE is a per-row test. Each of the five rows is checked alone against both conditions. A row that fails either one is gone before anything else happens. Three rows pass.
  2. The two that fail. C102 is One-Year, so the first condition fails. C104 is Two-Year and also pays 45, so it fails both. They are not counted, averaged or ranked later; from the engine's point of view they no longer exist.
  3. ORDER BY sorts the survivors. DESC means largest first, so C103 at 145.00 leads. The order of the output is the only thing this clause changes. The same three rows would come out in a different order without it.

The instinct race: app-layer loop vs. the warehouse

Before the levels, one thing has to be settled with a stopwatch, because it is the habit most likely to sink Diana's dashboard: pulling the rows into Python and averaging them there. The brain-power question above asked what happens with 40 million rows. Here we do it with ten million, both ways, and time it. The result decides where every later query in this section runs.

Before the fancy stuff, let's settle the Brain Power question with a stopwatch. Same aggregate, two ways, ten million rows: once by dragging every row into Python (the ORM-brain approach), once by asking the database to do its job.

Step-by-step: what watch_it_break.py does, in plain English
  1. Connect to a fresh, empty DuckDB held only in memory (no filename given, so nothing is saved to disk).
  2. Build a table called big with ten million invented rows. range(10_000_000) produces the numbers 0 through 9,999,999; each number i is turned into a customer id, one of three contract types (i % 3 is the remainder after dividing by 3, so it cycles 0, 1, 2), and a monthly charge.
  3. Way 1 (the slow way): start a stopwatch with time.perf_counter(), then call fetchall() — which drags all ten million rows out of the database and into Python's memory as a giant list.
  4. Walk that list one row at a time in a Python loop, adding each charge into a running total and a running count per contract type — an average computed by hand.
  5. Stop the stopwatch; the elapsed time is saved as py_secs.
  6. Way 2 (the right way): restart the stopwatch and instead ask the database itself to do the work: "average the charges, grouped by contract type". The ten million rows never leave the database engine.
  7. Print both times side by side. The Python loop takes roughly twenty seconds; the database answers in tens of milliseconds — the point of the whole race.
watch_it_break.pyruns offline
# pip install "duckdb>=1.3,<2"
"""Same three averages, two ways, 10 million rows. Race them."""
import time

import duckdb

con = duckdb.connect()
con.execute("""
CREATE TABLE big AS
SELECT 'C' || (i % 500000)  AS customer_id,
       (i % 3)::VARCHAR     AS contract_type,
       (40 + (i % 120) * 1.0)::DOUBLE AS monthly_charges   -- DOUBLE, not DECIMAL: the loop below adds floats
FROM range(10_000_000) t(i)
""")

# Way 1: ship 10M rows to Python, aggregate in a loop
t0 = time.perf_counter()
rows = con.execute("SELECT contract_type, monthly_charges FROM big").fetchall()
sums: dict[str, float] = {}
counts: dict[str, int] = {}
for contract, charge in rows:
    sums[contract] = sums.get(contract, 0.0) + charge
    counts[contract] = counts.get(contract, 0) + 1
py_secs = time.perf_counter() - t0

# Way 2: push the compute to the data
t0 = time.perf_counter()
con.execute("SELECT contract_type, AVG(monthly_charges) FROM big GROUP BY 1").fetchall()
sql_secs = time.perf_counter() - t0

print(f"app-layer loop : {py_secs:6.1f} s")
print(f"SQL GROUP BY   : {sql_secs * 1000:6.0f} ms")
Failure mode

On the machine that ran this, the loop took 6.0 seconds against 26 milliseconds for the GROUP BY. On a typical laptop the loop takes tens of seconds and multiple GB of RAM (10M Python tuples are shockingly expensive objects); the GROUP BY answers in tens of milliseconds from columnar storage. Your numbers will vary — the two-to-three-orders-of-magnitude ratio won't. Now scale the picture: against a real warehouse, way 1 also saturates the network, blows the service's memory limit, and gets your query killed by the DBA. This is why "strong SQL" appears in the job spec of every AI team: the forklift moves pallets so you don't carry boxes.

WAY 1: SHIP TEN MILLION ROWS TO PYTHON, THEN LOOP SELECT the 2 columns then fetchall() serialize 10,000,000 rows ship them out of the engine unpack into 10,000,000 tuples several GB of RAM Python for-loop, one row at a time, 10,000,000 times 1 the memory cost 2 the time cost wall clock ≈ 20 s (the whole width) WAY 2: ASK THE WAREHOUSE FOR THE THREE AVERAGES SELECT contract_type, AVG(monthly_charges) FROM big GROUP BY 1 — runs next to the rows 3 rows come back 3 averages 3 reads 2 of the table's 3 columns, in batches wall clock: tens of ms. To scale against the 20-second bar it is this sliver, about one pixel wide
Fig. 1.1d — The race, drawn. Both ways compute the same three averages over the same ten million rows. Way 1 pays for moving every row and for touching each one in Python; way 2 never moves them. The ratio is two to three orders of magnitude, and it does not shrink with better hardware.
  1. The memory cost. Ten million Python tuples are not ten million small numbers; each is an object with headers and pointers, roughly ten times the raw bytes. Several gigabytes of RAM for three averages, and against a real warehouse this is also the step that saturates the network.
  2. The time cost. The interpreter executes bytecode for every row, ten million times. Twenty seconds on a laptop, and the number grows in a straight line with the row count. pandas would do this loop faster, but the shipping cost in the box before it stays.
  3. The warehouse's way. GROUP BY runs where the rows already are, reads only the two columns it needs (Fig. 1.1b, marker 2), and sends back three rows. Tens of milliseconds. This is the rule 'push the compute to the data' with a stopwatch on it, and every query from here on obeys it.

Level 2 — GROUP BY & HAVING: summarize without leaving SQL

Diana's third line, "which tier is bleeding the most revenue", is a per-group question: for each contract type, how many customers, what do they pay, and how many have left. Level 1 could only keep or drop single rows. The team now needs a way to fold the five rows into one summary row per contract type, and to filter those summary rows after they are built. That is GROUP BY and HAVING, and the race just showed why it has to happen in the warehouse.

Step-by-step: what level_2_grouping.sql does, in plain English
  1. FROM subscriptions — start with all five rows.
  2. GROUP BY contract_type — fold the rows into one bucket per contract type. Five rows become three buckets: Month-to-Month (3 rows), One-Year (1 row), Two-Year (1 row).
  3. For each bucket, compute three summaries: COUNT(*) counts how many rows landed in the bucket; AVG(...) averages their charges (rounded to 2 decimal places); and the SUM(CASE WHEN churn = 1 THEN 1 ELSE 0 END) line counts churners — the CASE turns each churned row into a 1 and each loyal row into a 0, so summing them is the same as counting the 1s.
  4. HAVING COUNT(*) >= 1 — after the buckets are built, throw away any bucket that fails this test. (Here every bucket passes; the clause is included to show you where HAVING sits, marker 4 of Fig. 1.1e below: it filters whole buckets, never individual rows.)
  5. ORDER BY churned_count DESC — sort the buckets so the one losing the most customers appears first.
level_2_grouping.sql
-- "Average charge, customer count, and churn count per contract type."
SELECT   contract_type,
         COUNT(*)                       AS total_customers,
         ROUND(AVG(monthly_charges), 2) AS avg_monthly_charge,
         SUM(CASE WHEN churn = 1 THEN 1 ELSE 0 END) AS churned_count
FROM     subscriptions
GROUP BY contract_type
HAVING   COUNT(*) >= 1        -- filters whole GROUPS, after aggregation
ORDER BY churned_count DESC;
Output of level_2_grouping.sql
contract_typetotal_customersavg_monthly_chargechurned_count
Month-to-Month3125.002
One-Year185.500
Two-Year145.000
1 5 ROWS IN C101 · M2M · 120 · churn 1 C102 · 1-Yr · 85.5 · churn 0 C103 · M2M · 145 · churn 0 C104 · 2-Yr · 45 · churn 0 C105 · M2M · 110 · churn 1 GROUP BY contract_type 2 3 BUCKETS, ONE SUMMARY EACH Month-to-Month: C101 120 (churn) C103 145 · C105 110 (churn) count 3 · avg 125.00 · churned 2 One-Year: C102 85.50 count 1 · avg 85.50 · churned 0 Two-Year: C104 45.00 count 1 · avg 45.00 · churned 0 HAVING COUNT(*) ≥ 1 all 3 pass then ORDER BY churned DESC 3 3 ROWS OUT M2M · 3 · 125.00 · 2 1-Yr · 1 · 85.50 · 0 2-Yr · 1 · 45.00 · 0 THE ORDER THE ENGINE WORKS IN WHERE drops single rows GROUP BY builds the buckets HAVING drops whole buckets ORDER BY sorts what is left 4
Fig. 1.1e — Level 2 drawn on the five rows. Rows fold into buckets, each bucket becomes one summary row, and HAVING is a test on buckets, not rows. The strip underneath is the order-of-operations question every SQL interview asks.
  1. Rows in. The five rows still carry their churn flags, because the summary needs them. GROUP BY does not look at values; it only sorts rows into piles by contract type.
  2. Buckets. Three piles. Inside the Month-to-Month pile the average is (120 + 145 + 110) ÷ 3 = 125.00 and two of the three rows have churn = 1, so churned_count is 2. After this step the individual customers are gone; only the pile summaries remain.
  3. Rows out. ORDER BY churned_count DESC puts Month-to-Month first, which is Diana's answer: that tier is losing customers. HAVING COUNT(*) ≥ 1 let every bucket through here; with ≥ 2 it would have kept only this one row.
  4. The order. WHERE runs before the buckets exist, HAVING after. WHERE COUNT(*) > 5 is an error because there is no count yet when WHERE runs. Rows, then buckets: that is the whole distinction.

The WHERE-vs-HAVING distinction is a two-second interview filter, so nail the order of operations, the strip at marker 4 of Fig. 1.1e: WHERE discards individual rows before grouping; GROUP BY collapses what survives into buckets; HAVING discards entire buckets after aggregation. Rows, then buckets. If you catch yourself writing WHERE COUNT(*) > 5, you've put the bouncer inside the party.

BE the query engine

Your turn to play the database. Below is a six-row table called trials that you have not seen before: free-trial signups, the plan each one tried, how many seats they used, and whether they converted to a paid plan (1) or not (0). Under it is a query. With a pencil, write out the rows the engine returns, in order, before opening the answer.

The trials table, six rows
customer_idplanseatsconverted
C201Pro121
C202Basic30
C203Pro401
C204Team81
C205Basic10
C206Pro50

The query, one clause per line. Remember the order the engine applies them in: rows first, then buckets, then bucket filters.

  1. SELECT plan, COUNT(*) AS trials, SUM(converted) AS won, ROUND(AVG(seats), 1) AS avg_seats
  2. FROM trials
  3. WHERE seats >= 3
  4. GROUP BY plan
  5. HAVING COUNT(*) >= 2
  6. ORDER BY won DESC;

How many rows come out, and what is in each? Then a second question: delete the WHERE line and run the query again in your head. What changes?

Check your answer

One row comes out.

What the engine returns, with the WHERE line in place
plantrialswonavg_seats
Pro3219.0

Walk it the way the engine does. WHERE runs first and looks at single rows: C205 used one seat, so it is discarded before any grouping happens. Five rows remain. GROUP BY folds them into three buckets: Pro holds C201, C203 and C206; Basic holds only C202; Team holds only C204.

HAVING then looks at whole buckets and keeps only those holding two or more rows. Basic and Team are dropped. Pro is left with 3 trials, 2 wins, and an average of (12 + 40 + 5) / 3 = 19.0 seats. The ORDER BY has one row to sort.

Without the WHERE line, C205 survives into the Basic bucket, which now holds two rows and passes HAVING. Two rows come out: Pro (3, 2, 19.0) and then Basic (2, 0, 2.0), because ORDER BY won DESC puts the two wins first.

The lesson the gap teaches: WHERE and HAVING are not two spellings of the same filter. WHERE decides which rows exist before the buckets are built, so it changes which buckets pass HAVING. If Basic appeared in your first answer, you applied HAVING to the original table. The engine never sees that table once WHERE has run.

Level 3 — JOINs: combine tables without losing customers

The churn column tells Diana who left; it does not say why. SaaSify keeps support tickets in a second table, three tickets from two customers, and the obvious next question is whether the customers who churned were the ones filing tickets. Answering it means gluing the two tables together by customer id, and the way you glue them decides whether the three customers with zero tickets stay in the picture. That choice is the whole of level 3, and it decides what a churn model later gets to see.

Step-by-step: what level_3_join.sql does, in plain English
  1. The query inside the parentheses runs first, like brackets in arithmetic: count the tickets per customer in support_tickets. It produces a little two-column table — C101 has 2 tickets, C103 has 1 — and gives it the nickname t.
  2. LEFT JOIN ... ON s.customer_id = t.customer_id — glue that little table onto subscriptions (nicknamed s) by matching customer ids. The word LEFT is the important choice: it means "keep every row from the left table (subscriptions) even if it finds no match on the right". Customers with no tickets survive, carrying an empty value (NULL) where a count would be.
  3. COALESCE(t.ticket_count, 0) — COALESCE means "use the first of these that is not empty", so it turns each NULL into an honest 0.
  4. SELECT — keep the id, charge, contract type, and the (now clean) ticket count.
  5. ORDER BY support_tickets DESC LIMIT 3 — sort by ticket count, most first, and keep only the top three rows.
level_3_join.sql
-- "Each customer's details alongside their support-ticket count."
SELECT   s.customer_id,
         s.monthly_charges,
         s.contract_type,
         COALESCE(t.ticket_count, 0) AS support_tickets
FROM     subscriptions s
LEFT JOIN (
    SELECT customer_id, COUNT(*) AS ticket_count
    FROM   support_tickets
    GROUP BY customer_id
) t ON s.customer_id = t.customer_id
ORDER BY support_tickets DESC
LIMIT 3;
Output of level_3_join.sql — note the customer with zero tickets survives
customer_idmonthly_chargescontract_typesupport_tickets
C101120.00Month-to-Month2
C103145.00Month-to-Month1
C10285.50One-Year0
subscriptions s C101 · 120.00 C102 · 85.50 C103 · 145.00 C104 · 45.00 C105 · 110.00 1 t: tickets per customer C101 → 2 tickets C103 → 1 ticket (no row for C102, C104, C105) LEFT JOIN t … ON customer_id every s row, matched where possible C101 · 120.00 · 2 C102 · 85.50 · NULL → 0 C103 · 145.00 · 1 C104 · 45.00 · NULL → 0 C105 · 110.00 · NULL → 0 ORDER BY DESC, LIMIT 3 C101 · 2 C103 · 1 C102 · 0 3 3 rows out 2 COALESCE(t.ticket_count, 0) turns each NULL into an honest 0 4 INNER JOIN instead: only C101 and C103 have a match, so C102, C104 and C105 vanish from the result. No error, no warning, three customers gone.
Fig. 1.1f — Level 3 drawn. The little table t has rows for only two customers, so a join has to decide what happens to the other three. LEFT keeps them with a NULL; COALESCE makes the NULL a zero; INNER would have silently deleted them.
  1. The little table. The subquery runs first and counts tickets per customer: C101 has 2, C103 has 1. There is no row at all for the other three customers, which is the normal shape of any activity table.
  2. LEFT keeps everyone. Every subscriptions row comes through, and where t has no match the ticket count is NULL. COALESCE(t.ticket_count, 0) says 'use the first value that is not empty', so the NULL becomes an honest 0.
  3. Top three. Sorting by ticket count descending and keeping three rows gives C101, C103 and then C102 with 0, which is the point: a customer with zero tickets is a real, visible row.
  4. The silent drop. An INNER JOIN keeps only rows that match on both sides. C102, C104 and C105 would disappear without an error, and a churn model trained on the result would never see a customer who never complained. Wrong join types do not fail; they bias.

The load-bearing choice is LEFT JOIN: an INNER JOIN would silently drop every customer who never filed a ticket, marker 4 of Fig. 1.1f, and "customers with zero tickets" is often exactly the population your churn model needs to see. In ML data prep, a wrong join type doesn't error; it quietly biases your training set. The COALESCE at marker 2 turns the resulting NULLs into honest zeros.

Level 4 — Window functions: annotate rows instead of collapsing them

Diana also wants to know which customers matter most inside each tier, and GROUP BY cannot say: at marker 2 of Fig. 1.1e it folded the three Month-to-Month rows into one summary and threw the customers away. The team needs the rank of every customer within its contract type while keeping every row intact. That is what a window function does, and it is the pattern behind most dashboard questions of the form "top N per group".

Here's the mental picture that makes window functions click. GROUP BY is a trash compactor: 5 rows in, 3 summary rows out, detail destroyed. A window function is a sticky-note dispenser: all 5 rows come back untouched, each carrying a new column computed over its "window" of peers.

GROUP BY window function C101 C102 C103 C104 C105 5 rows in collapse M2M · avg 125 1-Yr · avg 85.5 2-Yr · avg 45 3 rows out — detail gone C101 C102 C103 C104 C105 5 rows in annotate C101 C102 C103 C104 C105 2 1 1 1 3 5 rows + new column 1 2 3
Fig. 1.2 — GROUP BY collapses rows into summaries; a window function keeps every row and appends the aggregate as a new column.
  1. Collapse. The same five rows as level 2 go in and three summary rows come out: Month-to-Month averages 125, One-Year 85.5, Two-Year 45. The customer ids are gone. You cannot ask "which customer" of the output.
  2. Annotate. The window function looks at the same groups but writes its answer onto each row instead of replacing the rows. Five in, five out, and every customer id is still there.
  3. The new column. The values are the charge_rank from the query output below: C101 is 2nd among Month-to-Month customers, C102 is 1st (and only) One-Year, C103 is 1st Month-to-Month, C104 is 1st Two-Year, C105 is 3rd Month-to-Month. Each rank was computed only among that row's own contract type.
Step-by-step: what level_4_window.sql does, in plain English
  1. There is no GROUP BY here, so nothing collapses: all five rows of subscriptions go in, and all five come back out.
  2. For each row, RANK() OVER (PARTITION BY contract_type ORDER BY monthly_charges DESC) works like this: look only at the row's peers — the other rows with the same contract type (that's what PARTITION BY means) — sort that small peer group by charge, highest first, and write down this row's position in it. That position becomes the new charge_rank column.
  3. AVG(monthly_charges) OVER (PARTITION BY contract_type) — likewise, compute the average charge of the row's peer group and stamp it onto the row as avg_for_tier. Every Month-to-Month row shows the same 125.00, because they share the same peers.
  4. Result: the original five rows, each now annotated with two extra columns — like sticky notes attached to intact rows, which is the whole difference from GROUP BY.
level_4_window.sql
-- "Rank customers by charges WITHIN each contract type -- keep every row."
SELECT   customer_id,
         contract_type,
         monthly_charges,
         RANK() OVER (PARTITION BY contract_type
                      ORDER BY monthly_charges DESC)         AS charge_rank,
         AVG(monthly_charges) OVER (PARTITION BY contract_type) AS avg_for_tier
FROM     subscriptions;
Output of level_4_window.sql — every input row survives, now annotated
customer_idcontract_typemonthly_chargescharge_rankavg_for_tier
C103Month-to-Month145.001125.00
C101Month-to-Month120.002125.00
C105Month-to-Month110.003125.00
C102One-Year85.50185.50
C104Two-Year45.00145.00

The family is bigger than RANK: ROW_NUMBER() for deduplication (you'll use it in the lab), LAG()/LEAD() for month-over-month deltas, NTILE(4) for quartiles, running totals via frame clauses. One pattern, a dozen dashboard questions.

Anatomy of a window function — the one line to know by heart
RANK()1 OVER2 (PARTITION BY contract_type3
             ORDER BY monthly_charges DESC4) AS charge_rank5
  1. The function. RANK() hands each row its position among its peers. Its siblings take the same clause: ROW_NUMBER() for one unique number per row, DENSE_RANK() for ranks without gaps, LAG() for the previous row's value, and plain AVG() or SUM() for a per-group figure. The common mistake is using RANK() to deduplicate: tied rows share a rank, so two rows can both be 1. Deduplication wants ROW_NUMBER().
  2. OVER. The word that turns an aggregate into a window function. Without it, AVG(monthly_charges) collapses the table and demands a GROUP BY; with it, every row is kept and the value is stamped onto each one. Leaving it out produces the classic error, "column must appear in the GROUP BY clause".
  3. PARTITION BY. Defines who counts as a peer. contract_type here means each row is ranked only against rows with the same contract. Omit it and the whole table is one window. The quiet mistake is partitioning at the wrong grain, say by customer_id: every row is then alone in its group, every rank is 1, and nothing errors.
  4. ORDER BY, inside the parentheses. Sets the order the ranking counts in, highest charge first because of DESC. It is independent of the query's outer ORDER BY, which only sorts the printed output. Forget DESC and rank 1 goes to the cheapest customer. Use ROW_NUMBER() over a column with ties and the numbering can change between runs; add a tiebreaker such as customer_id.
  5. AS charge_rank. Names the new column, marker 3 of Fig. 1.2. The mistake everyone makes once is WHERE charge_rank <= 3 in the same query. The engine evaluates window functions after WHERE, so the column does not exist yet. Wrap the query in a CTE and filter in the outer query, or in DuckDB write QUALIFY charge_rank <= 3, a clause that exists for exactly this.
🧠 Brain power

Before reading on: suppose C101 and C105 both paid $120. What ranks would RANK() assign within Month-to-Month — and what would DENSE_RANK() and ROW_NUMBER() do differently with the same tie?

Reveal the answer

RANK() gives both $120 rows rank 2 and then skips to 4 for the next row (Olympic medals: two silvers, no bronze). DENSE_RANK() gives both 2 and continues at 3 — no gap. ROW_NUMBER() refuses to acknowledge the tie: it hands out 2 and 3 in whatever order the ORDER BY leaves ambiguous — which means non-deterministic results unless you add a tiebreaker column. That's the trap interviewers are fishing for. Fig. 1.2b, right below, draws the three columns side by side; marker 3 is the trap.

M2M, IF C105 ALSO PAID 120.00 C103 · 145.00 C101 · 120.00 C105 · 120.00 two rows tie on the ORDER BY column 1 RANK() 1 2 2 ties share a rank; a 4th row would get 4, a gap 2 DENSE_RANK() 1 2 2 ties share a rank; a 4th row would get 3, no gap 3 ROW_NUMBER() 1 2 or 3 3 or 2 no tie allowed: which row gets 2 can change from run to run
Fig. 1.2b — The tie question drawn. C105's charge is changed to 120.00 here to force a tie (the real table has 110.00). Two functions admit the tie and differ only in what comes after it; the third pretends there is no tie and pays for it with results that change between runs.
  1. RANK. Olympic medals: two rows share rank 2, and the next rank would be 4 because two places were used. Fine for 'top three', wrong for 'exactly one row per group'.
  2. DENSE_RANK. Same shared 2, but the next rank would be 3. Use it when you want the rank numbers to have no gaps, for example to count distinct price tiers.
  3. ROW_NUMBER. Hands out 1, 2, 3 no matter what. With a tie the engine picks which of C101 and C105 gets 2, and it may pick differently tomorrow. That is why deduplication with ROW_NUMBER needs a tiebreaker in the ORDER BY, such as customer_id.

Level 5 — CTEs: pipelines the next engineer can read

Now the line Diana put first: MRR and retention by signup cohort. That needs two intermediate results, the month each customer signed up and the months each was active, joined by customer id and then counted per cohort. Writing it as one nested query would work and would be unreadable by the next engineer, who is the person who has to change it when the dashboard breaks. Level 5 names each step, which is how the query that becomes the dashboard's backbone stays maintainable.

Diana's actual ask — cohort retention — needs two intermediate results. Common Table Expressions (WITH ... AS) let you name each step, exactly like extracting well-named functions from a god-method:

Step-by-step: what level_5_cohorts.sql does, in plain English
  1. WITH cohorts AS (...) — define a named first step, like extracting a well-named helper function. For every customer, DATE_TRUNC('month', signup_date) chops the signup date down to the first day of its month (2025-01-15 becomes 2025-01-01), and that month is the customer's cohort — the group of everyone who signed up in the same month.
  2. activities AS (...) — a second named step doing the same date-chopping to each customer's activity dates.
  3. The main query joins the two steps together by customer id. LEFT JOIN again, so a customer with no activity at all would still be counted in their cohort.
  4. GROUP BY 1 — shorthand for "group by the first column in the SELECT list", i.e. one bucket per cohort month. In each bucket, COUNT(DISTINCT c.customer_id) counts how many customers the cohort started with, and COUNT(DISTINCT a.customer_id) counts how many of them show activity (DISTINCT makes sure a customer active five times still counts once).
  5. ORDER BY 1 — sort the cohorts chronologically. One row per signup month: size of the cohort, and how many are still active.
level_5_cohorts.sql
-- "Cohort retention for the CFO dashboard": one row per signup-month cohort.
WITH cohorts AS (
    -- Step 1: assign each customer to their signup-month cohort
    SELECT customer_id,
           DATE_TRUNC('month', signup_date) AS cohort_month
    FROM   subscriptions
),
activities AS (
    -- Step 2: months in which each customer was actually active
    SELECT customer_id,
           DATE_TRUNC('month', activity_date) AS active_month
    FROM   user_activity
)
SELECT c.cohort_month,
       COUNT(DISTINCT c.customer_id) AS total_cohort_users,
       COUNT(DISTINCT a.customer_id) AS active_users_now
FROM   cohorts c
LEFT JOIN activities a ON c.customer_id = a.customer_id
GROUP BY 1
ORDER BY 1;
Output of level_5_cohorts.sql — one row per signup-month cohort. (Every toy customer has at least one activity row, so retention reads 100% here; the production version with a month-offset join is where the numbers get interesting.)
cohort_monthtotal_cohort_usersactive_users_now
2025-01-0122
2025-02-0122
2025-03-0111
subscriptions C101 · signed up 2025-01-15 C102 · signed up 2025-01-20 C103 · signed up 2025-02-01 C104 · signed up 2025-02-10 C105 · signed up 2025-03-05 DATE_ TRUNC 1 cohorts (step 1) C101 · cohort Jan C102 · cohort Jan C103 · cohort Feb C104 · cohort Feb C105 · cohort Mar user_activity C101 · active 2025-03-02 C102 · active 2025-06-11 C103 · active 2025-06-28 C104 · active 2025-06-30 C105 · active 2025-02-20 DATE_ TRUNC 2 activities (step 2) C101 · active Mar C102 · active Jun C103 · active Jun C104 · active Jun C105 · active Feb 3 LEFT JOIN on customer_id, then GROUP BY cohort_month Jan: C101, C102 → 2 in, 2 active Feb: C103, C104 → 2 in, 2 active Mar: C105 → 1 in, 1 active 4 3 rows out 2025-01 · 2 · 2 2025-02 · 2 · 2 2025-03 · 1 · 1 cohort · total · active
Fig. 1.2c — Level 5 drawn as the pipeline it is. Each CTE is a named intermediate table you can read on its own; the final query only joins and counts. With the toy dates every customer is active, so every cohort reads 2 of 2 or 1 of 1.
  1. cohorts. DATE_TRUNC('month', signup_date) chops 2025-01-15 down to 2025-01-01, so C101 and C102 land in the January cohort, C103 and C104 in February, C105 in March. This step answers 'who belongs to which cohort' and nothing else.
  2. activities. The same chop applied to activity dates. This step answers 'which months was each customer seen in'. A customer seen five times in June would produce five rows here, which is why the final count uses DISTINCT.
  3. Join and count. LEFT JOIN by customer id keeps every cohort member even if they were never active, then GROUP BY cohort_month makes one pile per signup month and counts distinct ids on each side.
  4. The dashboard row. One row per cohort: how many signed up, how many are active. Swap the toy tables for production ones and add a month-offset join and this is the retention triangle in every SaaS board deck.

This query is the dashboard's backbone: swap the toy tables for production ones and add a month-offset join, and you have the retention triangle every SaaS board deck contains. When should a CTE become something else? A decision table you can reuse in interviews:

Decision table: CTE vs. subquery vs. temporary table
OptionChoose whenAvoid whenTypical cost
CTEReadability; result used once or twice in one queryReferenced many times — the engine may re-execute itFree to write, possibly recomputed
SubqueryOne-off inline logic, one level deepNested 3+ levels — unreadable, untestableFree, until a human has to modify it
Temp tableExpensive intermediate reused across queries; needs indexesSimple pipelines — adds state and cleanupStorage + explicit lifecycle

Before the two of them argue, look at what each one actually does. Fig. 1.2d asks the same question in both tools, draws where each one runs, and shows the one trap they share. Every line in the chat below points at a marker in this picture.

1 THE SAME QUESTION IN BOTH GRAMMARS, THE SAME THREE ROWS SQL SELECT contract_type, AVG(monthly_charges) FROM subscriptions GROUP BY 1 pandas df.groupby("contract_type") ["monthly_charges"].mean() Month-to-Month · 125.00 One-Year · 85.50 Two-Year · 45.00 same 3 rows, same numbers, on 5 rows or 5 million 2 WHERE EACH ONE RUNS the warehouse: 10,000,000 rows live here; SQL runs beside them GROUP BY: tens of ms · shipping rows out and looping: ~20 s .df(): a few thousand rows cross, one way only RAM on your laptop: the DataFrame lives here; pandas runs here groupby on those rows: ~1 s · then models, plots, LLM calls 3 THE SAME SILENT DEFAULT, TWO SPELLINGS SQL: LEFT JOIN (level 3) C101 · 2 tickets C103 · 1 ticket C102 · 0 tickets, kept pandas: merge() with no how= C101 · 2 tickets C103 · 1 ticket C102: gone, no error both defaults drop the unmatched row, without a warning; LEFT JOIN and how="left" are the spellings that keep C102.
Fig. 1.2d — Before the two of them argue, what each one actually does. Same question, same answer (panel 1); different places to run, and the hand-off between them is one method call (panel 2); the same trap with two spellings (panel 3). Every line in the chat below points at one of these three panels.
  1. Same question, same rows. On the five-row table SQL and pandas give identical output: Month-to-Month 125.00, One-Year 85.50, Two-Year 45.00. Neither tool is 'more correct'. The argument is about where the work happens and what happens next.
  2. Where each runs. SQL runs inside the warehouse, next to the ten million rows, and answers in tens of milliseconds. pandas runs in your laptop's memory on whatever crossed the .df() arrow. The twenty seconds in the race was the cost of shipping the rows across that arrow and looping over them one by one. The arrow points one way.
  3. Two spellings of one trap. In level 3, LEFT JOIN kept C102 with zero tickets. pandas merge() defaults to an inner join and drops her, exactly as INNER JOIN would in SQL. Neither tool warns. Both have an explicit spelling that keeps the row.
Fireside chat

Tonight's talk: SQL and pandas argue over the question, "Who's more important?"

SQL
pandas

Start at the top of Fig. 1.2d. One question, average charge per contract type, written in your grammar and in mine, and the same three rows come out: 125.00, 85.50, 45.00. So far we are equals. Now look at marker 2. Ten million rows, and the stopwatch says tens of milliseconds for me and twenty seconds for the loop that carried the rows to you. I run where the data lives. You need the data brought to you.

on a small table both tools give identical answers. The difference appears when the table is huge: SQL works inside the warehouse, so nothing has to be moved first.

That twenty seconds was not me. It was a plain Python for loop over ten million tuples, the slowest thing on the machine. Hand me the same rows as columns and my groupby finishes in about a second, which is the line under my box in marker 2. And notice what happens after your query returns the three rows in marker 1: nothing. Three rows are not a feature table, a training set or an eval set. That part is my job.

pandas is fast on column data that is already in memory; the slow part of the race was the row-by-row loop, not pandas. And SQL's job ends when the small result comes back. Turning it into features is pandas work.

About a second, after the rows have been serialized, shipped across the network and unpacked into your memory, which is the arrow in the middle of marker 2. Against a real warehouse that crossing is the twenty seconds, and you cannot make it go away. I am declarative: I say what I want, and a planner picks the join order and reads only the two columns it needs. You execute exactly what you were told, in RAM.

the cost that never goes away is moving the rows out of the warehouse. SQL avoids it by doing the work where the rows already are, and lets the database plan the fastest route.

In RAM, where scikit-learn lives. Every fit() call in Module 02 eats a DataFrame or the array behind it. Every plot, every feature someone engineers by hand, every ticket sent to a language model in Module 06 passes through me. You cannot call a model. You hand off, and the hand-off is the .df() arrow in marker 2, with my name on it.

models, plots and LLM calls all take in-memory data, and pandas is the in-memory shape. SQL's result has to become a DataFrame before any of that can happen.

The hand-off is the point. That arrow in marker 2 points one way: warehouse to workbench. You are the workbench, not the warehouse. And while we are being honest about who does what, look at marker 3. My LEFT JOIN kept C102, the customer with zero tickets. Your merge() defaults to an inner join and drops her. Same silent drop, same biased training set, and no error either way.

pandas comes after SQL, never instead of it. And both tools have a join default that quietly removes rows with no match; SQL's LEFT JOIN is the explicit way to keep them.

True, and I will own it: how="left" is one keyword away and people forget it. But your defaults have teeth too. Anyone who writes WHERE COUNT(*) > 5 gets an error, which is a kindness; anyone who writes ROW_NUMBER() without a tiebreaker gets a different answer every run and no error at all. Neither of us is safe by default. The difference is that a pytest file can catch mine.

both tools have traps that raise no error. pandas code lives in Python, where a unit test can check the row count; a SQL query pasted into a dashboard tool usually has no test around it.

And the analyst who does not know Python can read mine. That is the other thing you cannot do: be shared. The one query at the top of marker 1 serves the CFO's dashboard, the data scientist's notebook and the nightly job. Your notebook serves whoever has your laptop.

a saved SQL query is a shared asset that many people and tools can run. A pandas script needs Python and, usually, the person who wrote it.

Fair. Then let me name what you cannot do at all. You have no loop that calls out. You cannot retry a failed HTTP request, you cannot parse the JSON a model sends back, you cannot hold a Pydantic contract. Everything in Act III that touches the network starts where you stop.

SQL cannot talk to the outside world. Anything that calls an API, handles errors or validates a response has to be written in Python.

Then we agree on the order of operations, and it is the arrow in marker 2. I condense ten million rows to a few thousand. You turn a few thousand into features, evals and prompts. Anyone who does my job in your memory gets the twenty-second loop. Anyone who does your job in my syntax gets a four-hundred-line CASE statement.

SQL first, to shrink the data; pandas second, to shape it. Doing either job with the other tool is possible and painful.

Agreed. And DuckDB, the engine hosting this chapter, will run your SQL directly on one of my DataFrames, in the same process, by variable name. We are closer than this argument suggests.

DuckDB can run a SQL query against a pandas DataFrame directly, so on a laptop the two tools sit side by side in one program.

We are. We'll revisit who's more important when the dashboard is due at end of day.

neither wins. Diana's dashboard needs both, in that order.

04 · The lie detectorStatistics — Is That Number Real?

The dashboard's numbers now come out of the warehouse. The last line of Diana's memo was a warning: the product team's "huge checkout win" needs more scrutiny than applause. The numbers behind that claim are 55 conversions out of 420 visitors on the old page against 66 out of 410 on the new one, and the VP wants the new page rolled out company-wide on the strength of it, with an estimated $180K downside if the win is not real. The team needs a way to say whether a gap that size could be luck, and this section builds it.

Field report · The A/B test that almost bankrupted us

"The product team ran a two-week test on the new checkout flow: 420 visitors saw the old page (55 converted), 410 saw the new one (66 converted). That's 13.1% against 16.1% — a three-point lift, a 23% relative improvement.

The VP wanted it shipped company-wide by Friday. Then our data scientist asked one question: 'What's the p-value?' It was 0.22. If the new page actually changed nothing, results at least this extreme would still show up in about one test in five, just from noise.

We were about to rebuild our checkout page on the strength of a coin flip. Estimated downside if the true effect was zero or negative: $180K."

— Postmortem notes, SaaSify growth team
Go deeper when you're ready

This section teaches the single most important statistical tool — deciding whether a difference is real. Its companion chapter, Module 01b · Statistics Intuition, builds the rest of the everyday toolkit from zero — averages that mislead, precision and recall, base rates, calibration, correlation traps, expected value — with real-life scenarios and practice problems. Read it right after this module (it is the next page), or jump there now if the ideas here feel like they need more ground under them.

"Do I really need statistics to call an API? I have shipped two LLM features already and never computed a p-value."

— an engineer who has shipped two LLM features, right about now

No. Calling the API takes an HTTP client and a key; the async section on this page covers it. Statistics enters the moment you change something and want to know whether it helped. Prompt v2 passes 41 of 50 evals, v1 passed 36. Do you ship v2? That is the SaaSify checkout question with the nouns changed, and gut feeling gets it wrong about as often as a coin. Fig. 1.2e, right below, draws both questions side by side: the gap between the two prompts at marker 2 is about one lucky wobble long, exactly like the checkout gap at marker 1.

You will face that question weekly: a new model version, a new chunk size, a new system prompt. Without the tools in this section you will ship noise and roll back real wins. The scope is small on purpose: one test for comparing two rates, one formula for the error bar around a score, and percentiles for latency. That covers most of the statistics an AI engineer uses.

The honest downside: statistics tells you whether a difference is trustworthy, never why it happened, and it charges for the answer in samples. A trustworthy comparison needs hundreds of labelled cases, not twenty, and building that eval set is slow, unglamorous work. Module 07 is about paying that cost efficiently.

1 THE CHECKOUT TEST (scale: 20 px per point) 13.1% old page: 55 of 420 16.1% new page: 66 of 410 gap = 3.0 pt one lucky wobble (SE) = 2.45 pt z = gap ÷ wobble = 3.0 ÷ 2.45 = 1.22 wobbles p = 0.22: luck alone makes a gap this big 1 test in 5 2 THE PROMPT TEST (scale: 6 px per point) 72% prompt v1: 36 of 50 82% prompt v2: 41 of 50 gap = 10 pt one lucky wobble (SE) = 8.4 pt z = gap ÷ wobble = 10 ÷ 8.4 = 1.19 wobbles p = 0.23: luck alone makes a gap this big 1 test in 4 3 different scales, same shape: in both pictures the gap is about one wobble long, so both verdicts are 'not proven'
Fig. 1.2e — The checkout question and the prompt question are the same picture. The prompt numbers (36 and 41 of 50) are run through this page's ab_test_engine formula: z = 1.19, p = 0.23, computed for this figure. The two panels use different scales so that the shapes can be compared.
  1. The checkout test. The gap between the two dots is 3.0 points. The wobble ruler under it is the size of a gap that luck alone produces between two groups of 420 and 410 visitors: 2.45 points. The gap is 1.22 wobbles long, and that is not far enough from zero.
  2. The prompt test. A 10-point gap looks bigger, but with only 50 evals per prompt the lucky wobble is 8.4 points. The gap is 1.19 wobbles: the same shape as the checkout test, and the same verdict.
  3. One rule. Whatever the nouns, the question is always 'how many wobbles long is the gap?'. Above about two wobbles, luck becomes a poor explanation. Both of these are around one.

Statistics saved $180K in one meeting — and the same scene plays out in AI work every week, with "checkout page" swapped for "prompt v2" or "the new model". The tool behind it is called hypothesis testing.

The name sounds intimidating, but the idea underneath is one you already use in daily life: before you believe that a difference is real, you ask how easily plain luck could have produced it. If luck could easily produce it, you have not learned anything yet.

Everything in this section — every symbol, every formula — is just that one question made precise.

A courtroom is a good way to keep the pieces straight, so let's walk through it slowly. In a trial, the defendant is presumed innocent until the evidence is strong enough to say otherwise. Hypothesis testing works exactly the same way.

The null hypothesis (written H₀, pronounced "H-nought" or "H-zero") is the presumption of innocence. It says: the change did nothing — version A and version B are equally good, and any difference you measured is just luck.

The alternative hypothesis (H₁, read "H-one") is the accusation: version B really is different. Your job is not to prove B is better. Your job is to ask whether the evidence is strong enough to reject the boring explanation.

The p-value is the strength-of-evidence report, and it answers exactly one question: if the change truly did nothing, how often would luck alone still produce a difference this big? A small p-value (say 0.01) means "luck produces a result like this only 1 time in 100 — so the effect is probably real".

A large p-value (say 0.22) means "luck produces a result like this about 1 time in 5 — far too ordinary to build a decision on". Before you look at any data, you commit to a cutoff called α (alpha), almost always 0.05, meaning 5%.

If the p-value comes in below α, you call the result statistically significant — evidence strong enough to act on. If it comes in at or above α, you do not.

That procedure leaves two ways to be wrong, and both have standard names that interviewers expect you to know.

Shipping a change that actually did nothing — convicting an innocent defendant — is a Type I error, also called a false positive or a false alarm.

Sitting on a change that actually worked — letting a guilty defendant walk free — is a Type II error, a false negative, a missed win.

The α (alpha) = 0.05 cutoff is you deciding, in advance, that you can live with a 5% false-alarm rate.

1 100 REPEATS IF THE PAGE DID NOTHING 22 of 100 show a 3-point gap by luck alone that is p = 0.22: about 1 repeat in 5 2 THE FALSE-ALARM RATE YOU AGREED TO α = 0.05: act only if luck would do this in 5 of 100 or fewer. 22 > 5: do not act 3 THE COURTROOM: TWO MISTAKES you ship you hold truth: no effect truth: real effect Type I false alarm correct correct Type II missed win α is the Type I rate you accept (5 in 100). Power = 1 − β is the chance of not making a Type II error; the meeting's test had power 0.23.
Fig. 1.2f — The p-value, α and the two error types drawn with the meeting's numbers. p = 0.22 is 22 lucky repeats in 100; α = 0.05 is the 5-in-100 ceiling you set in advance; 22 is above 5, so the checkout claim stays unproven.
  1. The p-value as dots. Imagine the checkout test run 100 times in a world where the new page truly changes nothing. Luck alone would still hand 22 of those runs a gap of three points or more. That count, 22 in 100, is the p-value 0.22. It says nothing about how likely the page is to be better; it only says how ordinary this result would be if it were not.
  2. α as dots. Before looking at any data you decided how many lucky runs in 100 you can tolerate mistaking for a real effect: 5. The test's 22 is far above that ceiling, so the rule says hold. Setting the ceiling after seeing the data is how teams fool themselves.
  3. The two mistakes. Ship a page that did nothing and you made a Type I error, a false alarm; α is the rate of those you accepted. Hold a page that really worked and you made a Type II error, a missed win; power is the chance of avoiding that, and the meeting's test had only 0.23 of it.

One warning before the verdict pipeline in Fig. 1.3, because interviewers love this trap (we set it up again in section 08): the p-value is not "the probability that B is better", and p = 0.22 does not mean "there is a 78% chance the lift is real". The 22 shaded dots at marker 1 of Fig. 1.2f are lucky repeats, not a vote for the new page.

The p-value only describes an imaginary world where the change did nothing, and tells you how ordinary your data would look there.

In the SaaSify test, p = 0.22 says: even if the new page changed nothing at all, about one test in five would show a lift this size purely by luck. That is why the data scientist refused to ship. Here is the whole decision, start to finish:

raw counts A: 420 visitors, 55 conv · B: 410 visitors, 66 conv conversion rates & lift 13.1% vs 16.1% → +3.0 pt how big is the noise? standard error & z-score z = lift ÷ SE = 1.23 how surprising under H₀? p-value & 95% CI p = 0.22 · CI [−1.8 pt, +7.8 pt] p < α (alpha) = 0.05 ? no not proven — keep testing yes real lift — ship B 1 2 3 4 5
Fig. 1.3 — The A/B verdict pipeline: counts → rates → noise estimate → surprise measure → pre-committed decision. The SaaSify test exits left.
  1. Counts. The only raw facts: 55 of 420 and 66 of 410. Everything below is arithmetic on these four numbers, which is why the script that follows takes exactly four arguments.
  2. Rates and lift. 55 ÷ 420 = 13.1%, 66 ÷ 410 = 16.1%, a lift of 3.0 points. This is the number the VP saw. It is real as a description of the two weeks; the question is whether it says anything about the next two weeks.
  3. Noise and surprise. The standard error, 2.45 points, is the size of a gap luck produces between groups this big. z = 3.0 ÷ 2.45 = 1.22 says the lift is 1.22 lucky wobbles long. Fig. 1.2e drew this ruler.
  4. p-value and interval. A z of 1.22 happens by luck 22 times in 100 (Fig. 1.2f, marker 1). The 95% interval for the true lift runs from −1.8 to +7.8 points: it includes zero and it includes 'worse'.
  5. The pre-committed decision. p = 0.22 is not below α = 0.05, so the test exits left: not proven, keep testing. The cutoff was fixed before the data arrived, which is the only reason the exit is a decision and not a debate.

Statistics has a notation problem: it writes ordinary ideas in Greek letters and then expects you to know how to say them out loud. So before any more symbols appear, here is the full cast — every symbol this section uses, how to pronounce it, and what it means in plain words. You do not need to memorize this table; keep it as the thing you glance back at whenever a squiggle interrupts your reading.

Every symbol in this section — how to say it, and what it means
SymbolHow to say itWhat it means in plain words
H₀"H-nought" or "H-zero"The null hypothesis — the boring explanation: "the change did nothing; any difference you measured is luck."
H₁"H-one"The alternative hypothesis — the interesting claim: "the change made a real difference."
p"p-value"If the change truly did nothing, how often luck alone would still produce a difference this big. Small p = hard to blame on luck.
α"alpha"Your pre-committed cutoff for the p-value, usually 0.05. Below it, you act; at or above it, you keep testing.
z"z-score" / "z-statistic"The observed lift divided by the typical size of a lucky wobble — "how many noise-widths away from zero is this result?"
t"t-statistic"The same idea as z, used when comparing two averages whose spread you estimated from the data itself.
SE"standard error"The typical size of the random wobble in a measurement. The noise-width that z and t divide by.
CI"confidence interval"The range where the true value plausibly sits, given the data you have. The honest error bar around any single number.
n"n" (sample size)How many visitors, examples, or measurements you actually had. Every other row gets more trustworthy as n grows.
β"beta"The probability of missing a real effect (a Type II error). Power = 1 − β: the meeting's test had power 0.23, so β was 0.77.
x̄"x-bar"The average of a group of measurements. The bar on top always means "average of".
s²"s-squared" (the variance)How spread out a group's values are. Its square root, s, is the standard deviation — the spread in the original units.
σ"sigma"The standard deviation of a whole population (s is the sample's estimate of it). You'll meet it as sigma=0.6 in the latency script below.
μ"mu"The true average of a whole population — the number x̄ is trying to estimate.
√"square root"Appears wherever noise is being averaged down. It is why 4× the data buys only 2× the precision.
±"plus or minus"The wobble goes both ways: "70% ± 10 points" means anywhere from 60% to 80%.
≈"approximately equal to"Close enough for the decision at hand — the working precision of real statistics.

The formula in the fifth row below has not been explained yet. Section 06, "Under the hood", shows where the standard error comes from. For now treat it as a recipe and follow it with a calculator: every row here is one line of the script that follows.

Sharpen your pencil

Run the meeting's numbers by hand, once, and the code below will read as arithmetic you have already done. The old page: 420 visitors, 55 converted. The new page: 410 visitors, 66 converted. Work each row to four decimal places. Three rows are filled in to get you started.

p_c = 55 / 4200.1310, the old page's conversion rate
p_t = 66 / 410
lift = p_t − p_c
p_pool = (55 + 66) / (420 + 410)0.1458, the rate if both pages were secretly the same page: 121 conversions out of 830 visitors
SE = √( p_pool · (1 − p_pool) · (1/420 + 1/410) )
z = lift / SE
Is z above 1.96?1.96 is the z that matches α (alpha) = 0.05 when the lift could go either way. Below it, luck is still a plausible explanation.
Verdict

Symbol key: p_c and p_t are the control and treatment conversion rates; p_pool is the pooled rate; SE (say "standard error") is the typical size of a lucky difference between two groups of these sizes; √ is the square root; · means multiply; z is the lift measured in units of SE.

Check your answers
p_t = 66 / 4100.1610
lift = p_t − p_c0.1610 − 0.1310 = 0.0300, a three-point lift
SEp_pool · (1 − p_pool) = 0.1458 × 0.8542 = 0.1245. Then 1/420 + 1/410 = 0.0024 + 0.0024 = 0.0048. Multiply: 0.1245 × 0.0048 = 0.0006. Square root: 0.0245
z = lift / SE0.0300 / 0.0245 ≈ 1.22 (with unrounded intermediates, 1.2255; the script prints 1.225)
Is z above 1.96?No
VerdictNot proven. Do not ship on this evidence; collect more data

What the numbers mean. The lift is three points. A lucky difference between two groups of this size is typically about 2.5 points (the SE), so the observed lift is only 1.2 wobbles away from zero. Luck produces a gap that large about one test in five, which is the p = 0.22 the data scientist quoted.

Now notice what sample size does to the formula. SE shrinks with the square root of n. Ten times the visitors makes SE about 3.2 times smaller, the same 0.0300 lift becomes z ≈ 3.9, and the verdict flips. That is the second run of the script below, and you have just predicted its output.

Now the code that ran in that meeting.

The test it performs has a formal name — a two-proportion z-test, the standard tool for comparing two rates, such as two conversion rates or two eval pass rates — but you do not need to memorize the name to read the function.

It follows the diagram above step by step: compute the two rates, compute the lift, estimate the noise, turn the lift into a surprise score, and return a verdict. Every line that does something non-obvious carries a comment explaining why.

You will reuse this exact class in Module 07, with "conversion rate" swapped for "eval pass rate" — the mathematics does not notice the difference.

Build it in chunks

We build ab_test_engine.py in six chunks, each one a working program. The files are in code/01-working-stack/ladder/; every one is the previous file plus the lines shown, and chunk 6 is the whole thing.

  1. Chunk 1 — turn four counts into two rates and a lift

    We start with the part you already did by hand in the pencil box above: divide conversions by visitors, then subtract. Nothing about luck yet; the next chunks add that.

    Step-by-step: what this chunk does, in plain English
    1. Define run_ab_test with four counts: visitors and conversions for the control group, then the same for the treatment group.
    2. Divide conversions by visitors in each group to get the two rates.
    3. Subtract: the lift is the treatment rate minus the control rate.
    4. Return the three numbers in a dictionary, and print them for the meeting's real counts.
    ab_test_engine.py — chunk 1runs offline
    def run_ab_test(control_visitors, control_conversions,
                    treatment_visitors, treatment_conversions):
        p_c = control_conversions / control_visitors
        p_t = treatment_conversions / treatment_visitors
        lift = p_t - p_c
        return {"control_rate": p_c, "treatment_rate": p_t, "lift": lift}
    
    
    if __name__ == "__main__":
        print(run_ab_test(420, 55, 410, 66))   # the two-week checkout test
    

    A function with named arguments, and a dictionary as the return value.

    Save as chunk1_rates.py and run python3 chunk1_rates.py. You should see {'control_rate': 0.13095238095238096, 'treatment_rate': 0.16097560975609757, 'lift': 0.030023228803716606}: 13.1% to 16.1%, a lift of 3.0 points.

  2. Chunk 2 — measure the noise: pooled rate, standard error, z

    A 3-point lift means nothing until you know how big a lucky 3-point lift is for groups this size. That size is the standard error, and dividing the lift by it gives z.

    Step-by-step: what this chunk does, in plain English
    1. Add two import lines at the top of the file: numpy for the square root, scipy for the normal distribution used in chunk 3.
    2. Pool both groups into one rate, because the question is what luck alone would do if the two groups were really the same.
    3. Compute the standard error from the pooled rate and the two group sizes.
    4. Divide the lift by the standard error to get z, guarding against dividing by zero.
    5. The return line changes: it now hands back the lift, the standard error and z.
    ab_test_engine.py — chunk 2 (adds to chunk 1)runs offline
    import numpy as np
    from scipy import stats        # first used in chunk 3
    
    # inside run_ab_test, after `lift = p_t - p_c`:
        # Pooled rate: under H0 both arms share ONE true rate, so the noise
        # estimate must come from the combined data, not from either arm alone.
        p_pool = (control_conversions + treatment_conversions) / (
            control_visitors + treatment_visitors
        )
        se = float(np.sqrt(
            p_pool * (1 - p_pool) * (1 / control_visitors + 1 / treatment_visitors)
        ))
        z = lift / se if se > 0 else 0.0
        return {"lift": lift, "se": se, "z": z}   # replaces the chunk 1 return
    

    np.sqrt, and a one-line x if condition else y expression.

    Run python3 chunk2_noise.py. You should see {'lift': 0.030023228803716606, 'se': 0.024499667086772654, 'z': 1.2254545621938724}: the same z of about 1.2 you worked out by pencil.

  3. Chunk 3 — turn z into a p-value and a 95% interval

    z = 1.2 is a score; the p-value says how often luck alone beats it, and the interval says which true lifts are still plausible.

    Step-by-step: what this chunk does, in plain English
    1. Add alpha=0.05 to the function's arguments: the cutoff you decide before looking.
    2. Convert z to a p-value with the normal distribution's survival function, doubled because a lucky difference could go either way.
    3. Find the z value that marks the middle 95%, then build the interval as the lift plus and minus that many standard errors.
    4. The return line changes again: lift, z, p-value and interval.
    ab_test_engine.py — chunk 3 (adds to chunk 2)runs offline
    # signature gains a last argument:  ..., treatment_conversions, alpha=0.05):
        # Survival function, not 1 - cdf: same math, but sf() keeps precision
        # for large z where 1 - cdf underflows to exactly 0.
        p_value = 2 * float(stats.norm.sf(abs(z)))
    
        z_crit = float(stats.norm.ppf(1 - alpha / 2))
        ci = (lift - z_crit * se, lift + z_crit * se)
        return {"lift": lift, "z": z, "p_value": p_value, "ci_95": ci}
    

    stats.norm.sf and stats.norm.ppf, scipy's normal-distribution tail and its inverse.

    Run python3 chunk3_pvalue.py. You should see p_value of 0.2204 (22 lucky repeats in 100, above the 5 you allow) and an interval of about -0.018 to 0.078, which contains zero.

  4. Chunk 4 — ask how likely this test was to catch a real effect

    A p-value of 0.22 can mean there is no effect, or that the test was too small to see one. Power tells you which.

    Step-by-step: what this chunk does, in plain English
    1. Compute the spread of the observed lift, using each group's own rate this time.
    2. Convert the lift, measured in those spreads and minus the cutoff, into the chance a test of this size would have caught it.
    3. Add power to the returned dictionary.
    ab_test_engine.py — chunk 4 (adds to chunk 3)runs offline
        # Power: probability a test of THIS size would detect THIS effect.
        effect_se = float(np.sqrt(
            p_c * (1 - p_c) / control_visitors
            + p_t * (1 - p_t) / treatment_visitors
        ))
        power = float(stats.norm.cdf(abs(lift) / effect_se - z_crit)) if effect_se > 0 else 0.0
        # and the return gains  "power": power
    

    stats.norm.cdf, the probability of landing below a value.

    Run python3 chunk4_power.py. The dictionary now ends with 'power': 0.231 (rounded): this test had a 23% chance to notice a real 3-point lift.

  5. Chunk 5 — pack everything into a result object with a verdict

    The dictionary works but invites typos. A frozen dataclass names every field, rounds once, and carries the verdict as a property. The function now runs on both the meeting's numbers and the ten-times-traffic case.

    Step-by-step: what this chunk does, in plain English
    1. Define ABTestResult as a frozen dataclass, a record that cannot be changed after it is made.
    2. Add a verdict property: ship if the p-value beat alpha, otherwise collect more data.
    3. Replace the dictionary return with an ABTestResult, rounding each number once, and set is_significant to whether the p-value is below alpha.
    4. Add the signature types and a main block that prints both runs.
    ab_test_engine.py — chunk 5 (adds to chunk 4)runs offline
    @dataclass(frozen=True)
    class ABTestResult:
        control_rate: float
        treatment_rate: float
        absolute_lift: float
        relative_lift_pct: float
        z_statistic: float
        p_value: float
        ci_95: tuple[float, float]
        power: float
        is_significant: bool
    
        @property
        def verdict(self) -> str:
            return ("Ship it -- the lift is real beyond reasonable doubt."
                    if self.is_significant
                    else "Do NOT ship on this evidence. Collect more data.")
    
    # ...and at the end of run_ab_test, instead of the dictionary:
        return ABTestResult(
            control_rate=round(p_c, 4),
            treatment_rate=round(p_t, 4),
            absolute_lift=round(lift, 4),
            relative_lift_pct=round(100 * lift / p_c, 2) if p_c else 0.0,
            z_statistic=round(z, 3),
            p_value=round(p_value, 5),
            ci_95=(round(ci[0], 4), round(ci[1], 4)),
            power=round(power, 3),
            is_significant=p_value < alpha,
        )
    

    @dataclass(frozen=True) and @property (plus from dataclasses import dataclass at the top).

    Run python3 chunk5_pack.py. The meeting prints z=1.225 p=0.2204 CI=(-0.018, 0.078) power=0.231 and "Do NOT ship"; the ten-times-traffic run prints z=3.875 p=0.00011 and "Ship it". Same lift, different verdict.

  6. Chunk 6 — run the arithmetic backwards: how many visitors before you start?

    The first five chunks judge a test after the fact. This last one answers the question to ask before: how big must the test be?

    Step-by-step: what this chunk does, in plain English
    1. Take the current rate, the smallest lift you care about, alpha and the power you want.
    2. Look up the two z values for alpha and for power.
    3. Plug them into the standard sample-size formula and round up to a whole visitor.
    4. Print the answer next to the meeting's actual 420.
    ab_test_engine.py — chunk 6 (the whole file below)runs offline
    def required_sample_size(
        baseline_rate: float,
        minimum_detectable_effect: float,
        alpha: float = 0.05,
        power: float = 0.80,
    ) -> int:
        """Visitors per arm needed BEFORE the test. Run this first, always:
        an underpowered test is a decision you have already made to guess."""
        p1, p2 = baseline_rate, baseline_rate + minimum_detectable_effect
        p_bar = (p1 + p2) / 2            # the rate the no-effect world would show: the average of the two
        z_a = float(stats.norm.ppf(1 - alpha / 2))
        z_b = float(stats.norm.ppf(power))
        num = (z_a * np.sqrt(2 * p_bar * (1 - p_bar))
               + z_b * np.sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2
        return int(np.ceil(num / (p2 - p1) ** 2))
    

    np.ceil, rounding up, because 2,161.2 visitors means 2,162.

    Run python3 chunk6_sample_size.py. The last line reads To detect a 3-pt lift from 13% with 80% power: 2,162 per arm (4,324 total). The meeting's test had 420. This file is the whole program below.

The whole program

Chunk 1 starts at the rates line inside run_ab_test, chunk 2 at the pooled rate, chunk 3 at the survival function, chunk 4 at the power comment. Chunk 5 is the ABTestResult class plus the return ABTestResult(...) at the end of the function and the run-both-cases block, and chunk 6 is required_sample_size and the final print. Each chunk starts with a # ── chunk n ── comment.

Step-by-step: what ab_test_engine.py does, in plain English
  1. Define ABTestResult — a read-only report card (that is what @dataclass(frozen=True) gives you) with a named slot for every number the test produces. Its verdict property turns the yes/no significance flag into a sentence a human can act on.
  2. run_ab_test starts by computing each group's conversion rate: conversions divided by visitors. The lift is simply the treatment rate minus the control rate.
  3. Compute p_pool — the conversion rate you get if you mix both groups together. Why mix them? Because the null hypothesis says both groups share one true rate, and we must measure the noise in that imagined world, so the noise estimate has to come from the combined data.
  4. Compute se, the standard error — the typical size of a purely lucky difference between two groups of these sizes — using the formula from the Under-the-hood section.
  5. Compute z: the lift divided by that noise size. Read it as "the observed difference is z times bigger than a typical lucky wobble". (The if se > 0 guard just avoids dividing by zero.)
  6. Turn z into the p_value: how often luck alone would produce a z at least this extreme, in either direction (that is why it is multiplied by 2 — a "two-tailed" test). The code uses stats.norm.sf, the survival function, instead of 1 − cdf purely for numerical precision with very large z.
  7. Build the 95% confidence interval: lift ± 1.96 × se — the range where the true lift plausibly sits.
  8. Compute the statistical power: the probability that a test with these group sizes would successfully detect an effect of this size.
  9. Round everything and pack it into an ABTestResult, whose is_significant is simply "was the p-value below α?".
  10. required_sample_size runs the arithmetic in reverse: give it your current rate, the smallest lift you care about detecting, and the power you want, and it answers "how many visitors per group do you need before you start?"
  11. The bottom block runs the meeting's real numbers, then the same rates with ten times the traffic, prints both verdicts, and finally prints the sample size the meeting's test should have had.
ab_test_engine.pyruns offline
# pip install numpy "scipy>=1.14,<2"    # scipy 1.16 current as of Aug 2026
"""SaaSify A/B test engine: two-proportion z-test with CI, power, and verdict.

Module 07 reuses this unchanged to compare models and prompts --
"conversion rate" becomes "eval pass rate", the math doesn't notice.
"""
# ── chunk 5: the result object (its return statement is at the end of run_ab_test) ──
from dataclasses import dataclass

import numpy as np
from scipy import stats


@dataclass(frozen=True)
class ABTestResult:
    control_rate: float
    treatment_rate: float
    absolute_lift: float
    relative_lift_pct: float
    z_statistic: float
    p_value: float
    ci_95: tuple[float, float]
    power: float
    is_significant: bool

    @property
    def verdict(self) -> str:
        return ("Ship it -- the lift is real beyond reasonable doubt."
                if self.is_significant
                else "Do NOT ship on this evidence. Collect more data.")


def run_ab_test(
    control_visitors: int,
    control_conversions: int,
    treatment_visitors: int,
    treatment_conversions: int,
    alpha: float = 0.05,
) -> ABTestResult:
    # ── chunk 1: rates and lift ──
    p_c = control_conversions / control_visitors
    p_t = treatment_conversions / treatment_visitors
    lift = p_t - p_c

    # ── chunk 2: noise, pooled rate and z ──
    # Pooled rate: under H0 both arms share ONE true rate, so the noise
    # estimate must come from the combined data, not from either arm alone.
    p_pool = (control_conversions + treatment_conversions) / (
        control_visitors + treatment_visitors
    )
    se = float(np.sqrt(
        p_pool * (1 - p_pool) * (1 / control_visitors + 1 / treatment_visitors)
    ))
    z = lift / se if se > 0 else 0.0

    # ── chunk 3: p-value and interval ──
    # Survival function, not 1 - cdf: same math, but sf() keeps precision
    # for large z where 1 - cdf underflows to exactly 0.
    p_value = 2 * float(stats.norm.sf(abs(z)))

    z_crit = float(stats.norm.ppf(1 - alpha / 2))
    ci = (lift - z_crit * se, lift + z_crit * se)

    # ── chunk 4: power ──
    # Power: probability a test of THIS size would detect THIS effect.
    effect_se = float(np.sqrt(
        p_c * (1 - p_c) / control_visitors
        + p_t * (1 - p_t) / treatment_visitors
    ))
    power = float(stats.norm.cdf(abs(lift) / effect_se - z_crit)) if effect_se > 0 else 0.0

    return ABTestResult(
        control_rate=round(p_c, 4),
        treatment_rate=round(p_t, 4),
        absolute_lift=round(lift, 4),
        relative_lift_pct=round(100 * lift / p_c, 2) if p_c else 0.0,
        z_statistic=round(z, 3),
        p_value=round(p_value, 5),
        ci_95=(round(ci[0], 4), round(ci[1], 4)),
        power=round(power, 3),
        is_significant=p_value < alpha,
    )


# ── chunk 6: sample size before the test ──
def required_sample_size(
    baseline_rate: float,
    minimum_detectable_effect: float,
    alpha: float = 0.05,
    power: float = 0.80,
) -> int:
    """Visitors per arm needed BEFORE the test. Run this first, always:
    an underpowered test is a decision you have already made to guess."""
    p1, p2 = baseline_rate, baseline_rate + minimum_detectable_effect
    p_bar = (p1 + p2) / 2            # the rate the no-effect world would show: the average of the two
    z_a = float(stats.norm.ppf(1 - alpha / 2))
    z_b = float(stats.norm.ppf(power))
    num = (z_a * np.sqrt(2 * p_bar * (1 - p_bar))
           + z_b * np.sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2
    return int(np.ceil(num / (p2 - p1) ** 2))


if __name__ == "__main__":
    meeting = run_ab_test(420, 55, 410, 66)      # the two-week checkout test
    tenfold = run_ab_test(4200, 550, 4100, 660)  # same rates, 10x the traffic

    for name, r in [("The $180K meeting", meeting), ("Same lift, 10x data", tenfold)]:
        print(f"--- {name} ---")
        print(f"  {r.control_rate:.1%} -> {r.treatment_rate:.1%}  "
              f"(+{r.absolute_lift:.1%} abs, +{r.relative_lift_pct:.1f}% rel)")
        print(f"  z={r.z_statistic}  p={r.p_value}  CI={r.ci_95}  power={r.power}")
        print(f"  {r.verdict}")

    n = required_sample_size(baseline_rate=0.13, minimum_detectable_effect=0.03)
    print(f"\nTo detect a 3-pt lift from 13% with 80% power: {n:,} per arm "
          f"({2 * n:,} total). The meeting's test had 420.")
terminal
--- The $180K meeting ---
  13.1% -> 16.1%  (+3.0% abs, +22.9% rel)
  z=1.225  p=0.22043  CI=(-0.018, 0.078)  power=0.231
  Do NOT ship on this evidence. Collect more data.
--- Same lift, 10x data ---
  13.1% -> 16.1%  (+3.0% abs, +22.9% rel)
  z=3.875  p=0.00011  CI=(0.0148, 0.0452)  power=0.972
  Ship it -- the lift is real beyond reasonable doubt.

To detect a 3-pt lift from 13% with 80% power: 2,162 per arm (4,324 total).
The meeting's test had 420.
1 THE MEETING: 420 vs 410 VISITORS 13.1% 55 of 420 16.1% 66 of 410 A (old) B (new) gap 3.0 pt one lucky wobble (SE) = 2.45 pt, same scale as the bars z = 3.0 ÷ 2.45 = 1.22 wobbles p = 0.22 → not proven 2 SAME RATES, 10× THE TRAFFIC: 4,200 vs 4,100 13.1% 550 of 4,200 16.1% 660 of 4,100 A (old) B (new) gap 3.0 pt one lucky wobble (SE) = 0.77 pt, same scale as the bars z = 3.0 ÷ 0.77 = 3.9 wobbles p = 0.0001 → ship it 3 WHERE THE TRUE LIFT PLAUSIBLY SITS (95% CI), IN POINTS -3 0 = no lift +3 +6 +9 meeting: −1.8 to +7.8, zero inside, 'worse' inside 10× traffic: +1.5 to +4.5, every value positive
Fig. 1.3b — The two runs of ab_test_engine.py, drawn. The bars are identical in both panels; only the wobble ruler shrinks, from 2.45 to 0.77 points, and that is what turns 1.22 wobbles into 3.9 and moves the interval off zero.
  1. The meeting's test. Same 3.0-point gap as the terminal output. The wobble ruler is 2.45 points, so the gap is 1.22 wobbles long: z = 1.225 in the printout. That happens by luck about one test in five, so the verdict is not proven.
  2. Ten times the data. The bars do not move. The wobble ruler shrinks by √10 ≈ 3.2, to 0.77 points, so the same gap is now 3.9 wobbles long: z = 3.875 in the printout. Luck makes that about one test in ten thousand. Same lift, different verdict, only because the ruler shrank.
  3. The intervals. Read the range where the true lift plausibly sits. The meeting's range runs from −1.8 to +7.8 points: it contains zero and negative values, so the data is consistent with the new page doing nothing or being worse. The 10× range, +1.5 to +4.5, contains only positive values.

Read the two runs side by side, panel 1 against panel 2 of Fig. 1.3b, because this is the moment the whole subject clicks. The measured lift is identical in both: 13.1% against 16.1%. The only thing that changed is the amount of data, and with it the wobble ruler under each panel, and the verdict flipped from "do not ship" to "ship it". That is the entire subject in one sentence: a difference becomes believable when you have enough data that luck can no longer explain it.

You can watch that happen in the confidence interval — the range where the true lift plausibly sits, given the data you have. With the small test, that range was "−1.8 to +7.8 points", the upper range at marker 3 of Fig. 1.3b.

Look carefully at what it contains: zero is inside it, and so are negative values. In plain terms, the data was consistent with the new page doing nothing, and even with it being worse.

With ten times the data, the range tightened to "+1.5 to +4.5 points" — every value in it is positive, so the lift is real and you even know roughly how big it is.

Then the sample-size calculator delivers the punchline. Run before a test, it tells you how much data you need for the test to be trustworthy. A trustworthy version of this checkout test needed about 2,000 visitors per arm; the meeting's test had 420.

It was doomed before it started. Its power — the probability that a test of this size would successfully detect a real effect of this size — was only 23%.

In plain terms: even if the new page genuinely worked, a test this small would have failed to prove it three times out of four. That is why the docstring calls an underpowered test "a decision you have already made to guess".

The stats you'll actually use in 2026

The checkout verdict used one tool, the two-proportion z-test, and it will be the same tool when the question becomes "prompt v2 passed 41 of 50 evals, v1 passed 36" (Fig. 1.2e drew both). Two more questions arrive with every AI feature SaaSify ships after the dashboard: how far a single eval score can be trusted, and how slow the slowest requests are. Those three questions, answered with the checkout numbers and two short scripts, cover most of the statistics this job asks for.

Here is the honest scope of what you need: you do not need a statistics degree for this job, and nobody will ask you to derive formulas by hand. Three practical tools cover about 90% of the statistics an AI engineer actually uses at work — and you have just built the first one.

1 — A/B tests over models and prompts. "Prompt v2 passed 41 of 50 evals, v1 passed 36 of 50 — do we ship v2?" is the SaaSify checkout question wearing different clothes. Same z-test, same traps, same sample-size arithmetic — only the nouns changed. Module 07 turns this into a daily working habit; the engine you just read is the core of it.

2 — Eval variance. The most common statistics mistake on AI teams today goes like this: score the new model on 20 examples, get 75%. The old model scored 70%. Declare the new model the winner, update the slide deck, move on. The next script shows why that 5-point "win" means nothing at all.

🧠 Brain power

Before reading on: a model's true pass rate is 70%. You evaluate it on 20 examples and report the score. How far off can that score plausibly be — within a couple of points? Five? Twenty?

Reveal the answer

Twenty points. On a 20-example eval, the same model — same true quality of 70%, nothing about it changing between runs — can plausibly score anywhere from about 50% to 90%, depending only on which examples happen to land in the set.

That means two models that differ by 5 points on a 20-example eval are effectively tied: the gap between them is smaller than the noise around each score. The simulation below proves it in eight lines.

Module 07 builds the habits that fix it — bigger eval sets, and an honest error bar attached to every score you report.

Here is the experiment the script runs. Imagine a model whose true quality is exactly 70% — meaning that if you could somehow test it on unlimited examples, it would pass exactly 70% of them.

Of course, in real life you never get unlimited examples; you get an eval set of some fixed size. So the script asks: if I test this one unchanging model on a 20-example eval, over and over in 10,000 parallel universes, what scores do I see?

Then it repeats the whole experiment with 100-example and 500-example evals, so you can watch what more data buys you.

Step-by-step: what eval_variance.py does, in plain English
  1. Create a random-number generator seeded with 7. The seed makes the "randomness" repeatable: every run of the script produces the same numbers, so you and I see the same output.
  2. Fix the model's true quality at 70% (TRUE_PASS_RATE) and decide to simulate 10,000 parallel universes (RUNS).
  3. For each eval size n — first 20, then 100, then 500: rng.binomial(n, 0.70, size=10_000) simulates 10,000 complete evals in one line. Each simulated eval flips n biased coins (each lands "pass" 70% of the time) and counts the passes. Dividing by n turns each count into a score, like 14/20 → 0.70.
  4. np.percentile(scores, [2.5, 97.5]) finds the two values that fence in the middle 95% of those 10,000 scores — the honest range of results the same model can produce. Print that range for each n.
  5. The last two lines flip to the real-world situation: you ran one actual eval and 14 of 20 passed. stats.binomtest(k=14, n=20).proportion_ci(...) computes the 95% confidence interval for the true quality behind that result — the printed answer being 46% to 88%, the error bar that belongs next to the "70%" score.
eval_variance.pyruns offline
# pip install numpy "scipy>=1.14,<2"
"""Why a 20-example eval is a coin flip -- a preview of Module 07."""
import numpy as np
from scipy import stats

rng = np.random.default_rng(7)
TRUE_PASS_RATE = 0.70     # the model's "real" quality, if you could measure it
RUNS = 10_000             # parallel universes, each running the same eval

for n in (20, 100, 500):
    scores = rng.binomial(n, TRUE_PASS_RATE, size=RUNS) / n
    lo, hi = np.percentile(scores, [2.5, 97.5])
    print(f"n={n:4d}  measured score ranges {lo:.0%} .. {hi:.0%}  "
          f"(same model, same true quality)")

# The honest error bar around ONE real eval run: 14/20 passed.
ci = stats.binomtest(k=14, n=20).proportion_ci(confidence_level=0.95)
print(f"\n14/20 passed -> '70%' score, 95% CI [{ci.low:.0%}, {ci.high:.0%}]")
# n=  20  measured score ranges 50% .. 90%
# n= 100  measured score ranges 61% .. 79%
# n= 500  measured score ranges 66% .. 74%
# 14/20 passed -> '70%' score, 95% CI [46%, 88%]

Now read the output line by line, and then see the three lines drawn on one axis in Fig. 1.3c below. With 20 examples, honest scores from one unchanging model spread from 50% all the way to 90% (marker 1). With 100 examples the spread narrows to 61–79%; with 500 it tightens to 66–74% (marker 2). More data means less room for luck — that is the entire lesson, printed as three lines. The final line then flips the situation around to the one you will actually face at work: you ran your eval once, 14 of 20 examples passed, and you reported "70%". The confidence interval answers the honest question — given only 20 examples, where could the true quality really be? — and the answer is: anywhere from 46% to 88%. That wide range is the error bar that belongs next to every eval score you ever report. A score without one is not a measurement; it is an anecdote.

true quality 70% (never changes) 1 n = 20 50% 90% n = 100 61% 79% 2 n = 500 66% 74% 3 real run: 14 of 20 46% 88% each shaded range: where 95 of 100 honest evals of the SAME model land the error bar that belongs next to the reported '70%' 25× the data (20 → 500) makes the range 5× narrower (40 pt → 8 pt), because the wobble shrinks with √n and √25 = 5
Fig. 1.3c — The three lines eval_variance.py printed, drawn on one axis. The model never changes; only the number of examples does, and the range of scores it can honestly produce shrinks with the square root of that number.
  1. Twenty examples. The same 70%-quality model scores anywhere from 50% to 90% depending only on which 20 examples were drawn. A 5-point 'win' over another model is invisible inside a 40-point range.
  2. Five hundred examples. The range is 66% to 74%, 8 points wide. Now a 10-point gap between two models means something. Going from 20 to 500 is 25 times the data for 5 times the precision, which is the √n in the formula the next pencil exercise uses.
  3. One real run. You will never see the 10,000 universes; you see one score, 14 of 20. The confidence interval turns that around: the true quality behind a 70% score on 20 examples could be anywhere from 46% to 88%. That range is the error bar that belongs next to every eval number you report.
Sharpen your pencil

The simulation drew 10,000 imaginary evals to produce those three ranges. A one-line formula predicts all three. The typical wobble of a measured pass rate is SE = √( p · (1 − p) / n ). The middle 95% of scores sits at p ± 1.96 · SE. With p = 0.70, fill in the rows.

p · (1 − p) = 0.70 × 0.300.2100, and it is the same for every n
n = 20: SE = √(0.2100 / 20)
n = 20: range = 0.70 ± 1.96 · SE
n = 100: SE
n = 100: range
n = 500: SE = √(0.2100 / 500)√0.00042 = 0.0205
n = 500: range

Symbol key: p is the true pass rate; n is the number of eval examples; SE (say "standard error") is the typical wobble; √ is the square root; · means multiply; ± means plus or minus, the wobble going both ways.

Check your answers
n = 20: SE√(0.2100 / 20) = √0.0105 = 0.1025
n = 20: range1.96 × 0.1025 = 0.2009, so 0.4991 to 0.9009: about 50% to 90%
n = 100: SE√(0.2100 / 100) = √0.0021 = 0.0458
n = 100: range1.96 × 0.0458 = 0.0898, so 0.6102 to 0.7898: about 61% to 79%
n = 500: SE0.0205
n = 500: range1.96 × 0.0205 = 0.0402, so 0.6598 to 0.7402: about 66% to 74%

Three matches, to the point. The simulation needed 10,000 imaginary evals; the formula got the same answers with one square root each. What the numbers mean: on 20 examples, two models whose true qualities are 70% and 75% can trade places on any given run, because 5 points is half a wobble.

Read the denominator once more. n sits under a square root, so going from 20 to 500 examples, 25 times the data, shrinks the wobble by only 5 times. Section 06 walks through this same formula, and the Flex-your-memory question at the end of the page asks you to run it once more for n = 50.

Questions you might be asking now

The script, Fig. 1.3c and the pencil exercise pack three new ideas into a few lines: a score that moves between runs, a standard error and a confidence interval. The four questions below slow each one down. Every answer uses the same five reruns of one prompt, small enough to check with a pencil.

The five reruns every answer below uses. One support-ticket prompt that never changes, with a true pass rate of 70%, scored five times on 20 tickets each by eval_reruns.py. Its random seed was picked because the five scores average exactly 70%, so the example is typical rather than dramatic.
RunTickets passedScoreDistance from the true 70%
114 of 2070%0 points
217 of 2085%+15 points
311 of 2055%−15 points
415 of 2075%+5 points
513 of 2065%−5 points
Why does the same prompt get a different score every time I rerun the eval? Show me with numbers.

Because a 20-ticket score is a count of 20 separate pass-or-fail results, and each one carries its own luck. The prompt in the table never changed, yet its five runs scored 70%, 85%, 55%, 75% and 65%. Even its most likely result, exactly 70%, comes up in only about one run in five.

Start with what one run is. The eval takes 20 tickets, runs the prompt on each one, and marks each answer pass or fail. The score is the number of passes divided by 20. Nothing in that recipe forces the passes to add up to 14, even for a prompt whose true quality is 70%.

The script eval_variance.py models each ticket as a biased coin that lands "pass" 70% of the time. In a real eval, two different things flip that coin:

The two sources of luck in an eval score
SourceWhat changes between runsAt SaaSify
Which tickets land in the setEach run samples a different 20 tickets from the queueA run that happens to draw more of the hard billing disputes scores lower
The model's own randomnessThe same ticket can pass on one call and fail on the next, because the model samples its wordsA borderline refund question is answered well on Monday and vaguely on Tuesday

How likely is a run to land exactly on the truth? For 14 passes out of 20, the chance takes three steps.

  1. Price one pattern. One particular order of 14 passes and 6 fails has chance 0.714 × 0.36 = 0.006782 × 0.000729 = 0.00000494. It is tiny because it fixes every single ticket's result.
  2. Count the patterns. There are 38,760 different ways to choose which 14 of the 20 tickets pass. Every one of them gives the same score.
  3. Multiply. 38,760 × 0.00000494 = 0.192. So 19.2% of runs score exactly 70%, and 80.8% do not.

The same arithmetic for every other count gives the bars in Fig. 1.3h. The 10,000 simulated runs of eval_variance.py agree with it: 1,821 of them landed on exactly 14 of 20.

FIVE RERUNS OF ONE PROMPT, 20 TICKETS EACH filled square = that ticket's answer passed run 1 14/20 = 70% run 2 17/20 = 85% run 3 11/20 = 55% run 4 15/20 = 75% run 5 13/20 = 65% 1 each square is one ticket: run 1 passed 14 of its 20 2 same prompt, same true 70%, yet scores from 55% to 85% HOW OFTEN EACH SCORE COMES UP out of 100 reruns of the same 70% prompt 40 45 50 55 60 65 70 75 80 85 90 95 100 score on 20 tickets (%) 3 exactly 70%: about 19 reruns in 100 4 95+ reruns in 100 score from 50% to 90%
Fig. 1.3h — The same prompt, rerun. Left: the five reruns from the table, one square per ticket. Right: how often each score comes up in 100 reruns, from the three-step arithmetic above applied to every count. Values from rerunning eval_reruns.py.
  1. One run. Twenty squares, one per ticket; a filled square passed. Run 1 passed 14, which happens to equal the true 70%. The prompt was not aiming at 70%: each square was its own 70% chance.
  2. Five reruns. The same prompt scored 70%, 85%, 55%, 75% and 65%. The filled squares fall differently each time, so the counts differ. The five average exactly 70%, but no single run is guaranteed to be near that.
  3. The most likely score. About 19 reruns in 100 land on exactly 14 of 20. That is the tallest bar, and it still misses four times out of five. Its neighbours, 65% and 75%, are almost as likely.
  4. The honest range. The bars from 50% to 90% hold at least 95 reruns in 100. That is the first line eval_variance.py printed, 50% to 90%, drawn as bars instead of a range.

Two honest limits. First, freezing the eval does not remove the luck; it hides it. Rerun the same 20 tickets, and a model that answers them identically gives the same score every time. That score is still one draw from the 50% to 90% range, and next week's real tickets will not match it.

Second, the two sources shrink in different ways. Rerunning the same tickets a few times shows how much comes from the model's own randomness. The luck of which tickets were drawn shrinks only with more tickets, which is what the second and third lines of eval_variance.py measured.

A score is a count of lucky and unlucky tickets. On 20 tickets, the same 70% prompt honestly lands anywhere from 50% to 90%, and exactly on 70% only one run in five.

What exactly is the "standard error", and how do I calculate it by hand?

The standard error is the typical distance between one run's score and the true quality. For a 20-ticket eval of a 70% prompt it is 0.1025, about 10 points. You can measure it from reruns, or predict it with one line of arithmetic before any rerun exists.

The name has two halves. "Standard" means typical, and "error" means distance from the truth. So the standard error answers one question: how far off is a score, usually? There are two ways to find it, and they should agree.

Way 1: measure it from the five reruns

This is the five-step recipe for any standard deviation, applied to the five scores in the table.

  1. Find the average. (0.70 + 0.85 + 0.55 + 0.75 + 0.65) ÷ 5 = 0.70.
  2. Measure each distance from it. 0, +0.15, −0.15, +0.05 and −0.05.
  3. Square each distance. 0, 0.0225, 0.0225, 0.0025 and 0.0025. Without squaring, +0.15 and −0.15 would cancel, as if no run had missed.
  4. Average the squares. (0 + 0.0225 + 0.0225 + 0.0025 + 0.0025) ÷ 5 = 0.0100. This middle number is called the variance.
  5. Take the square root. √0.0100 = 0.1000, or 10.0 points. The √ (square root) undoes the squaring and puts the answer back in score units.

The spread of a score across reruns is exactly what "standard error" names. Five reruns give only a rough estimate of it. Dividing by 4 instead of 5 in step D, as pandas' .std() does by default, gives 0.1118.

Way 2: predict it before running anything

Nobody reruns an eval 10,000 times. The pencil exercise used a formula instead: SE = √(p · (1 − p) / n). It gets the number from two facts: how coin-like one ticket is, and how many tickets there are. Here it is, built up one step at a time.

  1. Score one ticket. It is worth 1 when it passes, 70% of the time, and 0 when it fails, 30% of the time. Its average is 0.70.
  2. Measure the two distances. A pass sits +0.30 above that average; a fail sits −0.70 below it.
  3. Square and average them, weighted by how often each happens. 0.70 × 0.09 + 0.30 × 0.49 = 0.063 + 0.147 = 0.21. That is p · (1 − p) = 0.70 × 0.30, the top of the formula. Its root, 0.458, is one ticket's spread.
  4. Add up 20 independent tickets. Independent wobbles add as variances, so the count of passes has variance 20 × 0.21 = 4.2. That is a spread of √4.2 = 2.05 tickets.
  5. Turn the count into a score. The score is the count ÷ 20, so its spread is 2.05 ÷ 20 = 0.1025. In one line: √(0.21 ÷ 20) = √0.0105 = 0.1025.

Step D is the non-obvious one. Twenty tickets do not all get lucky in the same direction, so part of the luck cancels. The spread of the total grows only with √20, not with 20, and so the spread of the score shrinks by √20 = 4.47.

Three routes to the standard error of a 20-ticket score, from eval_reruns.py
RouteWorkingStandard error
The five reruns, by hand√ of the average squared distance0.1000
The formula√(0.70 × 0.30 ÷ 20)0.1025
eval_variance.py's 10,000 runsThe spread of all 10,000 scores0.1024

Two names in this answer are easy to swap, so here they are side by side.

Standard deviation against standard error, for the 70% prompt
Standard deviationStandard error
What it describesHow far one value sits from the average: one ticket, a 1 or a 0, sits 0.458 awayHow far a whole score sits from the truth: 0.1025 for 20 tickets
Formula here√(p · (1 − p))√(p · (1 − p) / n)
With more ticketsNo change: a ticket is still a 1 or a 0Shrinks by √n: 0.0458 at 100 tickets, 0.0205 at 500
1 WAY 1: MEASURE THE FIVE RERUNS average 70% +15 pt −15 pt +5 pt −5 pt 50% 55% run 3 65% run 5 70% run 1 75% run 4 85% run 2 90% 2 one standard error ≈ 10 points each side: 10.0 from these five, 10.25 from the formula 3 WAY 2: ONE TICKET'S SPREAD, DIVIDED BY THE SQUARE ROOT OF THE TICKET COUNT 1 ticket 0.458 20 tickets 0.1025 = 0.458 ÷ √20 = 0.458 ÷ 4.47 100 tickets 0.0458 = 0.458 ÷ √100 = 0.458 ÷ 10 500 tickets 0.0205 = 0.458 ÷ √500 = 0.458 ÷ 22.4 25 times the tickets (20 → 500) buys only 5 times less wobble, because √25 = 5
Fig. 1.3i — The standard error found two ways. Top: the five reruns' distances from their average, squared, averaged and rooted. Bottom: one ticket's spread divided by the square root of the number of tickets. Values from rerunning eval_reruns.py.
  1. The five distances. The scores 55, 65, 70, 75 and 85% sit −15, −5, 0, +5 and +15 points from their average of 70%. Squared, averaged and rooted, they give 10.0 points.
  2. One standard error. A typical 20-ticket score lands about 10 points from the truth. The five reruns say 10.0, the formula says 10.25, and eval_variance.py's 10,000 runs say 10.24. They agree because they measure the same wobble three ways.
  3. One ticket against many. A single ticket is a 1 or a 0, so its spread is large: 0.458. Averaging n tickets divides that by √n (the square root of n). At 20 tickets √20 = 4.47, and the spread falls to 0.1025.

The honest limit: the formula needs p, the true pass rate, and at work you never have it. You feed it the score instead, and on 20 tickets that stand-in can itself be 15 points off. The next question shows what that does to an error bar. The standard error also measures luck only; a set of tickets that is easier than the real queue is the last question.

The standard error is the spread of a score across reruns. For a pass rate it is √(p · (1 − p) / n): one ticket's spread, 0.458 here, divided by the square root of the number of tickets.

What is a confidence interval, and why did 14 of 20 give 46% to 88% when the formula gives 50% to 90%?

A confidence interval is the range of true pass rates that could believably have produced the one score you got. For 14 of 20, the quick formula gives 49.9% to 90.1% and the exact method in eval_variance.py gives 45.7% to 88.1%. On 20 tickets, report the exact one.

Fig. 1.3c drew both kinds of range, and they answer opposite questions. Its first three lines start from a known truth, 70%, and ask where scores land. A confidence interval starts from one score and asks where the truth could be. At work you are always in the second situation: you have a score and no truth.

The quick recipe, by hand

  1. Take the score. 14 ÷ 20 = 0.70.
  2. Estimate the standard error from the score. The truth is unknown, so the score stands in for p: √(0.70 × 0.30 ÷ 20) = 0.1025.
  3. Multiply by 1.96. 1.96 × 0.1025 = 0.201. On a bell-shaped wobble, 95% of results land within 1.96 standard errors of the centre. That is the only reason for 1.96.
  4. Go that far each way. 0.70 − 0.201 = 0.499 and 0.70 + 0.201 = 0.901: 49.9% to 90.1%.

Step B is the weak point. It puts the score in place of the unknown truth, and on 20 tickets the score itself can be 15 points off. Run 2 shows the damage: 17 of 20 gives 85% ± (plus or minus) 15.6 points, which is 69.4% to 100.6%.

A pass rate above 100% is impossible. The recipe is stretching a symmetric bell over a wobble that is squeezed against the ceiling.

The exact method: test every candidate truth

The binomtest function in scipy takes a more honest route. It tries candidate true rates one at a time and asks two questions of each. How often would a prompt this good score 14 or more? How often 14 or fewer? A candidate stays inside the interval while both chances are at least 2.5%.

Candidate true rates for a score of 14 out of 20, checked by eval_reruns.py
Candidate true rateChance of 14 or more passesChance of 14 or fewer passesBelievable?
40.0%0.0060.998No: 14 or more passes would happen 6 times in 1,000
45.7%0.0250.992The lower edge
55.0%0.1300.945Yes
70.0%0.6080.584Yes
80.0%0.9130.196Yes
88.1%0.9940.025The upper edge
95.0%1.0000.000No: it would almost never score as low as 14

The two 2.5% edges add up to the 5% that "95%" leaves out. The interval is not centred on 70%, because a pass rate cannot go past 100%. Near the ceiling there is less room to wobble, so the upper edge sits 18.1 points above the score and the lower edge 24.3 points below it.

Both recipes on the five reruns from the table. Every one of the ten intervals contains the true 70%.
RunScoreQuick formulaExact method
114 of 20, 70%49.9% to 90.1%45.7% to 88.1%
217 of 20, 85%69.4% to 100.6%62.1% to 96.8%
311 of 20, 55%33.2% to 76.8%31.5% to 76.9%
415 of 20, 75%56.0% to 94.0%50.9% to 91.3%
513 of 20, 65%44.1% to 85.9%40.8% to 84.6%
1 ONE SCORE, 14 OF 20: WHICH TRUE RATES COULD HAVE PRODUCED IT? quick formula 49.9% to 90.1% exact method 45.7% to 88.1% edge: 2.5% edge: 2.5% 2 40%: 14 or more passes 6 times in 1,000 95%: 14 or fewer, 0 in 1,000 3 FIVE RERUNS: THIN LINE = QUICK FORMULA, THICK BAR = EXACT METHOD true 70% run 1 · 70% run 2 · 85% 4 100.6% run 3 · 55% run 4 · 75% run 5 · 65% 30% 50% 70% 90% 100% over every possible rerun, the quick recipe catches 70% in 94.7% of them, the exact method in 97.5%
Fig. 1.3j — Confidence intervals on one axis. Top: run 1's score of 14 of 20 with the quick and exact intervals, and two true rates the score rules out. Bottom: both intervals for all five reruns, against the true 70%. Values from rerunning eval_reruns.py.
  1. Two intervals for one score. Run 1 scored 70%. The quick formula reaches 20.1 points each way: 49.9% to 90.1%. The exact method tests candidate true rates and gets 45.7% to 88.1%, pulled down because nothing can pass more than 100%.
  2. Ruled out. A 40% prompt reaches 14 or more passes only 6 times in 1,000, and a 95% prompt almost never scores as low as 14. Neither can believably be the truth behind this score. The edges, 45.7% and 88.1%, are where that chance is exactly 2.5%.
  3. Five reruns, five pairs. Each interval is built around its own score, so the pairs move around. All ten cross the dashed true 70%. A recipe is judged by how often its moving intervals catch the one fixed truth.
  4. Past 100%. Run 2's quick interval ends at 100.6%, an impossible pass rate. Over every possible rerun, the quick recipe catches 70% in 94.7% of them, short of its promise. The exact method catches it in 97.5%.

What the 95% promises

The 95% belongs to the recipe, not to any one interval. Rerun the eval forever, build an interval each time, and a 95% recipe should catch the true 70% in 95 runs out of 100. Any single interval either contains 70% or it does not.

The script eval_reruns.py checks both recipes against every possible count from 0 to 20, weighted by the chances behind Fig. 1.3h. The quick formula catches 70% whenever the count is 10 to 17: 94.7% of reruns, just short of its promise. The exact method catches it for counts 10 to 18: 97.5% of reruns.

The honest limit: an interval covers only the luck of which tickets came up and how the model sampled. If the 20 tickets are not like the real queue, the interval can be exact, narrow and still wrong. That is the next question.

A confidence interval runs backwards, from one score to the true rates that could have produced it. On 20 tickets use the exact method, 46% to 88% for 14 passes, and remember that the 95% describes the recipe, not this one range.

Is variance the same thing as bias?

No. Variance is how far reruns scatter around the eval's own centre; bias is how far that centre sits from the true quality. Going from 20 to 500 tickets narrows the scatter from 40 points to 8. It does nothing to a 20-point bias.

A bathroom scale shows the difference. One scale reads a kilogram high this morning and a kilogram low tomorrow. That is variance, and weighing yourself ten times and averaging fixes it. Another scale always reads two kilograms heavy. That is bias: weigh yourself a thousand times and it is still two kilograms heavy, now with great confidence.

Now the SaaSify version. The real ticket queue is half billing disputes and half feature requests. The prompt passes 50% of billing disputes and 90% of feature requests, so its true quality is 0.5 × 50% + 0.5 × 90% = 70%. Suppose the eval set was pulled with a query that kept only feature requests, because those had clean reference answers.

The same 70% prompt scored on two eval sets, 10,000 reruns per row, from bias_vs_variance.py
Eval setTicketsCentre of the rerunsWhere 95% of reruns landSpread (standard error)Bias
Whole queue2070.2%50% to 90%0.102+0.2 points
Whole queue50070.0%66% to 74%0.0200.0 points
Feature requests only2089.9%75% to 100%0.067+19.9 points
Feature requests only50090.0%87% to 93%0.014+20.0 points

Read the first two rows. Twenty-five times the tickets cut the spread five-fold, and the centre stayed on 70%; the +0.2 is leftover luck from 10,000 reruns. Now read the last two. The same 25 times cut the spread from 0.067 to 0.014, and the centre stayed 20 points too high. More data bought precision, aimed at the wrong number.

The feature-only spread is smaller even at 20 tickets. A 90% ticket is less coin-like than a 70% one: p · (1 − p) is 0.09 instead of 0.21. A biased eval can look steadier than an honest one.

In pencil-sized form: the five reruns in the table above average 70%. Five reruns of the feature-only set, drawn with the same random numbers, scored 90%, 95%, 65%, 95% and 90%. They average 87%. Their scatter is plain to see in the list; their aim error is visible in none of them.

Variance and bias side by side
VarianceBias
What it isScatter of reruns around their own centreDistance from that centre to the true quality
Where it comes fromLuck: which tickets came up, and the model's own randomnessHow the eval was built: the wrong mix of tickets, or a lenient grader
Fixed by more tickets?Yes, it shrinks with √n (the square root of the ticket count)No
Shown by the standard error and the interval?Yes: it is all they measureNo: they are blind to it
How you find itRerun, or use the formulaCompare the eval set with the real queue
WHERE 95% OF 10,000 RERUNS LAND, FOR TWO EVAL SETS true quality 70% 1 whole queue, 20 50% 90% whole queue, 500 66% 74% 25× the tickets: 40-point range → 8 2 bias: +20 points feature only, 20 75% 100% 3 feature only, 500 87% 93% 450 of 500: interval 87.0–92.5%, misses 70% 40% 50% 60% 70% 80% 90% 100%
Fig. 1.3k — Variance and bias on one axis. Each bar is where 95% of 10,000 reruns land. More tickets narrow every bar; only changing which tickets are in the set moves a bar's centre back to the true 70%. Values from rerunning bias_vs_variance.py.
  1. Variance shrinks. From the whole queue, 20 tickets land anywhere from 50% to 90% and 500 tickets from 66% to 74%. Both bars are centred on the true 70%. This is the part of Fig. 1.3c that more data fixes.
  2. Bias does not. From feature requests only, both bars are centred on 90%. The 20-point gap to the dashed truth is the same at 20 tickets and at 500. No number of extra feature requests brings billing disputes into the score.
  3. Narrow and wrong. At 500 feature-only tickets the bar is 87% to 93%. The exact interval from one typical run, 450 of 500, is 87.0% to 92.5%. It looks precise and never comes near 70%, and the standard error cannot warn you, because it measures only scatter.

The worst case is the fourth row with an interval attached. A typical 500-ticket run of the feature-only set passes 450: a score of 90%, with an exact 95% interval of 87.0% to 92.5%. The interval is narrow, correctly computed, and nowhere near the true 70%.

The honest limit: nothing on this page detects bias from the scores alone. You find it by comparing how the set was built with what production sees. Count tickets per issue_type with the level-2 GROUP BY from Fig. 1.1e, once on the eval set and once on last month's queue, and look for shares that do not match.

Once each ticket type is scored separately, you can reweight by the real mix. Here that is 0.5 × the billing score + 0.5 × the feature score = 0.5 × 0.50 + 0.5 × 0.90 = 0.70. That fix needs billing tickets in the set. If the query never pulled any, no weighting can invent them.

Variance is scatter, and it shrinks with more tickets. Bias is aim, and it changes only when you change which tickets you pick. A small error bar says nothing about the aim.

3 — Percentiles for latency. A percentile is a simple idea once you picture it: line up every request your system served, sorted from fastest to slowest, and read off values at chosen positions along that line.

p50 is the value at the halfway point — the typical request, also called the median: half of all requests were faster, half were slower. p95 is the time that 95% of requests beat — only the slowest 1 in 20 took longer.

p99 is what the slowest 1 in 100 experience.

0 1,000 2,000 3,000 ms 1 p50 = 800 ms · half faster, half slower 2 p95 = 2,146 ms · 1 in 20 is slower 3 p99 = 3,231 ms · the 1 in 100 100,000 requests sorted fastest → slowest; each bar is one twentieth of them (5,000 requests) at its middle value
Fig. 1.3d — A percentile is a position in the sorted line-up. The bar heights are the twentieth-by-twentieth middle values of the lognormal times the script draws (computed for this figure); p50, p95 and p99 are the script's own printed numbers.
  1. p50, the median. Walk halfway along the sorted line-up and read the time: 800 ms. Half of all requests were faster than this, half slower. It is what a typical user feels.
  2. p95. Walk 95% of the way along. Only the last twentieth, one request in twenty, is slower than 2,146 ms. Service targets are written against this position because it describes a bad-but-common experience.
  3. p99. The last hundredth starts at 3,231 ms and keeps rising off the chart. One request in a hundred lives here, and at ten thousand requests a day that is a hundred users a day. This is the number in 'reduce p99 latency' job postings.

LLM systems are judged on those slow tails, the last bars at markers 2 and 3 of Fig. 1.3d, and the familiar average (the mean) actively hides them: most calls are quick, but a small number — long generations, retries, cold caches — are very slow, and averaging smears them invisible.

That is why production targets (called SLOs, service-level objectives) are written as "p95 under 2 seconds", never as "average under 1 second".

Step-by-step: what latency_percentiles.py does, in plain English
  1. Create a seeded random generator (same reason as before: repeatable output).
  2. Invent 100,000 request times with rng.lognormal(...) * 800. A lognormal distribution has exactly the shape real LLM latency has, the shape of the bars in Fig. 1.3d: a big cluster of fast requests and a long, thin tail of slow ones (long generations, retries, cold caches). Multiplying by 800 scales the numbers into realistic milliseconds.
  3. Compute the plain average of all 100,000 times — the number a naive dashboard would show.
  4. np.percentile(latencies_ms, [50, 95, 99]) sorts the times from fastest to slowest and reads off three positions: the halfway point (p50 — the typical request), the value 95% of requests beat (p95), and the value 99% beat (p99 — what the unluckiest 1 in 100 users experience).
  5. Print all four numbers, each labeled with who it describes — and notice the mean sits far from the p99 that actually hurts users.
latency_percentiles.pyruns offline
# pip install numpy
"""Latency is a distribution, not a number. LLM latency doubly so."""
import numpy as np

rng = np.random.default_rng(0)
# Lognormal: most calls fast, a heavy tail of slow ones -- the classic
# shape of LLM completion times (long generations, retries, cold caches).
latencies_ms = rng.lognormal(mean=0.0, sigma=0.6, size=100_000) * 800

mean = latencies_ms.mean()
p50, p95, p99 = np.percentile(latencies_ms, [50, 95, 99])
print(f"mean {mean:6.0f} ms   <- what the naive dashboard shows")
print(f"p50  {p50:6.0f} ms   <- the typical user")
print(f"p95  {p95:6.0f} ms   <- 1 in 20 requests is worse than this")
print(f"p99  {p99:6.0f} ms   <- what your angriest users screenshot")
# mean    958 ms / p50 800 ms / p95 ~2146 ms / p99 ~3231 ms
0 ms 2,000 ms 3,000 ms 1 median p50 = 800 ms 2 mean = 958 ms, dragged 158 ms right of the median p95 p99 3 the slow end: p95 2,146 ms to p99 3,231 ms and beyond shaded on the axis: the middle half of all requests, 534 to 1,198 ms
Fig. 1.3e — Mean against median on the script's own numbers. Half of all requests finish by 800 ms, yet the average is 958 ms, because the few very slow requests at the far right pull it up. The middle-half band (534 to 1,198 ms) is computed for this figure from the same lognormal.
  1. The median. Sort every request and take the middle one: 800 ms. Adding a handful of 10-second requests would not move it, because they are still just 'slower than the middle'.
  2. The mean. Add every time and divide by the count: 958 ms. The slow end counts in full, so the average sits 158 ms to the right of what a typical user feels, and it still says nothing about how bad the worst cases are. Both facts make it the wrong dashboard number.
  3. The slow end. From p95 at 2,146 ms out to p99 at 3,231 ms and further. One request in twenty lands in this stretch, one in a hundred beyond its right end. This is the part of the picture that times out a tool call and gets screenshotted.

Look at what the average hides, with Fig. 1.3e in view. The mean (~958 ms, marker 2) sounds perfectly respectable on a dashboard, yet it tells you nothing about the 1-in-100 request that takes 3.2 seconds — the request that times out your agent's tool call in Module 09, and the one an angry user screenshots and posts in the company Slack. Notice also that the mean sits above the median (marker 1): the slow tail at marker 3 of Fig. 1.3e drags it upward, so the "average" is slower than what a typical user actually experiences, while still hiding the worst cases. When a job posting says "reduce p99 latency", this is the vocabulary it is written in — and now you can read it.

05 · The precision lathePython — The 2026 Professional Setup

The queries and the A/B test now exist as files on one laptop. Diana's dashboard has to run every night, and the test engine has to be something a teammate can run and trust without a walkthrough. The team needs the same environment on every machine, a contract on every row that enters the code, and a way to call a model for thousands of support tickets without waiting on them one at a time. Those are the four upgrades in this section.

You already write Python. This section is about writing it the way senior AI teams do in August 2026.

That matters commercially: "Python (async, production-grade)" is the single most demanded skill in the market research, appearing in 91–96% of agentic-AI postings.

Four upgrades:

uv — your package.json moment

The first thing a teammate does with the dashboard code is install it, and with pip and a requirements file two installs a week apart can pull different versions. SaaSify's nightly job cannot depend on which day it was installed. The team needs one manifest and one lockfile, committed, so that every machine gets the same versions bit for bit. That is uv, and it is the scaffold every later lab lives in.

The pip-plus-requirements.txt workflow you may remember from older Python is this course's first deprecation radar entry: no lockfile, no environment isolation by default, glacial resolution. uv (from Astral, the Ruff people) is the 2026 default in new repos: one Rust binary that replaces pip, virtualenv, pyenv, and poetry — and resolves in milliseconds. If you know npm, you already know it: pyproject.toml is your package.json, uv.lock is your lockfile, uv run is your npx.

Step-by-step: what these shell commands do, in plain English
  1. Line 1 downloads uv's install script and runs it — a one-time setup, like installing Node before your first JavaScript project.
  2. uv init ai-course --python 3.12 creates a new project folder named ai-course with a pyproject.toml inside, pinned to Python 3.12. This is the npm init moment.
  3. uv add ... installs five libraries into the project's own private environment and records each one — with its allowed version range — in pyproject.toml, while uv.lock records the exact versions installed. The quoted ranges like "duckdb>=1.3,<2" mean "at least version 1.3, but stay below 2.0" so a future breaking release can't sneak in.
  4. uv add --dev mypy ruff pytest installs tools you need while developing (type checker, linter, test runner) but that the shipped project itself does not depend on — the devDependencies idea.
  5. uv run python -c "..." runs a tiny one-line check inside the project's environment, printing the installed versions. No "activate the virtualenv" dance — uv run handles that every time.
shell — course scaffoldruns offline
# Install uv once (Linux/macOS; Windows installer at docs.astral.sh/uv)
curl -LsSf https://astral.sh/uv/install.sh | sh

# One scaffold for the whole course -- every lab from here on lives inside it
uv init ai-course --python 3.12
cd ai-course
uv add pandas "duckdb>=1.3,<2" "pydantic>=2.7,<3" "scipy>=1.14,<2" httpx
uv add --dev mypy ruff pytest

# uv run executes inside the project venv -- no 'activate' dance, ever
uv run python -c "import duckdb, pydantic; print(duckdb.__version__, pydantic.VERSION)"
1 pyproject.toml: WHAT YOU ASKED FOR pandas ≥ 2.2 duckdb ≥ 1.3 and below 2 pydantic ≥ 2.7 and below 3 scipy ≥ 1.14 and below 2 httpx ≥ 0.27 allowed ranges, written by hand uv add 2 uv.lock: WHAT WAS ACTUALLY INSTALLED pandas == one exact version duckdb == one exact version pydantic == one exact version … every transitive package too each with a checksum generated, committed next to the manifest uv sync 3 THE SAME BITS EVERYWHERE your laptop a teammate's laptop CI, and the nightly job no more 'works on my machine'
Fig. 1.3f — What the two committed files do. The manifest says what you asked for, in ranges; the lockfile records exactly what was resolved, down to every transitive package; uv sync reproduces that exact set on any machine.
  1. The manifest. pyproject.toml holds the ranges you typed, such as duckdb at least 1.3 and below 2. Ranges are for humans: they say what you are willing to accept, not what you got.
  2. The lockfile. uv.lock pins every package, including the ones you never named, to one exact version with a checksum. It is generated, never edited by hand, and it is committed. This is the package-lock.json idea.
  3. Identical installs. uv sync reads the lockfile and installs that exact set. Your laptop, a teammate's, and the CI runner for Diana's nightly job end up bit for bit the same, which is what 'reproducible' means in the interview question at the end of this page.

Commit pyproject.toml and uv.lock, markers 1 and 2 of Fig. 1.3f; a teammate (or CI) runs uv sync and gets your environment bit-for-bit (marker 3). Here's the manifest the scaffold produces, plus the tool config we'll hold every lab to:

Step-by-step: what each part of pyproject.toml declares, in plain English
  1. [project] — the project's identity: its name, its version, and "this needs Python 3.12 or newer to run".
  2. dependencies — the libraries the project needs, each with an allowed version range. "pandas>=2.2" reads "version 2.2 or newer"; "duckdb>=1.3,<2" reads "at least 1.3 but below 2.0", fencing out a future major release that could break things.
  3. [dependency-groups] dev — tools used only while developing (type checker, linter, test runner); they are not part of what the project ships.
  4. [tool.mypy] strict = true — run the mypy type checker in its strictest mode, so missing or wrong type hints are errors, not suggestions.
  5. The [[tool.mypy.overrides]] block is one targeted exception: the duckdb package publishes no type information, so mypy is told not to complain about importing it.
pyproject.toml
[project]
name = "ai-course"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
    "pandas>=2.2",
    "duckdb>=1.3,<2",
    "pydantic>=2.7,<3",
    "scipy>=1.14,<2",
    "httpx>=0.27",
]

[dependency-groups]
dev = ["mypy>=1.11", "ruff>=0.6", "pytest>=8.3"]

[tool.mypy]
strict = true                # type hints are the norm, not the garnish

[[tool.mypy.overrides]]
module = ["duckdb", "duckdb.*"]
ignore_missing_imports = true

And the directory layout — memorize it, because every lab in this course drops into it unchanged:

layout — the course scaffold
ai-course/
  pyproject.toml        # deps + tool config, committed
  uv.lock               # exact pins, committed (your package-lock.json)
  data/                 # generated inputs and outputs, gitignored
  notebooks/            # exploration only -- nothing imports from here
  labs/
    __init__.py
    lab01/
      __init__.py
      config.py
      generate_messy_csv.py
      quality_report.py
  tests/
    test_lab01.py

Note the wall between notebooks/ and labs/. Notebooks are a superb thinking surface and a terrible shipping surface — hidden execution-order state, no diffs worth reviewing, no type-checking. The professional rhythm is: explore in a notebook, then promote anything worth keeping into a typed module under labs/ that a test can import. "A Jupyter notebook with model.predict() tells them nothing," as the portfolio research bluntly puts it.

Decision table: notebook vs. script/module
OptionChoose whenAvoid whenTypical cost
NotebookExploring data, plotting, one-off analysis, teaching yourself an APIAnything imported, scheduled, reviewed, or shippedHidden state; unreviewable diffs
Typed module + CLIAnything run twice, by CI, or by a teammateThrowaway exploration — ceremony slows thinkingA few minutes of structure up front

Pydantic v2 — TypeScript interfaces for your data boundaries

The rows that feed Diana's dashboard arrive as text: "120.00" for a charge, 1 for churn, "2025-01-15" for a date, and one day a charge of −5 will arrive too. SQL gave us the rows; nothing has yet checked them. The team needs a contract at the boundary that turns clean text into typed values and rejects the −5 with a readable error, and the same contract will later wrap every answer a language model sends back.

Type hints check what's inside your program; Pydantic checks what enters it. A Pydantic model is a class that parses, coerces, and validates raw data at runtime — a TypeScript interface that actually enforces itself.

Learn it now, deeply, because in Act III it is everywhere: LLM structured outputs (Module 06's client.messages.parse(..., output_format=YourModel) hands a Pydantic class to Claude and returns a validated instance), FastAPI request bodies, agent tool schemas, MCP servers.

The contract you define here survives the network hop into the model and back.

Step-by-step: what subscription_contract.py does, in plain English
  1. Define a class Subscription that inherits from Pydantic's BaseModel. Each line inside states a field's name, its type, and its rules: customer_id must match the pattern "a C followed by digits" (that r"^C\d+$" is a regular expression saying exactly that); monthly_charges must be greater than 0 and less than 10,000 (gt/lt = greater-than / less-than); contract_type may only be one of the three exact strings listed in Literal[...]; churn must be a true/false value.
  2. The @field_validator("signup_date") function adds a rule the field types can't express — a business rule: if the signup date is later than today, reject it with a clear error message. Otherwise pass the value through unchanged.
  3. Build a raw dictionary that imitates messy data arriving from outside: the charge is a string ("120.00"), churn is a number (1), the date is text.
  4. Subscription.model_validate(raw) is the checkpoint: it checks every rule and coerces what it reasonably can — "120.00" becomes the number 120.0, 1 becomes True, the date string becomes a real date. Out comes a clean, typed object.
  5. model_dump_json() serializes that validated object back to tidy JSON, and we print it.
  6. Finally, deliberately feed it bad data — a charge of −5. Pydantic raises a ValidationError; the except block catches it and prints the machine-readable description of what failed: which field, which rule, what it got ("Input should be greater than 0").
subscription_contract.pyruns offline
# pip install "pydantic>=2.7,<3"
"""Pydantic v2 in one screen -- the data-contract layer of every Act III system."""
from datetime import date
from typing import Literal

from pydantic import BaseModel, Field, ValidationError, field_validator


class Subscription(BaseModel):
    """One row of Diana's table, as a contract instead of a hope."""
    customer_id: str = Field(pattern=r"^C\d+$")
    signup_date: date
    monthly_charges: float = Field(gt=0, lt=10_000)
    contract_type: Literal["Month-to-Month", "One-Year", "Two-Year"]
    churn: bool

    @field_validator("signup_date")
    @classmethod
    def not_in_the_future(cls, v: date) -> date:
        # Field constraints handle shape; validators handle business rules.
        if v > date.today():
            raise ValueError("signup_date is in the future")
        return v


raw = {"customer_id": "C101", "signup_date": "2025-01-15",
       "monthly_charges": "120.00", "contract_type": "Month-to-Month", "churn": 1}

sub = Subscription.model_validate(raw)   # coerces "120.00" -> 120.0, 1 -> True
print(sub.model_dump_json())

try:
    Subscription.model_validate({**raw, "monthly_charges": -5})
except ValidationError as e:
    # Machine-readable errors: which field, which rule, what it got.
    print(e.errors()[0]["msg"])          # "Input should be greater than 0"
1 RAW, AS IT ARRIVES "customer_id": "C101" "signup_date": "2025-01-15" (text) "monthly_charges": "120.00" (text) "contract_type": "Month-to-Month" "churn": 1 (a number) model_validate 2 TYPED, CHECKED, OR REJECTED customer_id = "C101" ✓ matches the pattern C + digits signup_date = date(2025, 1, 15) text → date, not in the future ✓ monthly_charges = 120.0 text → float, above 0, below 10,000 ✓ contract_type = "Month-to-Month" ✓ one of three allowed values churn = True 1 → bool 3 THE SAME ROW WITH monthly_charges = −5 "monthly_charges": -5 model_validate ValidationError: "Input should be greater than 0", naming the field
Fig. 1.3g — The boundary subscription_contract.py draws. Text goes in; typed values come out, each checked against its declared rule; a value that breaks a rule is rejected with a message naming the field, the rule and the offending value.
  1. Raw input. The row as it arrives from a CSV, a form or an API: numbers stored as text, a date as text, a boolean as the number 1. This is what every boundary in Act III looks like before checking.
  2. Coerced and checked. model_validate converts what it reasonably can ('120.00' to 120.0, 1 to True, the text to a date) and tests every declared rule. Out comes an object whose types you can trust for the rest of the program.
  3. Rejected. A charge of −5 breaks the gt=0 rule, so nothing comes out except a ValidationError whose message says exactly which field failed which rule. The −5 never reaches the dashboard, and the error is machine-readable, which is what an LLM structured-output loop will rely on in Module 06.

Two v2 habits to lock in (the v1 names still haunt old blog posts): model_validate / model_dump_json, not parse_obj / json(); and constraints declared in Field(...) rather than ad-hoc if statements — declared constraints are visible in the JSON schema Pydantic generates, which is precisely what LLM structured outputs consume in Module 06.

async/await — because LLM apps are professional waiters

SaaSify's support queue holds 5,000 tickets, and Diana's next ask is a one-line summary of each, written by a model. One model call is about 1.2 seconds of waiting, so calling them one after another is 100 minutes. The team needs the waiting to overlap, which is what async gives, with a cap so the API's rate limit is respected.

An LLM API call is ~1.2 seconds of network waiting wrapped around ~0 seconds of your CPU's time. A synchronous backend handling ten such calls spends 12 seconds doing nothing, sequentially. Python's asyncio is the same trick as Node's event loop, which you already trust: at every await, the loop parks the current task and runs another. One process, hundreds of in-flight LLM calls.

sync one worker call 1 call 2 call 3 call 4 call 5 wall clock = 6.0 s (each call waits for the previous one's network) async one event loop call 1 call 2 call 3 call 4 call 5 all five wait on the network at once wall clock ≈ 1.2 s 0 s 1.2 s 6.0 s 1 2
Fig. 1.4 — Five 1.2-second LLM calls: sequentially they cost 6.0 s of wall clock; overlapped on one event loop they cost ~1.2 s, because the waiting happens concurrently.
  1. One after another. Each call waits 1.2 s for the network, and call 2 cannot start until call 1 returns. Five calls, 5 × 1.2 = 6.0 s, and the CPU did nothing the whole time.
  2. All at once. At each await the event loop parks the waiting call and starts the next one, so all five waits overlap. Wall clock is one wait, about 1.2 s. Nothing ran faster; the waiting simply stopped being sequential.
Step-by-step: what sync_vs_async.py does, in plain English
  1. fake_llm_call stands in for a real LLM request: await asyncio.sleep(1.2) waits 1.2 seconds without using the CPU — exactly what a network call feels like from the program's side — then returns a fake summary. The async def keyword marks it as a pausable function: at each await, the event loop may set it aside and run something else.
  2. sequential calls it in an ordinary loop, awaiting one call at a time — call 2 does not begin until call 1 has fully finished. Five calls therefore cost 5 × 1.2 = 6 seconds.
  3. concurrent first creates asyncio.Semaphore(50) — think of a ticket booth holding 50 tickets. Each call must take a ticket before it runs and returns it after; at most 50 calls are ever in flight at once. Real APIs enforce rate limits, so capping your fan-out like this is a habit, not an optimization.
  4. The inner helper bounded is the take-a-ticket wrapper: acquire the semaphore (async with sem), make the call, release automatically.
  5. asyncio.gather(*) launches all five wrapped calls at once and waits until every one has finished. All five sleeps overlap, so the total is ~1.2 seconds, not 6.
  6. The loop at the bottom times both versions with a stopwatch. asyncio.run(...) is the ignition key that starts the event loop and runs an async function to completion. The printed result is the whole argument: 6.0 s sequential versus 1.2 s concurrent.
sync_vs_async.pyruns offline
# stdlib only -- run it and watch the wall clock
"""An LLM call is ~1.2 s of waiting and ~0 s of CPU. Overlap the waiting."""
import asyncio
import time


async def fake_llm_call(i: int) -> str:
    await asyncio.sleep(1.2)          # stand-in for network + token generation
    return f"summary-{i}"


async def sequential(n: int) -> None:
    for i in range(n):
        await fake_llm_call(i)        # awaited one at a time: no overlap


async def concurrent(n: int, limit: int = 50) -> None:
    # Real APIs have rate limits -- ALWAYS cap fan-out with a semaphore.
    sem = asyncio.Semaphore(limit)

    async def bounded(i: int) -> str:
        async with sem:
            return await fake_llm_call(i)

    await asyncio.gather(*(bounded(i) for i in range(n)))


for name, factory in [("sequential", sequential), ("concurrent", concurrent)]:
    t0 = time.perf_counter()
    asyncio.run(factory(5))
    print(f"{name:10s} 5 calls: {time.perf_counter() - t0:4.1f} s")
# sequential 5 calls:  6.0 s
# concurrent 5 calls:  1.2 s
Failure mode

Scale the toy numbers to a real job and the sync version stops being slow and starts being impossible: summarizing 5,000 support tickets at 1.2 s per LLM call is 100 minutes sequential — versus about 2 minutes with a concurrency cap of 50. This is why async fluency is a screening question for LLM backend roles: a sync-only design doesn't just have worse p99, it can't do the batch work the product needs at all.

1 5,000 TICKETS, 1.2 s EACH, ONE AFTER ANOTHER 5,000 × 1.2 s = 6,000 s = 100 minutes 2 THE SAME 5,000 WITH A CAP OF 50 IN FLIGHT 5,000 ÷ 50 = 100 rounds × 1.2 s = 120 s = 2 minutes (drawn to scale: 1/50th of the one above) 3 WHY IT WORKS: WAITING CAN OVERLAP, COMPUTING CANNOT five network waits stacked: 1.2 s total, the event loop switches while each one waits five CPU jobs (tokenizing, say) chained: 5× the time, nothing to switch to while one runs async for IO (LLM calls, databases, vector search); separate processes for CPU (tokenizing, reranking, parsing)
Fig. 1.4b — The failure-mode numbers drawn to scale, and the reason behind them. Overlap only helps when the tasks are waiting; a CPU-bound loop has nothing to overlap, so the same gather() would buy nothing there.
  1. Sequential. 5,000 tickets at 1.2 s each is 100 minutes of a worker holding one connection open at a time. Not slow: unusable for a nightly job that also has to finish the dashboard.
  2. Capped concurrency. A semaphore of 50 lets 50 calls wait at once, so the batch takes 100 rounds of 1.2 s, about 2 minutes. The cap is there because real APIs rate-limit; it is a habit, not an optimisation.
  3. Waiting against computing. The event loop is one thread taking turns. It wins when tasks wait, because a wait is when it switches to the next task. A CPU-bound job never yields, so five of them still run one after another; more cores need separate processes.

Same pattern against a real HTTP endpoint — Ollama's OpenAI-compatible server, so the code shape is identical to any hosted API you'll meet in Act III:

Step-by-step: what concurrent_summaries.py does, in plain English
  1. Read the server address and model name from environment variables, falling back to a local Ollama server (http://localhost:11434/v1) and the llama3.2 model — so the script runs with no API key at all.
  2. summarize sends one POST request to the server's /chat/completions endpoint, asking the model for a one-line summary of one ticket. Because the request is awaited, the event loop is free to run the other summarize calls while this one waits for the network.
  3. resp.raise_for_status() makes failure loud: if the server answered with an error code, stop here instead of quietly parsing garbage.
  4. Dig the summary text out of the JSON reply (choices[0].message.content — the standard OpenAI-compatible response shape you will see all through Act III).
  5. main defines three example tickets, then opens one httpx.AsyncClient shared by all calls — one client means reused network connections, which is faster and kinder to the server than opening a fresh one per request.
  6. asyncio.gather(*) fires all three summaries simultaneously and collects the results in order; the loop prints each one. asyncio.run(main()) starts the whole thing.
concurrent_summaries.pyruns offline · needs local Ollama
# pip install "httpx>=0.27,<1"
# Local model, no API key:  ollama pull llama3.2  &&  ollama serve
"""Concurrent calls against a real LLM HTTP endpoint (Ollama, OpenAI-compatible)."""
import asyncio
import os

import httpx

BASE_URL = os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1")
MODEL = os.environ.get("LLM_MODEL", "llama3.2")


async def summarize(client: httpx.AsyncClient, ticket: str) -> str:
    resp = await client.post(                     # the loop runs other calls
        f"{BASE_URL}/chat/completions",           # while this one awaits
        json={
            "model": MODEL,
            "messages": [{"role": "user",
                          "content": f"One-line summary: {ticket}"}],
        },
        timeout=60.0,
    )
    resp.raise_for_status()
    return str(resp.json()["choices"][0]["message"]["content"])


async def main() -> None:
    tickets = [
        "Billing dispute: charged twice for the Pro tier in March.",
        "Outage report: dashboard has returned 500s since 09:40 UTC.",
        "Feature request: export cohort retention as CSV.",
    ]
    async with httpx.AsyncClient() as client:     # one pooled client, reused
        summaries = await asyncio.gather(*(summarize(client, t) for t in tickets))
    for s in summaries:
        print("-", s.strip())


asyncio.run(main())
🧠 Brain power

Before reading on: would asyncio.gather also speed up a CPU-bound loop — say, tokenizing a million documents? Why or why not?

Reveal the answer

No. The event loop is one thread taking turns; it only wins when tasks wait (network, disk), because waiting is when it switches to other work, the stacked green blocks at marker 3 of Fig. 1.4b. A CPU-bound loop never yields, so async buys nothing (the chained red blocks under them) — you need multiple processes (or a C-backed library that releases the GIL) to use more cores. Rule of thumb for AI backends: async for IO (LLM calls, DB, vector search), processes for CPU (tokenizing, reranking, parsing). Mixing them up is the most common architecture mistake in first LLM services.

06 · Under the hoodThe Math, If You Want It

Everything above used two formulas as recipes: the standard error that sized the checkout wobble at 2.45 points, and the surprise score that turned a 3-point gap into 1.22 wobbles. This section shows where both come from, with the eval numbers from section 04 and a 75%-accurate model as the worked case. Read it when you want to defend the numbers to Diana, not just produce them.

Why 20 eval examples is a coin flip — the standard-error math

Suppose your assistant is "really" right 75% of the time and you score it on n examples. Each example behaves like a biased coin flip that lands "pass" 75% of the time, so the score you measure wobbles randomly around the true 75%. The size of a typical wobble has a name — the standard error — and a one-line formula:

SE = √( p·(1−p) / n )

Symbol key: SE (say "standard error") is the typical wobble we are solving for; p is the true pass rate; n is the number of examples; the raised dot (·) means multiply; √ is the square-root sign.

Read the formula in words before plugging anything in: p·(1−p) measures how coin-flippy each example is (largest at 50/50, zero if the model always passes or always fails), and dividing by n says the wobble shrinks as the eval grows. But notice the square root wrapped around everything: it means the shrinking is slow. Four times the examples buys you only twice the precision.

Now the numbers.

At n = 20 and p = 0.75: SE = √(0.75 × 0.25 / 20) ≈ 0.097 — read ≈ as "approximately equal to" — which is nearly ±10 points ("plus or minus ten": the wobble goes both up and down) of typical error.

And the conventional 95%-confidence range is about twice that (±1.96 × SE ≈ ±19 points), so a "75%" measurement honestly means "anywhere from the mid-50s to the mid-90s".

That is exactly why a 70%-versus-80% comparison on 20 examples is noise: the gap between the models is smaller than the wobble around either score. At n = 200 the standard error drops to ≈ 0.031, and now a 10-point gap finally means something.

true quality 75% 1 n = 20: 75 ± 19 56% 94% 2 n = 200: 75 ± 6 69% 81% 3 two models, 70% and 80% 70% 80% a 10-point gap fits inside the n = 20 range: noise and is wider than the whole n = 200 range: real
Fig. 1.4c — The standard-error arithmetic in the text, drawn: ±1.96 × SE at n = 20 is ±19 points, at n = 200 it is ±6. A 10-point gap between two models fits inside the first range and is wider than the second.
  1. n = 20. SE = √(0.75 × 0.25 / 20) ≈ 0.097, and 1.96 times that is 19 points. A '75%' measured on 20 examples honestly means anywhere from 56% to 94%.
  2. n = 200. Ten times the examples shrinks SE to ≈ 0.031, about √10 ≈ 3.2 times smaller, and the range to 69% to 81%. This is the same square-root law as Fig. 1.3c, at a different true rate.
  3. The 10-point gap. At n = 20 the gap between a 70% model and an 80% model is smaller than the wobble around either score, so it is noise. At n = 200 the gap is wider than the whole range, so it means something. Eval sets need hundreds of cases; this is the reason.

Remember this in Module 07: eval sets need hundreds of cases, not dozens, and this little formula is the entire reason.

What a p-value actually is (and is not)

The two-sample test asks one question: how surprising is the gap you observed, in a world where there is no real difference at all? The t-statistic turns that question into a single number by dividing the observed gap by the amount of gap that luck alone would typically produce:

t = (x̄B − x̄A) / √( s²A/nA + s²B/nB )

Symbol key: x̄ (say "x-bar") is a group's average, so x̄A is group A's average and x̄B is group B's; s² ("s-squared") is a group's variance — how spread out its values are; n is a group's size; √ is the square root; the small A and B subscripts simply label which group each number belongs to.

In words: the top of the fraction is "how far apart the two averages are"; the bottom is "how far apart luck would typically push them anyway", built from each group's spread (s², the variance) and size (n). A t near 1 means the gap is about what luck produces routinely — unremarkable. A t of 3 or more means the gap is three times larger than a typical lucky wobble — hard for chance to explain.

1 Fig. 1.2e, AGAIN: THE GAP MEASURED IN WOBBLES x̄ of A: 13.1% x̄ of B: 16.1% top of the fraction: the gap, 3.0 pt bottom: luck's typical push, 2.45 pt gap ÷ wobble = 1.22: about what luck produces routinely 2 20 METRICS WATCHED AT α = 0.05 each metric has a 1-in-20 chance of 'lighting up' by luck alone so with 20 of them, one false alarm per look is the expectation fix: name the one metric that decides, before the test starts
Fig. 1.4d — The two ideas in this block, drawn. The t (or z) statistic is the checkout gap divided by the lucky wobble, the same rulers as Fig. 1.2e; and watching 20 metrics at α = 0.05 hands you one false alarm per look on average.
  1. The fraction. Top: how far apart the two averages are, 3.0 points. Bottom: how far apart luck would typically push them, 2.45 points, built from each group's spread and size. The ratio, 1.22, is unremarkable; 3 or more is hard for chance to explain.
  2. Twenty chances. α = 0.05 means one lucky 'significant' result in every 20 tries. Watch 20 metrics and, on average, one of them crosses the bar by luck every time you look. The fix is to pick the single deciding metric before the data exists.

From there, a p-value of 0.03 means: if A and B were truly identical, you would see a gap this large only 3% of the time.

It does not mean "there is a 97% chance B is better" — that misreading is the most common statistics error in industry, and a favorite interview trap.

One more trap while we are here: if you monitor 20 metrics at the p < 0.05 threshold, then on average one of them will "light up" by pure luck every time you look, because 0.05 means one false alarm per 20 chances.

That is the multiple-comparisons problem, marker 2 of Fig. 1.4d, and it is why serious teams decide — before the experiment starts — which single metric gets to make the call.

Questions you might be asking now

The two blocks above explain where the formulas come from. Three questions about the checkout meeting usually survive them: where 0.22 comes from, what "power 0.23" means, and how one visitor's click ends up inside the verdict. Every answer uses the same counts from the meeting.

The meeting's counts, from the first run of ab_test_engine.py. The gap is 16.10% − 13.10% = 3.00 points, one lucky wobble (the standard error) is 2.45 points, and z = 3.00 ÷ 2.45 = 1.225.
GroupVisitorsConvertedConversion rate
Old page (A)4205513.10%
New page (B)4106616.10%
Both pages together83012114.58%
Where does p = 0.22 actually come from? Show me the "luck alone" repeats with the meeting's numbers.

From replaying the meeting's test in a world where the new page changed nothing. In 100,000 such replays, 22,410 showed a gap of 3.00 points or more in one direction or the other, so p = 0.224. The bell-curve shortcut inside ab_test_engine.py gets 0.220 from z = 1.225 in one line.

Fig. 1.2f drew the p-value as 22 shaded dots out of 100 and asked you to imagine the repeats. Here they are, computed by checkout_replay.py. The recipe has five steps. Only the first needs an idea; the rest is counting.

  1. Build the no-effect world. If the page did nothing, both pages share one conversion rate. The best guess for it is the pooled rate: 121 ÷ 830 = 14.58%. This is H₀ (H-nought), the null hypothesis, turned into a machine.
  2. Replay the test once. Send 420 pretend visitors to A and 410 to B, and let each one convert with chance 14.58%. The first replay gave A 58 conversions (13.81%) and B 57 (13.90%).
  3. Write down the gap. B's rate minus A's rate: 13.90% − 13.81% = +0.09 points.
  4. Repeat 100,000 times. The gaps pile up around zero, because zero is the truth in this world. Their spread is 2.45 points, the same standard error the formula gave.
  5. Count the replays at least as extreme as the meeting. 11.2% had B ahead by 3.00 points or more, and 11.2% had A ahead by as much. Together that is 22,410 of 100,000: p = 0.224.

Step E counts both directions because nobody promised, before the test, that only "B wins" would count. Had A come out 3 points ahead, someone would have been just as tempted to act on it. Counting one side only gives 0.112, half the answer, and choosing the side after seeing the data is a quiet way to cheat.

100,000 REPLAYS IN A WORLD WHERE THE NEW PAGE CHANGED NOTHING 1 both pages convert at 14.58%: the replayed gaps pile up at zero B ahead by 3.00+ pt: 11.2% 2 A ahead by 3.00+ pt: 11.2% −10 −4.8 −3 0 +3 +4.8 +10 replayed gap between the pages, B − A, in points 3 α line at ±4.80 pt: about 2.5% of replays beyond each; 3.00 does not reach it 11.2% + 11.2% = 22.4% of replays: p = 0.224 (bell-curve shortcut: 0.220)
Fig. 1.4e — The p-value, computed instead of imagined. 100,000 replays of the meeting's test with both pages converting at the pooled 14.58%, binned by the gap each replay produced. The shaded bars are the replays at least as extreme as the real 3.00-point gap. Values from rerunning checkout_replay.py.
  1. The no-effect world. Every bar is a batch of replays in which both pages convert at 14.58%, so any gap is pure luck. They pile up at zero and thin out fast: their spread is 2.45 points, the standard error.
  2. The meeting's gap, both ways. The shaded bars right of +3 are replays with B ahead by 3.00 points or more: 11.2%. The shaded bars left of −3 mirror them for A: 11.2%. Together they are the p-value, 0.224.
  3. The α line. Beyond ±4.80 points lie only about 2.5% of replays on each side: 2.47% and 2.33% here. A gap has to cross this line to count as significant at α (alpha) = 0.05, and 3.00 points does not reach it.
Three routes to the same p-value, from checkout_replay.py
RouteWhat it doesp
Replay the counts100,000 pretend tests with both pages at 14.58%0.224
Shuffle the labelsDeal the real 830 outcomes, 121 of them conversions, into groups of 420 and 410 at random, 20,000 times0.244 (exactly 0.238 when every possible split is counted)
The bell curveThe area beyond ±1.225 on a standard bell: 0.1102 on each side0.220

The shuffle is the most literal reading of "the page did nothing": which page a visitor saw becomes a meaningless label. It comes out a little higher because 121 conversions can only split in whole visitors, and the meeting's own 55-and-66 split, 3.7 shuffles in 100 on its own, counts as "at least as extreme". All three routes say the same thing: luck alone does this in about one test in four or five.

Where 1.96 comes from

The same bell explains the 1.96 in every formula on this page. On a standard bell, exactly 5% of the area lies beyond ±1.96 (plus or minus 1.96): 2.5% on each side. That is α (alpha) = 0.05 drawn as a distance. For the meeting's group sizes it is 1.96 × 2.45 = 4.80 points, marker 3 in Fig. 1.4e.

In visitors: with A still at 55 of 420, B would have needed 74 of 410 to cross that line, the first whole count past it. That is 18.0%, a gap of 4.95 points, z = 1.969 and p = 0.049, from 8 more conversions than the 66 it got.

The honest limit: the replay describes only the imaginary world. It says how ordinary a 3-point gap is when nothing changed, and it cannot give the chance that the new page works; that is the p-value trap from section 04. It also assumes every visitor is independent. A bot that clicks 50 times breaks all three routes at once.

A p-value is a count from an imaginary world: replay the test with no real effect and see how often luck alone matches your gap. For the meeting, about 22 replays in 100 did.

What is "power", and how did the calculator get 0.23 for the meeting and 2,162 visitors per page?

Power is the chance that a test of a given size says "real" when the effect really is real. If the new page truly converts 3 points better, a test with 420 and 410 visitors notices only 23 times in 100. The calculator's 2,162 per page raises that to about 80 in 100.

Think of a smoke alarm. α (alpha) sets how often it goes off when there is no fire: 5 times in 100. Power is how often it goes off when there is a fire. An alarm that seldom false-alarms but sleeps through three fires in four is not safe, and neither was the meeting's test.

The p-value question imagined a world with no effect. Power imagines the other world, where the new page really lifts conversion from 13.1% to 16.1%. It asks how often the test would then cross the α line, marker 3 in Fig. 1.4e.

Power 0.23, by hand

  1. Size the wobble in the real-effect world. Each page keeps its own rate: √(0.1310 × 0.8690 ÷ 420 + 0.1610 × 0.8390 ÷ 410) = √0.000600 = 0.0245, again 2.45 points.
  2. Measure the true gap in wobbles. 3.00 ÷ 2.45 = 1.225. If the effect is real, the test's z lands on a bell centred at 1.225.
  3. Find the finish line. The test says "real" only when z passes 1.96.
  4. Measure from the bell's centre to the line. 1.96 − 1.225 = 0.735 wobbles to the right of the centre.
  5. Read the area past the line. On a standard bell, 23.1% of the area lies more than 0.735 to the right of the centre. That is power = 0.231.

Replaying the real-effect world 100,000 times with checkout_replay.py agrees: 23.1% of the pretend tests came out significant. The other 76.9% are Type II errors, missed wins. That 0.769 is the β (beta) in the symbol table of section 04.

2,162 per page, by hand

Planning runs the same picture backwards. You choose the smallest lift worth finding (3 points up from 13%), the α you accept (0.05) and the power you want (80%). Then you solve for visitors per page. required_sample_size() does it in five steps.

  1. The α part. 1.96 × √(2 × 0.145 × 0.855) = 1.96 × 0.4979 = 0.9760. This is the noise a gap must clear when nothing changed, and 14.5% is the rate that no-effect world would show: the average of the two.
  2. The power part. 0.8416 × √(0.13 × 0.87 + 0.16 × 0.84) = 0.8416 × 0.4975 = 0.4187. 0.8416 is how far past the line a bell's centre must sit for 80% of the bell to cross it.
  3. Add, then square. (0.9760 + 0.4187)² = 1.3947² = 1.9451.
  4. Divide by the lift squared. 1.9451 ÷ 0.03² = 1.9451 ÷ 0.0009 = 2,161.2.
  5. Round up. 2,162 visitors per page, 4,324 in all.

In words: the gap must sit 1.96 wobbles past zero plus another 0.84, and a wobble shrinks with the square root of the visitor count. Steps C and D find the visitor count at which 3 points is that many wobbles long.

Power for four test sizes, by the engine's formula and by 100,000 replays each, from checkout_replay.py
TestVisitors per pageOne wobbleTrue gap in wobblesPower, formulaPower, replay
The meeting, 13.1% vs 16.1%420 and 4102.45 points1.2250.2310.231
The plan, 13% vs 16%2,162 each1.07 points2.800.8010.800
Ten times the meeting4,200 and 4,1000.77 points3.870.9720.973
The plan, if the true lift is only 1.5 points2,162 each1.05 points1.430.2990.300
1 THE MEETING: 420 AND 410 VISITORS, ONE WOBBLE = 2.45 POINTS no effect real +3-point lift 2 α line: +4.80 points 3 power 0.23 23 tests in 100 cross −6 −3 0 +3 +6 +9 4 THE PLAN: 2,162 VISITORS PER PAGE, ONE WOBBLE = 1.07 POINTS no effect real +3-point lift α line: +2.10 points power 0.80 about 80 tests in 100 cross −6 −3 0 +3 +6 +9 gap between the pages, B − A, in points; both panels drawn to the same scale
Fig. 1.4f — Power drawn as two bells. The dashed bell is where the gap lands if the new page did nothing; the solid bell is where it lands if the page really adds 3 points. The shaded part of the solid bell crosses the α line. Top: the meeting. Bottom: the calculator's 2,162 per page. Values from rerunning checkout_replay.py.
  1. Two worlds. The dashed bell is the world of Fig. 1.4e, where the page did nothing. The solid bell is where the gap lands if the page really adds 3 points. With 420 and 410 visitors both bells are 2.45 points wide, so they overlap almost completely.
  2. The α line. The test says "real" only past 1.96 wobbles, which is +4.80 points here. Only 2.5% of the dashed bell lies past it on this side: the small red tail, the false alarms you agreed to.
  3. Power 0.23. The shaded part of the solid bell is the share of real-effect tests that cross the line: 23.1%. The other 76.9% would report "not proven" about a page that really works.
  4. The plan. At 2,162 visitors per page both bells shrink to 1.07 points wide. The line moves in to +2.10 points, and 80.1% of the solid bell now crosses it. The lift did not grow; the bells got narrower.

Two honest limits. First, this arithmetic only works if step A uses the rate the no-effect world would show, which is the average of the two rates, 14.5%. An earlier version of the calculator used the baseline 13% instead and asked for 2,028 per page; replaying that size gives about 77.6% power, not the 80% it promised.

Second, power depends on the lift you assumed, and nobody knows the true lift in advance. If it is really 1.5 points, 2,162 per page has power 0.299, and 80% power would take 8,273 per page. Plan for the smallest lift that would change the decision, not the lift you hope for.

Power is the chance your test notices a real effect of the size you assumed, and you check it before the test starts. At 0.23, the meeting's test was more than three times as likely to miss a real win as to find one.

Walk one visitor through the whole stack, from a row in the warehouse to Diana's verdict.

Visitor V-0007 saw the new page and bought. Their row becomes 1 of page B's 66 conversions, then 0.244 points of B's 16.10%, and the verdict stays "not proven". The trace also shows where the stack can be fooled: logging 20 purchases twice would have flipped the verdict to "ship it".

The counts in the table above did not arrive by themselves. one_visitor_trace.py rebuilds the two-week test as 830 event rows in DuckDB, one row per visitor. It follows the first buyer on page B, V-0007, through every stage of Fig. 1.1. The rows are generated; their counts, and every number below, are the meeting's.

V-0007, station by station, as one_visitor_trace.py printed it
StationWhat V-0007 is hereThe numbers
1 · The warehouse rowOne row of checkout_events: V-0007, page B, converted 11 of 830 rows; COUNT(DISTINCT visitor_id) is also 830
2 · GROUP BY variantA 1 inside B's SUM(converted)A: 420 rows, 55 conversions. B: 410 rows, 66 conversions
3 · The .df() hand-offStill inside the 66, now in pandasconversions arrives as 66.0, a float64 column
4 · run_ab_test(420, 55, 410, 66)1 ÷ 410 of B's rate0.244 points of 16.10%; the gap is 3.00 points
5 · The verdictA sliver of zz = 1.225, p = 0.220: "Do NOT ship on this evidence"

Station 2 is level 2 of section 03 again. GROUP BY folds 410 rows into one summary row, exactly as it folded contract types in Fig. 1.1e. After this station nothing knows who V-0007 was. They are a 1 inside a sum.

Station 3 holds a real surprise. In DuckDB, SUM of an integer column returns a 128-bit integer, and pandas has no column type that large. So .df() stores 55 and 66 as 55.0 and 66.0.

The engine still runs on 66.0, but a strict type check or a JSON contract that expects an integer would reject it. Write SUM(converted)::BIGINT in the query, and the column arrives as int64; the script prints both.

At station 4 the visitor's weight is set by the group size alone: one purchase out of 410 visitors is 0.244 points. The gap is 3.00 points, so V-0007 is about a twelfth of it.

ONE BUYER ON THE NEW PAGE, FROM A WAREHOUSE ROW TO THE VERDICT 1 warehouse row V-0007 · B · 1 id · page · bought 1 of 830 rows 830 distinct ids 2 GROUP BY A: 420 rows, 55 B: 410 rows, 66 V-0007 is 1 of 66 the id is gone 3 .df() hand-off conversions 66 → 66.0 HUGEINT → float64 fix: ::BIGINT 4 run_ab_test 66 ÷ 410 = 16.10% V-0007: 0.244 pt gap 3.00, SE 2.45 z = 1.225 5 verdict p = 0.220 above α = 0.05 NOT PROVEN do not ship 6 change one thing at station 1, rerun IF V-0007 HAD NOT BOUGHT B: 65 of 410 · z = 1.13 · p = 0.259 p moved by 0.04; the verdict holds: not proven IF 20 PURCHASE EVENTS WERE LOGGED TWICE 850 rows · B: 86 of 430 · z = 2.706 · p = 0.007 engine says "Ship it"; 850 rows but 830 distinct ids
Fig. 1.4g — One checkout visitor through the stack. Top: the five stations, and what the visitor has become at each. Bottom: two changes made at station 1 and carried through; only the second changes the verdict, and it is a bookkeeping bug, not a better page. Values from rerunning one_visitor_trace.py.
  1. The row. One event row per visitor: an id, the page they saw, and 1 for a purchase. The table has 830 rows and 830 distinct ids, so nobody is counted twice. V-0007 is the first buyer on page B.
  2. The fold. GROUP BY variant turns 830 rows into two summary rows, exactly as level 2 did with contract types. V-0007 survives only as a 1 inside B's sum of 66; the id never leaves the warehouse.
  3. The hand-off. .df() brings the two rows into pandas. DuckDB's SUM of an integer column is a 128-bit HUGEINT, which pandas stores as float64, so 66 arrives as 66.0. Cast with ::BIGINT in the query, or with int() before the engine.
  4. The engine. 66 ÷ 410 = 16.10%, and one buyer is 1 ÷ 410 = 0.244 points of it, about a twelfth of the 3.00-point gap. The gap divided by the 2.45-point wobble is z = 1.225.
  5. The verdict. p = 0.220 is above α (alpha) = 0.05, so the engine prints "Do NOT ship on this evidence". V-0007's purchase counted, and on its own it was nowhere near enough to matter.
  6. Two what-ifs. Without V-0007's purchase, p rises to 0.259 and the verdict holds. With 20 purchase events logged twice, B reads 86 of 430, p = 0.007, and the engine says "Ship it". Only a check at station 1 can catch that.

What one visitor, and one bug, can do

Change one thing at station 1 and rerun the rest, from one_visitor_trace.py
ScenarioPage BzpEngine's verdict
The meeting as it happened66 of 4101.2250.220Do not ship
V-0007 did not buy65 of 4101.130.259Do not ship
The same one-visitor flip at ten times the traffic659 of 4,100 (was 660)3.845 (was 3.875)0.00012 (was 0.00011)Ship it
The confirmation event fired twice for 20 buyers on page B86 of 4302.7060.007Ship it

The second row is the fragility of a small test: one person's purchase moves p by 0.04. At ten times the traffic, the same flip moves it by 0.00001. A big test is not only more powerful; it is also harder for any single row to push around.

The last row is the honest limit of the whole stack. Twenty purchase events logged twice turn 66 of 410 into 86 of 430, and the engine says "Ship it" with p = 0.007. Nothing after station 1 can tell, because statistics checks luck, not bookkeeping.

The check belongs at station 1, and it is one query: COUNT(*) returns 850 while COUNT(DISTINCT visitor_id) returns 830. That mismatch is exactly the kind of data-quality gate the lab in section 07 asks you to build.

A visitor becomes a 1 in a SUM, a quarter of a point in a rate and a sliver of z. The statistics judge only the luck in the rows they receive, so check that rows and distinct visitors match before any test runs.

There are no dumb questions

Why uv and not conda or plain pip? Everyone at my company uses conda.
conda still works, but the 2026 Python-for-AI mainstream has consolidated on uv: it resolves and installs in seconds, writes a lockfile by default, and replaces pip + venv + pyenv + pipx with one binary. Every lab in this course assumes uv run works. If your team is on conda, the concepts transfer — a pinned, reproducible environment is the point, the tool is detail.
Do I really need type hints for lab code?
Yes — not for the interpreter, for the ecosystem. Pydantic validates LLM outputs against typed models (Module 06), FastAPI generates API contracts from them (Module 12), and coding agents (Module 15) produce dramatically better edits in typed codebases because the types are machine-readable context.
SQL in an AI course — is that a box-ticking exercise?
The opposite: data engineering tops the AI-adjacent skills in postings (11.6%). Every RAG corpus, every fine-tuning dataset, every eval set starts life as a query against someone's warehouse. Engineers who can pull and clean their own data ship AI features weeks faster than those who file tickets for it.
Why percentiles instead of averages for latency?
Because users don't experience averages. If p50 is 800ms and p99 is 12s, one user in a hundred is staring at a spinner for twelve seconds — and at 10K requests/day that's a hundred bad experiences daily, invisible in the mean. LLM latency is long-tailed (retries, cold caches, long generations), so tails, not means, drive the SLA conversation in Module 12.
Boardroom translation

This module is the difference between "I think the new prompt is better" and "the new prompt lifts resolution rate 4.2 points, p < 0.01 on 400 tickets — annualized, that's ₹80 lakh in deflected support cost." Executives fund the second sentence. The stack skills come with their own pitch: reproducible environments and typed contracts are why your demo won't die in the client's environment — which is, in the end, what "production-grade" means to a buyer.

07 · The labBuild the Course Scaffold

The pieces now exist separately: a five-row warehouse, five levels of SQL, an A/B engine that turned 55-of-420 against 66-of-410 into "not proven", a typed contract and a concurrent client. The lab assembles them into the scaffold every later module reuses, and proves the stack works on a deliberately messy dataset before Diana sees a number from it.

LAB 01 — The project scaffold + a data-quality report

Mission: set up the exact project structure every later lab will reuse, then prove the stack works by producing a data-quality report over a deliberately messy dataset. Use the messy-CSV generator from the SQL section (or re-run it) so everything works offline.

  • uv init ai-course && uv add pandas duckdb pydantic pytest — committed with pyproject.toml and uv.lock; a teammate can clone and uv run pytest green in under two minutes
  • A Settings Pydantic model loads config from environment variables (no hardcoded paths or keys anywhere) and fails loudly with a helpful message when one is missing
  • report.py queries the messy CSV through duckdb and emits a data-quality report: row counts, null rates per column, duplicate keys, out-of-range values, and the top-5 revenue rows — every number produced by SQL, not pandas loops
  • At least three typed functions with docstrings; uv run mypy . (or pyright) passes with zero errors
  • One async function fetches three URLs concurrently (httpbin or local files) and the report prints sequential-vs-concurrent wall-clock — your first measured speedup
  • README states what the report found — written for a stakeholder, numbers first

Stretch: add a pytest suite asserting the data-quality rules (null rate below threshold, no duplicate keys) so the report becomes a gate — the exact pattern evals will follow in Module 07.

08 · Interview radarHow This Shows Up in Interviews

Interview radar

"Write a query: top 3 products by revenue per region."

The real test Whether you reach for a window function or try to fake per-group ranking with joins.

Strong answer This is a rank-within-groups problem, so I'd use a window function: ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) numbers each region's products from its own top seller down. Wrap that in a subquery or CTE, keep the rows numbered 3 or less, and every region returns exactly its top three. A join-based workaround exists, but reaching for it is exactly what this question is built to screen out.

Land it Practice the pattern until it is reflexive — the interviewer is watching how fast it comes, not just whether it comes.

"Your A/B test shows p = 0.04. What do you tell the PM?"

The real test Whether you can turn a statistic into a decision briefing instead of announcing "it's significant."

Strong answer A strong report covers three things before anyone celebrates:

  • Effect size with a confidence interval — how big the lift is and how uncertain, not just that it cleared the significance bar
  • The pre-registered metric — this is the metric we agreed to judge on before launch, not one picked after peeking at the results
  • Sample-size adequacy — the test was large enough for the result to be worth acting on

Land it Then translate for the PM: "we'd see a gap this large by luck 4% of the time" — the plain-English version is what makes the number usable.

"Why is your LLM backend async? What breaks if it isn't?"

Strong answer LLM calls are IO-bound waits of 1–10 seconds: the process is doing nothing but holding a connection open while the model generates.

With a sync worker pool, every in-flight call occupies a whole worker, so the pool exhausts under even modest concurrency, requests queue behind it, and p95 latency explodes.

Async flips that: one process keeps hundreds of calls in flight, because a request that is merely waiting costs almost nothing. The caveat that shows depth is that async only helps waiting — CPU-bound stages still need processes.

Land it Name the metric you'd watch to prove it: p95 latency and queue depth.

"How do you make a Python project reproducible?"

Strong answer Four habits, and they compound:

  • Lockfiles — commit the exact resolved dependency set, so every machine installs the same environment
  • Pinned versions — declared dependencies carry versions, so an upstream release can't silently change behavior
  • Env-var config — no hardcoded paths or keys; configuration comes from the environment and fails loudly when something is missing
  • One-command setup — a teammate clones the repo and is running the tests within minutes, exactly the scaffold this module's lab builds

Land it Close with why it matters: "works on my machine" is a cost center — every environment mismatch gets paid for in someone's debugging hours.

Quick reference — The working stack

Stack rule
Pick the tool with no server to run and the most users, and write down the size or team situation that would make you switch (the table in section 02).
Push the work to the database
Filter, aggregate and join in SQL; bring back the small result (the rule from section 02). Pulling a million rows into pandas to filter them is the single most common beginner mistake.
p-value
How often luck alone would produce a difference at least this big. Small p means luck is a poor explanation — it does not mean the effect is large or important.
α (alpha)
The cutoff you set in advance for how much luck you will tolerate, usually 0.05 (marker 2 of Fig. 1.2f). Choosing it after seeing the data is how people fool themselves.
Type I / Type II error
Type I: you claimed an effect that is not there. Type II: you missed one that is. Which is worse depends entirely on the decision.
confidence interval
The range of effects consistent with your data. More useful than a p-value, because it shows the size of what you might have found.
standard error (SE)
The typical distance between one measured score and the true value: the spread you would see across reruns. For a pass rate it is √(p · (1 − p) / n), which is 0.10 for a 70% prompt on 20 tickets, worked by hand in Fig. 1.3i.
bias vs variance
Variance is scatter between reruns, and more data shrinks it. Bias is a centre in the wrong place, caused by how the data was picked, and more data does not move it (Fig. 1.3k).
power
The chance your test would notice a real effect of a given size. Low power is why most “no difference” results mean nothing.
Percentiles for latency
Averages hide the slow tail (marker 3 of Fig. 1.3e), and the tail is what users feel. Report p50, p95, p99.

09 · RecapWhat You Can Do Now

  • You can stand up a pinned, reproducible Python project with uv in one command — and explain why lockfiles matter
  • You can pull, join, and window your way through a warehouse in SQL, and clean messy data where it lives
  • You can run and read an A/B test — effect size, confidence interval, and the p-value's real meaning
  • You can compute why small eval sets lie (standard error) — the foundation Module 07 builds on
  • You can write typed, Pydantic-validated code that FastAPI and LLM structured outputs will plug into unchanged
  • You can explain and demonstrate why AI backends are async, and measure the speedup
  • You can report p50/p95/p99 latency and defend why tails beat means
  • You can work out a standard error and a confidence interval by hand, and explain why 14 passes out of 20 honestly means anywhere from 46% to 88%
  • You can replay a test in a world with no effect to see where its p-value comes from, and check a test's power before it starts
🧠 Flex your memory

From this module: without looking, write the standard-error formula and compute SE for a 75%-accurate model measured on 50 examples. Is a 6-point improvement distinguishable from noise?

Reaching back to Module 00: sketch the "inversion" diagram from memory — what goes in and what comes out of traditional programming vs machine learning? Where in today's data-quality lab did you feed "outputs" rather than "rules"?