The Working Stack — Python, SQL & Statistics for AI
"Before you build the engine, master the workshop tools."
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.
"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."
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:
- Pull the right rows out of a warehouse — that is SQL.
- Decide whether an observed difference is real or luck — that is statistics.
- Wrap the whole thing in code another engineer can run, type-check and trust — that is professional Python.
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.
- 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.
- 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.
- 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.
- 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.
- 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.
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:
| You know cold | This 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 path | Hypothesis tests asserting against the null — "prove this isn't luck" |
| package.json + lockfile | pyproject.toml + uv.lock |
| TypeScript interfaces at API boundaries | Pydantic 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?
- 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.
- 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. - 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.
- 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.
| Stage | In this module's scripts | At SaaSify's real scale | What flows out |
|---|---|---|---|
| Data warehouse | warehouse_sim.py seeds five rows into saasify.duckdb | Snowflake or BigQuery holding tens of millions of event rows, loaded nightly | Tables you query, and never pull whole |
| SQL query, the forklift | level_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 triangle | A few thousand tidy rows: one per customer, cohort or rank |
| The hand-off | con.sql(...).df(), the comment on the last line of warehouse_sim.py | pd.read_sql(...) against the warehouse, or Parquet files the warehouse exports and DuckDB reads directly | A pandas DataFrame that fits in memory |
| DataFrame, the workbench | Subscription.model_validate(raw) in subscription_contract.py checks each row | The same Pydantic model at every service boundary, then feature engineering in pandas | Typed rows ready to become features, prompts and eval sets |
| Statistics, the lie detector | run_ab_test(420, 55, 410, 66) in ab_test_engine.py; eval_variance.py; latency_percentiles.py | The same z-test on prompt v1 against v2 in Module 07, sized with required_sample_size() before the test starts | A verdict with a confidence interval, not a bare percentage |
| Model / LLM app | concurrent_summaries.py sends three tickets to a local model at once | Acts II and III: features into scikit-learn, context into an LLM, fan-out capped by a semaphore | Predictions, summaries and eval scores |
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.
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| SQL engine | DuckDB (the 1.x line) | SQLite, PostgreSQL, ClickHouse, Spark | Runs 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 table | pandas, reached through .df() | Polars, plain Python lists | Every 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. |
| Statistics | numpy and scipy, written by hand in ab_test_engine.py | statsmodels, pingouin, a hosted experiment tool | Writing 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 packages | Python 3.12 with uv | pip + venv, Poetry, conda | One 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 checking | Pydantic v2 | dataclasses, attrs, marshmallow, hand-written if checks | It 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 HTTP | asyncio with httpx | threads, requests, aiohttp | Waiting 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.
- 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.
- 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.
- 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.
Step-by-step: what warehouse_sim.py does, in plain English
- 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.
- Open a database stored in a single file called
saasify.duckdb(DuckDB creates the file if it does not exist yet). Theconvariable is your phone line to that database — every later command goes through it. - Create a table named
subscriptionsand 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 wordsCREATE OR REPLACEmean "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. - In exactly the same way, create a
support_ticketstable with three ticket rows (which customer raised it, and what kind of issue it was). - Again the same way, create a
user_activitytable with five rows recording a date on which each customer was active. - 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.
# 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.
| customer_id | signup_date | monthly_charges | contract_type | churn | signup_tier |
|---|---|---|---|---|---|
| C101 | 2025-01-15 | 120.00 | Month-to-Month | 1 | Pro |
| C102 | 2025-01-20 | 85.50 | One-Year | 0 | Basic |
| C103 | 2025-02-01 | 145.00 | Month-to-Month | 0 | Pro |
| C104 | 2025-02-10 | 45.00 | Two-Year | 0 | Basic |
| C105 | 2025-03-05 | 110.00 | Month-to-Month | 1 | Pro |
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
FROM subscriptions— start with the five-row table we just seeded.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.SELECT— from each surviving row, keep just three columns: the customer id, the charge, and the contract type.ORDER BY monthly_charges DESC— sort what is left from the highest charge to the lowest (DESC is short for "descending").- Result: three rows come back — C103 ($145), C101 ($120), C105 ($110) — exactly the table below.
-- 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)
| customer_id | monthly_charges | contract_type |
|---|---|---|
| C103 | 145.00 | Month-to-Month |
| C101 | 120.00 | Month-to-Month |
| C105 | 110.00 | Month-to-Month |
- 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.
- 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.
- 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
- Connect to a fresh, empty DuckDB held only in memory (no filename given, so nothing is saved to disk).
- Build a table called
bigwith 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 % 3is the remainder after dividing by 3, so it cycles 0, 1, 2), and a monthly charge. - Way 1 (the slow way): start a stopwatch with
time.perf_counter(), then callfetchall()— which drags all ten million rows out of the database and into Python's memory as a giant list. - 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.
- Stop the stopwatch; the elapsed time is saved as
py_secs. - 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.
- 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.
# 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")
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.
- 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.
- 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.
- 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
FROM subscriptions— start with all five rows.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).- 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 theSUM(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. 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.)ORDER BY churned_count DESC— sort the buckets so the one losing the most customers appears first.
-- "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;
| contract_type | total_customers | avg_monthly_charge | churned_count |
|---|---|---|---|
| Month-to-Month | 3 | 125.00 | 2 |
| One-Year | 1 | 85.50 | 0 |
| Two-Year | 1 | 45.00 | 0 |
- 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.
- 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.
- 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.
- 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.
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
- 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 nicknamet. LEFT JOIN ... ON s.customer_id = t.customer_id— glue that little table ontosubscriptions(nicknameds) 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.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.SELECT— keep the id, charge, contract type, and the (now clean) ticket count.ORDER BY support_tickets DESC LIMIT 3— sort by ticket count, most first, and keep only the top three rows.
-- "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;
| customer_id | monthly_charges | contract_type | support_tickets |
|---|---|---|---|
| C101 | 120.00 | Month-to-Month | 2 |
| C103 | 145.00 | Month-to-Month | 1 |
| C102 | 85.50 | One-Year | 0 |
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
- There is no GROUP BY here, so nothing collapses: all five rows of
subscriptionsgo in, and all five come back out. - 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 newcharge_rankcolumn. 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 asavg_for_tier. Every Month-to-Month row shows the same 125.00, because they share the same peers.- 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.
-- "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;
| customer_id | contract_type | monthly_charges | charge_rank | avg_for_tier |
|---|---|---|---|---|
| C103 | Month-to-Month | 145.00 | 1 | 125.00 |
| C101 | Month-to-Month | 120.00 | 2 | 125.00 |
| C105 | Month-to-Month | 110.00 | 3 | 125.00 |
| C102 | One-Year | 85.50 | 1 | 85.50 |
| C104 | Two-Year | 45.00 | 1 | 45.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.
RANK()1 OVER2 (PARTITION BY contract_type3
ORDER BY monthly_charges DESC4) AS charge_rank5
- 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 plainAVG()orSUM()for a per-group figure. The common mistake is usingRANK()to deduplicate: tied rows share a rank, so two rows can both be 1. Deduplication wantsROW_NUMBER(). - OVER. The word that turns an aggregate into a window function. Without it,
AVG(monthly_charges)collapses the table and demands aGROUP 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". - PARTITION BY. Defines who counts as a peer.
contract_typehere 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 bycustomer_id: every row is then alone in its group, every rank is 1, and nothing errors. - 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 outerORDER BY, which only sorts the printed output. ForgetDESCand rank 1 goes to the cheapest customer. UseROW_NUMBER()over a column with ties and the numbering can change between runs; add a tiebreaker such ascustomer_id. - AS charge_rank. Names the new column, marker 3 of Fig. 1.2. The mistake everyone makes once is
WHERE charge_rank <= 3in the same query. The engine evaluates window functions afterWHERE, so the column does not exist yet. Wrap the query in a CTE and filter in the outer query, or in DuckDB writeQUALIFY charge_rank <= 3, a clause that exists for exactly this.
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.
- 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'.
- 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.
- 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
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.activities AS (...)— a second named step doing the same date-chopping to each customer's activity dates.- 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.
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, andCOUNT(DISTINCT a.customer_id)counts how many of them show activity (DISTINCT makes sure a customer active five times still counts once).ORDER BY 1— sort the cohorts chronologically. One row per signup month: size of the cohort, and how many are still active.
-- "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;
| cohort_month | total_cohort_users | active_users_now |
|---|---|---|
| 2025-01-01 | 2 | 2 |
| 2025-02-01 | 2 | 2 |
| 2025-03-01 | 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.
- 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.
- 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.
- 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:
| Option | Choose when | Avoid when | Typical cost |
|---|---|---|---|
| CTE | Readability; result used once or twice in one query | Referenced many times — the engine may re-execute it | Free to write, possibly recomputed |
| Subquery | One-off inline logic, one level deep | Nested 3+ levels — unreadable, untestable | Free, until a human has to modify it |
| Temp table | Expensive intermediate reused across queries; needs indexes | Simple pipelines — adds state and cleanup | Storage + 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.
- 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.
- 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.
- 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.
Tonight's talk: SQL and pandas argue over the question, "Who's more important?"
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.
"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."
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.
- 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.
- 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.
- 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.
- 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.
- α 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.
- 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:
- 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.
- 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.
- 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.
- 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'.
- 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.
| Symbol | How to say it | What 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.
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.
-
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
- Define
run_ab_testwith four counts: visitors and conversions for the control group, then the same for the treatment group. - Divide conversions by visitors in each group to get the two rates.
- Subtract: the lift is the treatment rate minus the control rate.
- Return the three numbers in a dictionary, and print them for the meeting's real counts.
ab_test_engine.py — chunk 1runs offlinedef 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 testA function with named arguments, and a dictionary as the return value.
Save as
chunk1_rates.pyand runpython3 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. - Define
-
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
- Add two import lines at the top of the file: numpy for the square root, scipy for the normal distribution used in chunk 3.
- Pool both groups into one rate, because the question is what luck alone would do if the two groups were really the same.
- Compute the standard error from the pooled rate and the two group sizes.
- Divide the lift by the standard error to get z, guarding against dividing by zero.
- 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 offlineimport 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 returnnp.sqrt, and a one-linex if condition else yexpression.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. -
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
- Add
alpha=0.05to the function's arguments: the cutoff you decide before looking. - Convert z to a p-value with the normal distribution's survival function, doubled because a lucky difference could go either way.
- Find the z value that marks the middle 95%, then build the interval as the lift plus and minus that many standard errors.
- 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.sfandstats.norm.ppf, scipy's normal-distribution tail and its inverse.Run
python3 chunk3_pvalue.py. You should seep_valueof 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. - Add
-
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
- Compute the spread of the observed lift, using each group's own rate this time.
- Convert the lift, measured in those spreads and minus the cutoff, into the chance a test of this size would have caught it.
- 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": powerstats.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. -
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
- Define
ABTestResultas a frozen dataclass, a record that cannot be changed after it is made. - Add a
verdictproperty: ship if the p-value beat alpha, otherwise collect more data. - Replace the dictionary return with an
ABTestResult, rounding each number once, and setis_significantto whether the p-value is below alpha. - 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(plusfrom dataclasses import dataclassat the top).Run
python3 chunk5_pack.py. The meeting printsz=1.225 p=0.2204 CI=(-0.018, 0.078) power=0.231and "Do NOT ship"; the ten-times-traffic run printsz=3.875 p=0.00011and "Ship it". Same lift, different verdict. - Define
-
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
- Take the current rate, the smallest lift you care about, alpha and the power you want.
- Look up the two z values for alpha and for power.
- Plug them into the standard sample-size formula and round up to a whole visitor.
- Print the answer next to the meeting's actual 420.
ab_test_engine.py — chunk 6 (the whole file below)runs offlinedef 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 readsTo 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
- 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. Itsverdictproperty turns the yes/no significance flag into a sentence a human can act on. run_ab_teststarts by computing each group's conversion rate: conversions divided by visitors. The lift is simply the treatment rate minus the control rate.- 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. - 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. - Compute
z: the lift divided by that noise size. Read it as "the observed difference is z times bigger than a typical lucky wobble". (Theif se > 0guard just avoids dividing by zero.) - 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 usesstats.norm.sf, the survival function, instead of1 − cdfpurely for numerical precision with very large z. - Build the 95% confidence interval: lift ± 1.96 × se — the range where the true lift plausibly sits.
- Compute the statistical
power: the probability that a test with these group sizes would successfully detect an effect of this size. - Round everything and pack it into an
ABTestResult, whoseis_significantis simply "was the p-value below α?". required_sample_sizeruns 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?"- 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.
# 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.")
--- 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.
- 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.
- 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.
- 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.
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
- 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.
- Fix the model's true quality at 70% (
TRUE_PASS_RATE) and decide to simulate 10,000 parallel universes (RUNS). - 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. 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.- 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.
# 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.
- 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.
- 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.
- 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.
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.
| Run | Tickets passed | Score | Distance from the true 70% |
|---|---|---|---|
| 1 | 14 of 20 | 70% | 0 points |
| 2 | 17 of 20 | 85% | +15 points |
| 3 | 11 of 20 | 55% | −15 points |
| 4 | 15 of 20 | 75% | +5 points |
| 5 | 13 of 20 | 65% | −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:
| Source | What changes between runs | At SaaSify |
|---|---|---|
| Which tickets land in the set | Each run samples a different 20 tickets from the queue | A run that happens to draw more of the hard billing disputes scores lower |
| The model's own randomness | The same ticket can pass on one call and fail on the next, because the model samples its words | A 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Find the average. (0.70 + 0.85 + 0.55 + 0.75 + 0.65) ÷ 5 = 0.70.
- Measure each distance from it. 0, +0.15, −0.15, +0.05 and −0.05.
- 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.
- Average the squares. (0 + 0.0225 + 0.0225 + 0.0025 + 0.0025) ÷ 5 = 0.0100. This middle number is called the variance.
- 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.
- 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.
- Measure the two distances. A pass sits +0.30 above that average; a fail sits −0.70 below it.
- 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.
- 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.
- 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.
| Route | Working | Standard error |
|---|---|---|
| The five reruns, by hand | √ of the average squared distance | 0.1000 |
| The formula | √(0.70 × 0.30 ÷ 20) | 0.1025 |
| eval_variance.py's 10,000 runs | The spread of all 10,000 scores | 0.1024 |
Two names in this answer are easy to swap, so here they are side by side.
| Standard deviation | Standard error | |
|---|---|---|
| What it describes | How far one value sits from the average: one ticket, a 1 or a 0, sits 0.458 away | How far a whole score sits from the truth: 0.1025 for 20 tickets |
| Formula here | √(p · (1 − p)) | √(p · (1 − p) / n) |
| With more tickets | No change: a ticket is still a 1 or a 0 | Shrinks by √n: 0.0458 at 100 tickets, 0.0205 at 500 |
- 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.
- 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.
- 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
- Take the score. 14 ÷ 20 = 0.70.
- 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.
- 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.
- 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 rate | Chance of 14 or more passes | Chance of 14 or fewer passes | Believable? |
|---|---|---|---|
| 40.0% | 0.006 | 0.998 | No: 14 or more passes would happen 6 times in 1,000 |
| 45.7% | 0.025 | 0.992 | The lower edge |
| 55.0% | 0.130 | 0.945 | Yes |
| 70.0% | 0.608 | 0.584 | Yes |
| 80.0% | 0.913 | 0.196 | Yes |
| 88.1% | 0.994 | 0.025 | The upper edge |
| 95.0% | 1.000 | 0.000 | No: 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.
| Run | Score | Quick formula | Exact method |
|---|---|---|---|
| 1 | 14 of 20, 70% | 49.9% to 90.1% | 45.7% to 88.1% |
| 2 | 17 of 20, 85% | 69.4% to 100.6% | 62.1% to 96.8% |
| 3 | 11 of 20, 55% | 33.2% to 76.8% | 31.5% to 76.9% |
| 4 | 15 of 20, 75% | 56.0% to 94.0% | 50.9% to 91.3% |
| 5 | 13 of 20, 65% | 44.1% to 85.9% | 40.8% to 84.6% |
- 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%.
- 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%.
- 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.
- 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.
| Eval set | Tickets | Centre of the reruns | Where 95% of reruns land | Spread (standard error) | Bias |
|---|---|---|---|---|---|
| Whole queue | 20 | 70.2% | 50% to 90% | 0.102 | +0.2 points |
| Whole queue | 500 | 70.0% | 66% to 74% | 0.020 | 0.0 points |
| Feature requests only | 20 | 89.9% | 75% to 100% | 0.067 | +19.9 points |
| Feature requests only | 500 | 90.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 | Bias | |
|---|---|---|
| What it is | Scatter of reruns around their own centre | Distance from that centre to the true quality |
| Where it comes from | Luck: which tickets came up, and the model's own randomness | How 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 measure | No: they are blind to it |
| How you find it | Rerun, or use the formula | Compare the eval set with the real queue |
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
- Create a seeded random generator (same reason as before: repeatable output).
- 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. - Compute the plain average of all 100,000 times — the number a naive dashboard would show.
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).- Print all four numbers, each labeled with who it describes — and notice the mean sits far from the p99 that actually hurts users.
# 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
- 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'.
- 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.
- 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 for environments and dependencies.
- Type hints as the norm, not as decoration.
- Pydantic v2 at every data boundary.
- async/await, because LLM apps spend their lives waiting on the network.
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
- Line 1 downloads uv's install script and runs it — a one-time setup, like installing Node before your first JavaScript project.
uv init ai-course --python 3.12creates a new project folder namedai-coursewith apyproject.tomlinside, pinned to Python 3.12. This is thenpm initmoment.uv add ...installs five libraries into the project's own private environment and records each one — with its allowed version range — inpyproject.toml, whileuv.lockrecords 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.uv add --dev mypy ruff pytestinstalls tools you need while developing (type checker, linter, test runner) but that the shipped project itself does not depend on — the devDependencies idea.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 runhandles that every time.
# 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)"
- 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.
- 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.
- 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
[project]— the project's identity: its name, its version, and "this needs Python 3.12 or newer to run".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.[dependency-groups] dev— tools used only while developing (type checker, linter, test runner); they are not part of what the project ships.[tool.mypy] strict = true— run the mypy type checker in its strictest mode, so missing or wrong type hints are errors, not suggestions.- 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.
[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:
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.
| Option | Choose when | Avoid when | Typical cost |
|---|---|---|---|
| Notebook | Exploring data, plotting, one-off analysis, teaching yourself an API | Anything imported, scheduled, reviewed, or shipped | Hidden state; unreviewable diffs |
| Typed module + CLI | Anything run twice, by CI, or by a teammate | Throwaway exploration — ceremony slows thinking | A 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
- Define a class
Subscriptionthat inherits from Pydantic'sBaseModel. Each line inside states a field's name, its type, and its rules:customer_idmust match the pattern "a C followed by digits" (thatr"^C\d+$"is a regular expression saying exactly that);monthly_chargesmust be greater than 0 and less than 10,000 (gt/lt= greater-than / less-than);contract_typemay only be one of the three exact strings listed inLiteral[...];churnmust be a true/false value. - 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. - Build a
rawdictionary that imitates messy data arriving from outside: the charge is a string ("120.00"), churn is a number (1), the date is text. 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.model_dump_json()serializes that validated object back to tidy JSON, and we print it.- Finally, deliberately feed it bad data — a charge of −5. Pydantic raises a
ValidationError; theexceptblock catches it and prints the machine-readable description of what failed: which field, which rule, what it got ("Input should be greater than 0").
# 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"
- 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.
- 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.
- 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.
- 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.
- All at once. At each
awaitthe 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
fake_llm_callstands 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. Theasync defkeyword marks it as a pausable function: at eachawait, the event loop may set it aside and run something else.sequentialcalls 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.concurrentfirst createsasyncio.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.- The inner helper
boundedis the take-a-ticket wrapper: acquire the semaphore (async with sem), make the call, release automatically. 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.- 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.
# 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
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.
- 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.
- 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.
- 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
- Read the server address and model name from environment variables, falling back to a local Ollama server (
http://localhost:11434/v1) and thellama3.2model — so the script runs with no API key at all. summarizesends one POST request to the server's/chat/completionsendpoint, asking the model for a one-line summary of one ticket. Because the request isawaited, the event loop is free to run the other summarize calls while this one waits for the network.resp.raise_for_status()makes failure loud: if the server answered with an error code, stop here instead of quietly parsing garbage.- 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). maindefines three example tickets, then opens onehttpx.AsyncClientshared by all calls — one client means reused network connections, which is faster and kinder to the server than opening a fresh one per request.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.
# 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())
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.
- 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%.
- 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.
- 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.
- 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.
- 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.
| Group | Visitors | Converted | Conversion rate |
|---|---|---|---|
| Old page (A) | 420 | 55 | 13.10% |
| New page (B) | 410 | 66 | 16.10% |
| Both pages together | 830 | 121 | 14.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.
- 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.
- 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%).
- Write down the gap. B's rate minus A's rate: 13.90% − 13.81% = +0.09 points.
- 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.
- 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.
- 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.
- 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.
- 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.
| Route | What it does | p |
|---|---|---|
| Replay the counts | 100,000 pretend tests with both pages at 14.58% | 0.224 |
| Shuffle the labels | Deal the real 830 outcomes, 121 of them conversions, into groups of 420 and 410 at random, 20,000 times | 0.244 (exactly 0.238 when every possible split is counted) |
| The bell curve | The area beyond ±1.225 on a standard bell: 0.1102 on each side | 0.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
- 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.
- 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.
- Find the finish line. The test says "real" only when z passes 1.96.
- Measure from the bell's centre to the line. 1.96 − 1.225 = 0.735 wobbles to the right of the centre.
- 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.
- 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.
- 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.
- Add, then square. (0.9760 + 0.4187)² = 1.3947² = 1.9451.
- Divide by the lift squared. 1.9451 ÷ 0.03² = 1.9451 ÷ 0.0009 = 2,161.2.
- 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.
| Test | Visitors per page | One wobble | True gap in wobbles | Power, formula | Power, replay |
|---|---|---|---|---|---|
| The meeting, 13.1% vs 16.1% | 420 and 410 | 2.45 points | 1.225 | 0.231 | 0.231 |
| The plan, 13% vs 16% | 2,162 each | 1.07 points | 2.80 | 0.801 | 0.800 |
| Ten times the meeting | 4,200 and 4,100 | 0.77 points | 3.87 | 0.972 | 0.973 |
| The plan, if the true lift is only 1.5 points | 2,162 each | 1.05 points | 1.43 | 0.299 | 0.300 |
- 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.
- 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.
- 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.
- 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.
| Station | What V-0007 is here | The numbers |
|---|---|---|
| 1 · The warehouse row | One row of checkout_events: V-0007, page B, converted 1 | 1 of 830 rows; COUNT(DISTINCT visitor_id) is also 830 |
2 · GROUP BY variant | A 1 inside B's SUM(converted) | A: 420 rows, 55 conversions. B: 410 rows, 66 conversions |
3 · The .df() hand-off | Still inside the 66, now in pandas | conversions arrives as 66.0, a float64 column |
4 · run_ab_test(420, 55, 410, 66) | 1 ÷ 410 of B's rate | 0.244 points of 16.10%; the gap is 3.00 points |
| 5 · The verdict | A sliver of z | z = 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.
- 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.
- The fold.
GROUP BY variantturns 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. - The hand-off.
.df()brings the two rows into pandas. DuckDB'sSUMof an integer column is a 128-bit HUGEINT, which pandas stores as float64, so 66 arrives as 66.0. Cast with::BIGINTin the query, or withint()before the engine. - 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.
- 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.
- 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
| Scenario | Page B | z | p | Engine's verdict |
|---|---|---|---|---|
| The meeting as it happened | 66 of 410 | 1.225 | 0.220 | Do not ship |
| V-0007 did not buy | 65 of 410 | 1.13 | 0.259 | Do not ship |
| The same one-visitor flip at ten times the traffic | 659 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 B | 86 of 430 | 2.706 | 0.007 | Ship 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 runworks. 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.
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.
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 withpyproject.tomlanduv.lock; a teammate can clone anduv run pytestgreen in under two minutes- A
SettingsPydantic model loads config from environment variables (no hardcoded paths or keys anywhere) and fails loudly with a helpful message when one is missing report.pyqueries 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
"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
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"?