13A.6 Product Metrics, Experiments and Unit Economics

Ship & get hiredLesson 6 of 816,310 words8 parts
Module 13A · 0 of 8 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8

Modules 10A and 11A to 11C taught you to measure an LLM system and to run it cheaply. This lesson teaches you to run it as a business: which numbers tell you the product is working, how to test a change on real users without fooling yourself, what one successful task actually costs, what to charge, and how to roll a feature out without betting the company on a hunch. The through-line is that an LLM feature is a probabilistic system sold inside a business: its quality is a distribution, its cost is a distribution, and both move when the provider changes a model underneath you. The engineering is done in earlier modules; this lesson is the product judgement layer that turns those systems into something people pay for and trust.

What you'll learn

  • The metric tree for AI products: business outcome → usage → quality → experience → safety → cost, and how to pick a north-star metric and guardrail metrics without fooling yourself
  • How to instrument an AI feature: the event schema that joins product events to traces and eval cases, privacy-aware analytics, sampling, and the offline/online split
  • The six layers of metrics that matter, with concrete definitions per product shape (assistant, copilot, agent, document pipeline, voice), plus the extra metrics agents need (verified task success, steps per success, takeover rate, pass^k)
  • How to run experiments on LLM features honestly: what to randomise, the AI-specific traps (shared caches, novelty effects, silent model updates), holdouts, model-upgrade experiments, heterogeneous effects, and the decision memo
  • The data flywheel: production traffic → labelled cases → eval sets → better prompts and models, and the biases that corrupt it
  • Unit economics: cost per successful task (not per call), gross margin, pricing models, contractual SLAs for probabilistic features, cost caps as product features, and the product trade-off behind every cost lever
  • Rollout strategy: dogfood → private beta → staged rollout → general availability, with entry, success and exit criteria per stage
  • Roadmapping under uncertainty: assumption mapping, time-boxed experiments, and saying no

What you don't need

  • API keys or any model calls. Every code sample in this lesson is pure standard-library Python and runs offline. Where an experiment or a metric needs live traffic, the lesson shows you the arithmetic on numbers you already have (or fixtures you write).
  • A statistics background beyond means and percentages. The one formula that matters — the two-proportion sample-size calculation — is derived in plain English and implemented for you.
  • Modules 10A and 11A to 11C re-taught. This lesson links to their exact sections for eval methodology, experiment statistics, tracing, cost levers and the readiness checklist; it does not repeat them.

Setup

No installation is needed: all three ai_product modules in this lesson (metrics.py, experiment.py, unit_economics.py) use only the Python standard library, so they run on any Python 3.11+. If you are working inside a uv project (as the capstone lessons assume), copy the files into your ai_product/ package directory; otherwise save them anywhere and run them directly:

bash
python3 metrics.py events_sample.jsonl
python3 experiment.py demo
python3 unit_economics.py demo

The lesson's running example is the support copilot from lesson 13B.2: an agent that drafts reply suggestions for human support agents, with citations, tools and an approval gate. The same patterns apply to the document-intelligence app (13B.3) and the voice agent (13B.5); each capstone lesson points back here for its metrics and economics.


What you must be able to do after this lesson#

  • Build a metric tree and pick a north-star metric that passes the tests
  • Instrument events that join to traces and eval cases
  • Design an experiment for an LLM feature avoiding shared-cache and novelty traps
  • Compute cost per successful task instead of cost per call
  • Plan a staged rollout with entry and exit criteria

Why this matters for an AI engineer#

You'll hear these phrases in planning meetings, investor reviews and incident postmortems. Each one is a section of this lesson:

You'll hear... You'll understand it after...
"What's the north-star metric for this feature?" Part 1: the metric tree
"Thumbs-up is up 12% — ship it." 1.6 Goodhart's law for AI metrics
"Instrument the funnel before we launch." Part 2: instrumentation
"Acceptance rate, edit distance, escalation rate — which do we track?" Part 3: the six layers
"Let's A/B test the new prompt." Part 4: experimentation
"The experiment is only 40% powered." 4.3 Sample size, by hand
"Hold out 5% so we can measure the long-term effect." 4.8 Holdouts
"The provider shipped a new model snapshot — is it better?" 4.6 Shadow traffic, canaries and model-upgrade experiments
"How does production data become eval data?" Part 5: the data flywheel
"What does one resolved ticket cost us?" Part 6: unit economics
"Should we charge per seat, per task or per resolution?" 6.4 Pricing models
"Users are burning through the free tier — cap it?" 6.6 Cost caps as product features
"Dogfood first, or straight to beta?" Part 7: rollout
"The roadmap assumes GPT-7-class reasoning — risky." Part 8: roadmapping with uncertainty

Part 1: The metric tree for AI products#

1.1 Why AI features need their own metric tree#

A classic web feature has a fairly simple success shape: the user clicks, the server responds deterministically, and "it worked" is a boolean you can check in code. An LLM feature breaks that shape in three ways that change what you measure:

  1. Quality is a distribution, not a boolean. Two identical requests can produce a perfect answer and a fluent wrong one. "The feature works" is really "the feature works often enough, on the cases that matter" — which is why quality metrics (acceptance rate, eval scores, groundedness) sit inside the product metric tree, not beside it.
  2. Cost is coupled to quality. The cheapest configuration (small model, no reasoning, tight budgets) is also the least capable; the most capable configuration can cost 40× more per task (lesson 02.9, Part 6 shows the spread). You cannot optimise cost and quality independently, so the tree must show both and the trade-off between them.
  3. The ground moves. Providers ship new model snapshots, change prices and retire models on schedules you don't control (lesson 02.9, Part 8, lesson 11C.2). A metric that was green last quarter can drift without any code change on your side — which is why Part 5's flywheel and Part 4's experiments exist.

1.2 The six layers#

Draw the product's metrics as a tree. Each layer answers a different question, and a healthy product has numbers at every layer — not just the top.

flowchart TB
    BIZ["Business outcome<br/>resolved tickets, revenue influenced,<br/>time saved, cost per outcome"]
    USE["Product usage<br/>activation, retention, task completion,<br/>weekly active users of the feature"]
    QUAL["Quality<br/>acceptance rate, edit distance,<br/>groundedness, eval scores"]
    EXP["Experience<br/>latency percentiles, abandonment,<br/>clarifying-question rate, CSAT"]
    SAFE["Safety<br/>policy violations, escalations,<br/>PII leaks, injection successes"]
    COST["Cost<br/>cost per task / session / tenant,<br/>gross margin, spend vs budget"]
    BIZ --> USE --> QUAL --> EXP --> SAFE --> COST

Reading the tree top to bottom:

  • Business outcome — did the feature move the number the company cares about? For the support copilot: tickets resolved without a human agent (deflection rate, defined in lesson 10A.9), agent handle-time saved, or cost per resolved ticket. For the document app: documents processed straight-through without manual correction. For the voice agent: calls completed to a booked outcome.
  • Product usage — are people actually using it, repeatedly? Activation (first successful task), retention (week-2 return), task completion (did they finish what they started), and feature-level active use. Usage is necessary but not sufficient: a feature can be heavily used and worthless (see 1.5).
  • Quality — is the output good? The eval-side metrics of Modules 10A and 07 live here: acceptance rate (sent unedited), edit distance (how much the human changed), groundedness/citation precision, eval-suite scores, abstention correctness. These are the metrics that distinguish an AI product from a CRUD app.
  • Experience — how did it feel? Latency percentiles (p50/p95, not averages — lesson 11A.2, 2.3 explains why), abandonment mid-task, time-to-first-token, clarification loops, satisfaction.
  • Safety — did it stay inside the guardrails? Policy-violation rate, escalation-to-human rate, injection-attack success rate, PII leakage incidents, over-refusal rate. Owned deeply by Module 12; here they appear as product metrics with thresholds.
  • Cost — what did it cost to deliver? Cost per task, per session, per tenant, per successful task; gross margin; spend against budget. Part 6 builds this layer properly.

1.3 Choosing the north-star metric#

The north-star metric (also called the Overall Evaluation Criterion in experimentation writing — Kohavi, Tang and Xu's Trustworthy Online Controlled Experiments, Cambridge University Press 2020, devotes a chapter to it) has to satisfy four tests:

  1. It reflects customer value. If it goes up and users are actually worse off, it's the wrong metric. "Messages sent" goes up when the bot frustrates users into retrying.
  2. It is predictive of the business outcome. It should lead the revenue/retention number, not lag it by a quarter.
  3. It is actionable. Your team can move it deliberately. A metric nobody can influence is a weather report.
  4. It is simple enough to argue about. If two teams compute it differently, you don't have a metric, you have a debate.

Candidate north-stars per product shape:

Product shape Candidate north-star Why it works Trap to avoid
Support copilot (drafts for agents) Resolved tickets per agent-hour, or cost per resolved ticket Directly ties AI output to the support org's real bottleneck Counting "drafts accepted" — agents accept bad drafts to clear the queue
Document intelligence (extract/classify) Straight-through processing rate: documents shipped with zero manual correction Captures both accuracy and review cost in one number Field-level accuracy alone — a 99% field accuracy can still mean every document needs a human glance
Consumer assistant / chat Weekly tasks completed (a task = a user goal reached, not a message sent) Rewards resolution over engagement Session length or messages per session — engagement metrics that reward frustration
Voice agent (bookings, triage) Tasks completed to a verified outcome (booking confirmed, issue logged correctly) The outcome is checkable against a system of record Call containment rate alone — containing a call badly is worse than transferring it
Proactive suggestions (07.6's promise, owned by 13A.1) Accepted-suggestion rate × downstream task success Measures whether suggestions were wanted and right, not just shown Suggestion impressions — the purest vanity metric in AI

1.4 Leading vs lagging indicators#

  • Leading indicators move first and predict the outcome: daily active users of the feature, draft acceptance rate, task completion rate, p95 latency. You steer by these.
  • Lagging indicators confirm value after the fact: monthly resolved-ticket count, quarter revenue, NPS, retention at day 30.

An AI feature's dangerous failure mode is optimising a lagging indicator with a proxy that broke. If your north-star is "monthly resolutions" and your dashboard shows "drafts generated", you've built a lagging goal on a leading proxy — and the proxy will be gamed first. Keep the chain explicit: leading metric → mechanism → lagging outcome, and check that the links still hold (lesson 10A.9, 1.3 is the offline/online version of the same check).

1.5 Vanity metrics and "AI usage"#

A vanity metric is a number that goes up when things are going well and when things are going badly — it can't distinguish them. Classic web vanity metrics: pageviews, registered users, app installs. The AI-specific additions:

Tempting number Why it's vanity for an AI feature
Total tokens processed / total generations Costs money and can mean users are frustrated and retrying
"AI feature" pageviews or demo plays Interest isn't usage; a slick demo can coexist with a useless product
Raw thumbs-up count Grows with traffic; says nothing about the rate or the denominator
Model benchmark score (MMLU etc.) Measures the model, not your product — lesson 02.9, 7.6 is dedicated to this
Cost savings "estimated" by the vendor A claim, not a measurement — until you've measured the baseline yourself

"AI usage" deserves special mention because it's the metric most likely to be proposed in your first planning meeting. Usage is real — if nobody uses the feature, nothing else matters — but usage is not value. A support agent who opens the copilot on every ticket because the UI nags them generates usage and zero benefit; worse, if the drafts are bad and they learn to ignore them, you've trained the exact behaviour you don't want. Track usage as the top of the funnel and pair it with the layers below: of the agents who tried it, how many came back (retention), of the drafts shown, how many were accepted (quality), of the accepted drafts, did resolution time actually fall (outcome). Lesson 13A.1 covers the product-side version of this trap; this lesson owns the measurement side.

A useful test from Lean Analytics (Croll and Yoskovitz, O'Reilly 2013): a good metric is comparative (you can compare it to last week, to a target, to a competitor), understandable (a new hire gets it in ten seconds), a ratio or rate (per what?) and one that changes the way you behave (someone can act on it). This lesson adds a fifth habit of its own: pair the number with the story, with reviewed sessions beside the dashboard. "1.2M tokens today" fails the ratio test; "cost per resolved ticket, down 8% WoW" passes all four.

1.6 Goodhart's law for AI metrics#

For AI products the law bites in specific, predictable ways:

  • Thumbs-up rate as a target. Optimising for approval produces sycophantic, non-committal answers — the model (and the prompt tuned toward the metric) learns that "that's a great question!" pleases raters. Worse, users sometimes rate up to make the interaction stop, or rate down reflexively on long answers regardless of quality. Lesson 10A.9, 2.5 quantifies the selection bias: satisfied users respond ~2% of the time, dissatisfied ~15%, so the raw thumbs-up rate lies even before anyone gamed it.
  • "AI usage" as a target. If the KPI is "agents using the copilot", the rational move is nags, defaults-on, and measuring opens rather than value. Usage grows; value doesn't.
  • Resolution rate as a target. A copilot can "resolve" a ticket by giving a confident wrong answer that makes the customer go away — resolution up, churn up next month. Pair the metric with a quality guardrail and a downstream check (reopen rate, CSAT on resolved tickets).
  • Edit distance as a target. Minimising how much humans edit sounds right, but the cheapest way to reduce edits is to make drafts vaguer — a generic "Thanks for reaching out, we're looking into it" needs no edits and helps nobody. Pair edit distance with acceptance-without-escalation and outcome metrics.
  • Cost per task as a target. Pure cost pressure produces the failure modes of Part 6: smaller models on hard queries, truncated contexts, disabled review. The defence is measuring cost per successful task, which can't be improved by failing more often.

The general defence has three parts: (1) never let a single metric be the target — always a north-star plus guardrails; (2) audit the metric itself quarterly — is it still measuring what you think?; (3) keep a qualitative channel (reviewed sessions, support notes) reading the same traffic, because the number will always lag the story.

Anti-pattern What it looks like What it costs you
Dashboard of 40 metrics, no north-star Weekly metrics review becomes a tour No shared definition of "better"; every argument is anecdote
North-star = vendor's claimed saving "Copilot saves $X/agent/month" from the sales deck Budget allocated on a number nobody measured; first real measurement embarrasses everyone
Guardrails set after launch Quality regresses for a month before anyone notices The regression was visible in data you already collected
Metric defined per team, not per product Support counts "resolution", engineering counts "ok outcome", finance counts "cost" Three numbers, zero decisions
Experiment read on the north-star alone Treatment wins engagement, loses quality — nobody checked You shipped a feature users love and regret
Cost metric excludes failures "Cost per call is $0.01" while 40% of calls are retried Real cost is 67% higher; pricing built on the wrong denominator

What this means for you as an engineer: your first deliverable on any AI feature isn't code — it's a one-page metric spec: the six layers, the north-star, the guardrails with thresholds, and the event schema that feeds them (Part 2). Write it before the second sprint, not after the launch retrospective. 3.7 ends with a copy-ready template for exactly this document.


Part 2: Instrumentation — joining product events to traces and evals#

2.1 Three event layers, one join key#

An AI feature emits events at three different layers, and the whole point of instrumentation is that they join:

flowchart LR
    subgraph client ["Client / UX layer (13A.2, 13A.3)"]
        E1["wire events:<br/>status, token, tool_start,<br/>citation, done, error"]
        E2["feedback events:<br/>thumbs, edit, report,<br/>approval decisions"]
    end
    subgraph app ["Application layer (this lesson)"]
        E3["product events:<br/>task_started, task_completed,<br/>draft_accepted, escalated"]
    end
    subgraph ops ["Ops layer (Modules 11A to 11C)"]
        E4["traces & spans:<br/>model calls, retrieval,<br/>tool calls, costs"]
        E5["eval cases:<br/>labelled failures,<br/>judge scores"]
    end
    E1 --> E3
    E2 --> E3
    E3 -- "request_id / trace_id" --> E4
    E3 -- "case_id / event_id" --> E5
  • Wire events (lesson 13A.2) are the real-time stream between server and UI — they exist to render the answer, not to be stored.
  • Feedback events (lesson 13A.3's feedback.py) are deliberate user signals: thumbs, ratings, edit records, report reasons.
  • Product events (this lesson) are the analytics record: "a task started", "a task completed with outcome ok", "a draft was accepted unedited", "the user escalated to a human". They are sparse, deliberate and cheap to store — one row per task, not per token.
  • Traces (lesson 11A.1) hold the per-call detail: tokens, cost, latency, model version, prompt version.
  • Eval cases (lesson 10A.2) hold the labelled examples that become regression tests.

The join keys are what make this a system rather than three log files: request_id/trace_id links a product event to its trace; session_id links events within a conversation; case_id/event_id links a production failure to the eval case it generated; experiment_id/variant links a metric to the change that caused it. Lesson 11A.1, 8.1 lists the attribution attributes that must be on every span from day one — feature, tenant_hash, user_hash, session_id, prompt_name, prompt_version, model_resolved, experiment_id/variant — and the same keys belong on product events. If you didn't record variant on the day of the experiment, the experiment is unrecoverable.

2.2 The product event schema#

ai_product/metrics.py (below) consumes a deliberately small JSONL schema — the same one the capstone builds emit:

Field Type Required Notes
event string yes task_started, task_completed, answer_shown, draft_accepted, draft_edited, escalated, abandoned, feedback
feature string yes grouping key: support_copilot, doc_intel, voice_agent
variant string no experiment arm; - or absent outside experiments
outcome string on task_completed ok, failed, refused — the field cost-per-success divides by. Abandonment is not an outcome: a task that was abandoned never completed, so it emits the standalone abandoned event instead
session_id string yes joins events within one conversation/task
user_hash string yes hash, never a raw user id (12.4)
tenant_hash string yes same, per customer
latency_ms number on answer_shown task-start → first useful output (see 13A.2's perceived-latency work)
edit_distance number 0–1 on draft_edited normalised Levenshtein; or send before/after and let the aggregator compute it
cost_usd number optional attributed cost copied from the cost record (03.7, 5.1)
judge_score number 0–1 optional sampled-judge score (10A.9, 3.1)
day string optional YYYY-MM-DD bucket for trend reports

Design choices worth defending:

  • Events are per-task, not per-request. A "task" is the user's job (draft a reply, process a document, complete a booking call). A task may take several model calls, retries and tool calls — all of which live in the trace. The product event says what happened to the task, which is what the metric tree measures.
  • outcome is a closed enum. ok must mean "the task reached a usable result", defined per feature in the metric spec (1.2). For the support copilot, ok = a draft was produced and the case resolved without rework — not "the model returned text". A sloppy outcome poisons every rate computed from it, including cost-per-success (6.2).
  • Measurement fields ride on exactly one event per task. Emit latency_ms, cost_usd, judge_score and edit_distance on a single event per task — the answer_shown or task_completed event, whichever your spec names — never on several. The aggregator appends every occurrence it sees: the same cost on both answer_shown and task_completed is counted twice, inflating both the latency percentiles' denominators and cost-per-task. If an emitter gets this wrong, the fix is in the emitter, not the aggregator — silently deduplicating by session_id would hide real double-billing bugs you want to see.

2.3 ai_product/metrics.py — the aggregator#

The module is pure standard library and reads the JSONL schema above. It computes the scorecard per (feature, variant) slice — and per day with --by day:

python
# ai_product/metrics.py — product-metric aggregator for AI features.
#
# Pure standard library. Reads a JSONL stream of *product* events (the layer
# above the 13A.2 wire contract and the 13A.3 feedback events) and reports the
# product metrics: task completion, draft acceptance, edit distance,
# escalation, abandonment and latency percentiles.
#
# One JSON object per line. Fields used:
#   feature        str   which feature produced the event (grouping key)
#   variant        str   experiment arm, if any (grouping key)
#   event          str   task_started | task_completed | answer_shown |
#                        draft_accepted | draft_edited | escalated |
#                        abandoned | feedback
#   outcome        str   ok | failed | refused            (on task_completed)
#                        — abandonment is the standalone `abandoned` event,
#                        never an outcome (an abandoned task never completes)
#   session_id     str   joins repeated events of one conversation
#   user_hash      str   privacy-preserving user id (never a raw id)
#   tenant_hash    str   privacy-preserving tenant id
#   latency_ms     float time from task start to first useful output
#   edit_distance  float 0..1 normalised Levenshtein (0 = sent unedited);
#                        OR send "before"/"after" strings and we compute it
#   cost_usd       float billed cost attributed to this event (optional)
#   judge_score    float sampled-judge quality score 0..1 (optional)
#   day            str   YYYY-MM-DD bucket (optional; defaults to "all")
#
# Usage:
#     python metrics.py events.jsonl                 # report per feature+variant
#     python metrics.py events.jsonl --by day        # also split by day
from __future__ import annotations

import argparse
import json
import sys
from collections import defaultdict
from dataclasses import dataclass, field
from pathlib import Path


def levenshtein(a: str, b: str) -> int:
    """Edit distance between two strings (insert/delete/substitute = 1)."""
    if a == b:
        return 0
    if not a:
        return len(b)
    if not b:
        return len(a)
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1,
                           prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]


def normalised_edit_distance(before: str, after: str) -> float:
    """0.0 = identical, 1.0 = completely rewritten. Length-normalised so a
    one-word fix in a long draft doesn't look like a rewrite."""
    denom = max(len(before), len(after), 1)
    return levenshtein(before, after) / denom


def percentile(values: list[float], p: float) -> float | None:
    """p-th percentile, 0 <= p <= 100, by linear interpolation between the
    two closest ranks — the same 'type 7' method numpy and R use by default.
    n=4, p=50 -> average of the two middle values."""
    if not values:
        return None
    xs = sorted(values)
    if len(xs) == 1:
        return xs[0]
    rank = (len(xs) - 1) * p / 100.0
    lo, hi = int(rank), min(int(rank) + 1, len(xs) - 1)
    frac = rank - lo
    return xs[lo] * (1 - frac) + xs[hi] * frac


@dataclass
class Bucket:
    """Counters for one (feature, variant[, day]) slice of traffic."""
    started: int = 0
    completed: int = 0
    ok: int = 0
    failed: int = 0
    refused: int = 0
    abandoned: int = 0
    escalated: int = 0
    accepted_unedited: int = 0      # draft_accepted events
    edited: int = 0                 # draft_edited events
    edit_distances: list[float] = field(default_factory=list)
    latencies: list[float] = field(default_factory=list)
    costs: list[float] = field(default_factory=list)
    judge_scores: list[float] = field(default_factory=list)
    sessions: set = field(default_factory=set)
    users: set = field(default_factory=set)

    def add(self, ev: dict) -> None:
        kind = ev.get("event", "")
        if kind == "task_started":
            self.started += 1
        elif kind == "task_completed":
            self.completed += 1
            outcome = ev.get("outcome", "ok")
            if outcome == "ok":
                self.ok += 1
            elif outcome == "refused":
                self.refused += 1
            else:
                self.failed += 1
        elif kind == "escalated":
            self.escalated += 1
        elif kind == "abandoned":
            self.abandoned += 1
        elif kind == "draft_accepted":
            self.accepted_unedited += 1
        elif kind == "draft_edited":
            self.edited += 1
            if "edit_distance" in ev:
                self.edit_distances.append(float(ev["edit_distance"]))
            elif "before" in ev and "after" in ev:
                self.edit_distances.append(
                    normalised_edit_distance(str(ev["before"]), str(ev["after"])))
        if ev.get("latency_ms") is not None:
            self.latencies.append(float(ev["latency_ms"]))
        if ev.get("cost_usd") is not None:
            self.costs.append(float(ev["cost_usd"]))
        if ev.get("judge_score") is not None:
            self.judge_scores.append(float(ev["judge_score"]))
        if ev.get("session_id"):
            self.sessions.add(ev["session_id"])
        if ev.get("user_hash"):
            self.users.add(ev["user_hash"])


def rate(num: float, den: float) -> float | None:
    return num / den if den else None


def fmt_pct(x: float | None) -> str:
    return f"{x:6.1%}" if x is not None else "   n/a"


def fmt_num(x: float | None, nd: int = 1) -> str:
    return f"{x:,.{nd}f}" if x is not None else "n/a"


def report(bucket: Bucket, label: str) -> list[str]:
    """One slice -> the product scorecard. Rates are per *started* task
    unless the name says otherwise; see the lesson for why that choice
    matters (denominator choice is a product decision, not a detail)."""
    drafts = bucket.accepted_unedited + bucket.edited
    cost_total = sum(bucket.costs)
    lines = [
        f"--- {label} ---",
        f"  tasks started        {bucket.started:>8,}   sessions {len(bucket.sessions):>7,}   users {len(bucket.users):>7,}",
        f"  completion rate      {fmt_pct(rate(bucket.ok, bucket.started))}   (ok {bucket.ok:,} / started {bucket.started:,})",
        f"  failure rate         {fmt_pct(rate(bucket.failed + bucket.refused, bucket.started))}",
        f"  abandonment rate     {fmt_pct(rate(bucket.abandoned, bucket.started))}",
        f"  escalation rate      {fmt_pct(rate(bucket.escalated, bucket.completed))}   (per completed task)",
        f"  acceptance (unedited){fmt_pct(rate(bucket.accepted_unedited, drafts))}   ({bucket.accepted_unedited:,} accepted / {drafts:,} drafts)",
        f"  mean edit distance   {fmt_num(rate(sum(bucket.edit_distances), len(bucket.edit_distances)), 3)}   (0 = sent as-is; n={len(bucket.edit_distances):,})",
        f"  latency p50/p95      {fmt_num(percentile(bucket.latencies, 50), 0)} / {fmt_num(percentile(bucket.latencies, 95), 0)} ms",
    ]
    if bucket.judge_scores:
        lines.append(
            f"  judge score mean     {fmt_num(rate(sum(bucket.judge_scores), len(bucket.judge_scores)), 3)}   (n={len(bucket.judge_scores):,} sampled)")
    if bucket.costs:
        per_ok = cost_total / bucket.ok if bucket.ok else None
        lines.append(
            f"  cost / started task  ${fmt_num(rate(cost_total, bucket.started), 4)}   cost / ok task  ${fmt_num(per_ok, 4)}")
    return lines


def aggregate(events_path: str, by_day: bool = False) -> None:
    groups: dict[tuple, Bucket] = defaultdict(Bucket)
    with open(events_path) as fh:
        for lineno, line in enumerate(fh, 1):
            line = line.strip()
            if not line:
                continue
            try:
                ev = json.loads(line)
            except json.JSONDecodeError as exc:
                sys.exit(f"{events_path}:{lineno}: bad JSON: {exc}")
            feature = ev.get("feature", "unknown")
            variant = ev.get("variant", "-")
            day = ev.get("day", "all") if by_day else ""
            groups[(feature, variant, day)].add(ev)

    if not groups:
        sys.exit(f"{events_path}: no events")

    # Group order: feature, then variant, then day — stable and readable.
    for key in sorted(groups):
        feature, variant, day = key
        label = f"feature={feature}  variant={variant}" + (f"  day={day}" if by_day else "")
        print("\n".join(report(groups[key], label)))


def main() -> None:
    ap = argparse.ArgumentParser(
        description="Aggregate product events (JSONL) into the AI-feature scorecard.")
    ap.add_argument("events", help="JSONL file of product events")
    ap.add_argument("--by", choices=["day"], help="split the report by day")
    args = ap.parse_args()
    aggregate(args.events, by_day=args.by == "day")


if __name__ == "__main__":
    main()

The aggregator makes two percentile choices explicit, because "p95" means different things in different tools:

  • Percentile method: linear interpolation between the two closest ranks — the same "type 7" default numpy and R use. With latencies [4200, 6100], p50 is 5150, not 4200 or 6100. Document the method in your metric spec; a dashboard that uses nearest-rank will disagree with yours by a few percent and start arguments.
  • Denominators: completion rate divides by started tasks (the user-facing denominator); escalation rate divides by completed tasks (an escalation is a property of finished work). Mixing denominators inside one report is the most common way metric reviews go wrong — the report prints the denominator next to every rate for exactly this reason.

2.4 Run it on the sample events#

Save the following as events_sample.jsonl next to metrics.py — 34 synthetic events for a small pilot of the support copilot and the document app. Three variants' worth of traffic is too small to mean anything statistically (Part 4 is about that), but it exercises every field in the schema, including the before/after edit-distance path:

jsonl
{"event": "task_started", "feature": "support_copilot", "variant": "control", "session_id": "s001", "user_hash": "u1a", "tenant_hash": "t_acme", "day": "2026-11-03"}
{"event": "answer_shown", "feature": "support_copilot", "variant": "control", "session_id": "s001", "user_hash": "u1a", "tenant_hash": "t_acme", "latency_ms": 4200, "cost_usd": 0.0112, "day": "2026-11-03"}
{"event": "draft_accepted", "feature": "support_copilot", "variant": "control", "session_id": "s001", "user_hash": "u1a", "tenant_hash": "t_acme", "day": "2026-11-03"}
{"event": "task_completed", "feature": "support_copilot", "variant": "control", "session_id": "s001", "user_hash": "u1a", "tenant_hash": "t_acme", "outcome": "ok", "day": "2026-11-03"}
{"event": "task_started", "feature": "support_copilot", "variant": "control", "session_id": "s002", "user_hash": "u2b", "tenant_hash": "t_acme", "day": "2026-11-03"}
{"event": "answer_shown", "feature": "support_copilot", "variant": "control", "session_id": "s002", "user_hash": "u2b", "tenant_hash": "t_acme", "latency_ms": 6100, "cost_usd": 0.0131, "day": "2026-11-03"}
{"event": "draft_edited", "feature": "support_copilot", "variant": "control", "session_id": "s002", "user_hash": "u2b", "tenant_hash": "t_acme", "before": "Hi, your refund of $45.00 was issued on Nov 1 and should arrive within 5 business days.", "after": "Hi Priya, your $45.00 refund was issued on Nov 1 and should arrive by Nov 8 at the latest.", "day": "2026-11-03"}
{"event": "task_completed", "feature": "support_copilot", "variant": "control", "session_id": "s002", "user_hash": "u2b", "tenant_hash": "t_acme", "outcome": "ok", "day": "2026-11-03"}
{"event": "task_started", "feature": "support_copilot", "variant": "control", "session_id": "s003", "user_hash": "u3c", "tenant_hash": "t_beta", "day": "2026-11-03"}
{"event": "answer_shown", "feature": "support_copilot", "variant": "control", "session_id": "s003", "user_hash": "u3c", "tenant_hash": "t_beta", "latency_ms": 3800, "cost_usd": 0.0098, "day": "2026-11-03"}
{"event": "escalated", "feature": "support_copilot", "variant": "control", "session_id": "s003", "user_hash": "u3c", "tenant_hash": "t_beta", "day": "2026-11-03"}
{"event": "task_completed", "feature": "support_copilot", "variant": "control", "session_id": "s003", "user_hash": "u3c", "tenant_hash": "t_beta", "outcome": "failed", "day": "2026-11-03"}
{"event": "task_started", "feature": "support_copilot", "variant": "treatment", "session_id": "s004", "user_hash": "u4d", "tenant_hash": "t_acme", "day": "2026-11-03"}
{"event": "answer_shown", "feature": "support_copilot", "variant": "treatment", "session_id": "s004", "user_hash": "u4d", "tenant_hash": "t_acme", "latency_ms": 3900, "cost_usd": 0.0124, "day": "2026-11-03"}
{"event": "draft_accepted", "feature": "support_copilot", "variant": "treatment", "session_id": "s004", "user_hash": "u4d", "tenant_hash": "t_acme", "day": "2026-11-03"}
{"event": "task_completed", "feature": "support_copilot", "variant": "treatment", "session_id": "s004", "user_hash": "u4d", "tenant_hash": "t_acme", "outcome": "ok", "day": "2026-11-03"}
{"event": "task_started", "feature": "support_copilot", "variant": "treatment", "session_id": "s005", "user_hash": "u5e", "tenant_hash": "t_gamma", "day": "2026-11-03"}
{"event": "answer_shown", "feature": "support_copilot", "variant": "treatment", "session_id": "s005", "user_hash": "u5e", "tenant_hash": "t_gamma", "latency_ms": 5800, "cost_usd": 0.0140, "day": "2026-11-03"}
{"event": "draft_edited", "feature": "support_copilot", "variant": "treatment", "session_id": "s005", "user_hash": "u5e", "tenant_hash": "t_gamma", "before": "Your warranty covers manufacturing defects for 24 months from purchase.", "after": "Your warranty covers manufacturing defects for 24 months from the purchase date; accidental damage is not covered.", "day": "2026-11-03"}
{"event": "task_completed", "feature": "support_copilot", "variant": "treatment", "session_id": "s005", "user_hash": "u5e", "tenant_hash": "t_gamma", "outcome": "ok", "day": "2026-11-03"}
{"event": "task_started", "feature": "support_copilot", "variant": "treatment", "session_id": "s006", "user_hash": "u6f", "tenant_hash": "t_beta", "day": "2026-11-04"}
{"event": "abandoned", "feature": "support_copilot", "variant": "treatment", "session_id": "s006", "user_hash": "u6f", "tenant_hash": "t_beta", "day": "2026-11-04"}
{"event": "task_started", "feature": "support_copilot", "variant": "treatment", "session_id": "s007", "user_hash": "u7g", "tenant_hash": "t_acme", "day": "2026-11-04"}
{"event": "answer_shown", "feature": "support_copilot", "variant": "treatment", "session_id": "s007", "user_hash": "u7g", "tenant_hash": "t_acme", "latency_ms": 4400, "cost_usd": 0.0118, "day": "2026-11-04"}
{"event": "draft_accepted", "feature": "support_copilot", "variant": "treatment", "session_id": "s007", "user_hash": "u7g", "tenant_hash": "t_acme", "day": "2026-11-04"}
{"event": "task_completed", "feature": "support_copilot", "variant": "treatment", "session_id": "s007", "user_hash": "u7g", "tenant_hash": "t_acme", "outcome": "ok", "day": "2026-11-04"}
{"event": "task_started", "feature": "doc_intel", "variant": "-", "session_id": "d001", "user_hash": "u8h", "tenant_hash": "t_acme", "day": "2026-11-04"}
{"event": "answer_shown", "feature": "doc_intel", "variant": "-", "session_id": "d001", "user_hash": "u8h", "tenant_hash": "t_acme", "latency_ms": 12400, "cost_usd": 0.0410, "judge_score": 0.91, "day": "2026-11-04"}
{"event": "task_completed", "feature": "doc_intel", "variant": "-", "session_id": "d001", "user_hash": "u8h", "tenant_hash": "t_acme", "outcome": "ok", "day": "2026-11-04"}
{"event": "task_started", "feature": "doc_intel", "variant": "-", "session_id": "d002", "user_hash": "u9i", "tenant_hash": "t_beta", "day": "2026-11-04"}
{"event": "answer_shown", "feature": "doc_intel", "variant": "-", "session_id": "d002", "user_hash": "u9i", "tenant_hash": "t_beta", "latency_ms": 9800, "cost_usd": 0.0375, "judge_score": 0.72, "day": "2026-11-04"}
{"event": "task_completed", "feature": "doc_intel", "variant": "-", "session_id": "d002", "user_hash": "u9i", "tenant_hash": "t_beta", "outcome": "ok", "day": "2026-11-04"}
{"event": "task_started", "feature": "doc_intel", "variant": "-", "session_id": "d003", "user_hash": "u10j", "tenant_hash": "t_gamma", "day": "2026-11-04"}
{"event": "task_completed", "feature": "doc_intel", "variant": "-", "session_id": "d003", "user_hash": "u10j", "tenant_hash": "t_gamma", "outcome": "failed", "day": "2026-11-04"}

Then run it:

bash
python3 metrics.py events_sample.jsonl
Output31 lines
--- feature=doc_intel  variant=- ---
  tasks started               3   sessions       3   users       3
  completion rate       66.7%   (ok 2 / started 3)
  failure rate          33.3%
  abandonment rate       0.0%
  escalation rate        0.0%   (per completed task)
  acceptance (unedited)   n/a   (0 accepted / 0 drafts)
  mean edit distance   n/a   (0 = sent as-is; n=0)
  latency p50/p95      11,100 / 12,270 ms
  judge score mean     0.815   (n=2 sampled)
  cost / started task  $0.0262   cost / ok task  $0.0393
--- feature=support_copilot  variant=control ---
  tasks started               3   sessions       3   users       3
  completion rate       66.7%   (ok 2 / started 3)
  failure rate          33.3%
  abandonment rate       0.0%
  escalation rate       33.3%   (per completed task)
  acceptance (unedited) 50.0%   (1 accepted / 2 drafts)
  mean edit distance   0.433   (0 = sent as-is; n=1)
  latency p50/p95      4,200 / 5,910 ms
  cost / started task  $0.0114   cost / ok task  $0.0170
--- feature=support_copilot  variant=treatment ---
  tasks started               4   sessions       4   users       4
  completion rate       75.0%   (ok 3 / started 4)
  failure rate           0.0%
  abandonment rate      25.0%
  escalation rate        0.0%   (per completed task)
  acceptance (unedited) 66.7%   (2 accepted / 3 drafts)
  mean edit distance   0.377   (0 = sent as-is; n=1)
  latency p50/p95      4,400 / 5,660 ms
  cost / started task  $0.0095   cost / ok task  $0.0127

The draft_edited events carry before/after text; the aggregator computed the normalised edit distances (0.433 and 0.377) itself. In production you'd more likely send the precomputed edit_distance float — the same number, computed client-side where the strings already live.

2.5 Privacy-aware analytics#

Product events are another copy of user data, and lesson 12.4 owns the full treatment. The rules that matter here:

  • Hash identifiers at the edge. user_hash/tenant_hash are salted hashes (or keyed IDs from your identity system), never raw emails or account IDs. The hash lets you count distinct users and join sessions without the analytics store holding PII.
  • Never send content you don't need. The event schema has no prompt, answer, ticket_text or document field — deliberately. If a failure needs content for debugging, that's what the trace is for, under its own retention rules (12.4, 1.3); product analytics gets the outcome, not the text.
  • before/after draft text is the exception that proves the rule. Edit-distance events carry user-visible draft text — the minimum needed to compute the metric. Send the precomputed edit_distance float when you can; keep raw text only if your privacy review approves it, with the same retention and deletion propagation as traces (12.4, 1.4).
  • Consent and purpose. Product analytics is a different purpose from providing the service; where consent is required (GDPR-style regimes), the analytics pipeline is part of the consent surface, and users must be able to opt out without losing the feature.
  • Retention. Product events age out faster than traces: raw events 90 days, aggregates forever. Write the retention schedule down (lesson 11C.4 owns data lifecycle) — "we'll decide later" means "keep forever".

2.6 Sampling, dashboards and the offline/online split#

  • Sampling. At low volume (B2B tools, internal features) record every event — the data is cheap and the slices are thin. At high volume (consumer chat), sample deterministically by user_hash so a user's events are all-in or all-out (this keeps per-user metrics unbiased and makes experiment assignment consistent — 4.2 relies on it). Sampled-judge scoring (10A.9, 3.1) is the same idea applied to expensive quality measurement: judge 1–5% of tasks, weight back up, report the confidence interval.
  • Dashboards at three altitudes. Exec: north-star + guardrails, weekly. Product: the diagnostic layer — acceptance, edit distance, escalation, abandonment, by slice. Engineering: the system layer — latency percentiles, cost per task, error rates (lesson 11A.2 owns this dashboard). If a number appears on two dashboards with different definitions, fix the definition, not the dashboard.
  • The offline/online split. Offline metrics (eval suites on curated sets) tell you the system can be good; online metrics (production events) tell you it is being good for real users, on real traffic, today. Lesson 10A.9, Part 1 owns the taxonomy and the alignment check. The product-level rule: every offline regression gate needs a corresponding online metric, or you're optimising for a number that stopped predicting the real one.

What this means for you as an engineer: instrumentation is a day-one task, not a launch-week task. The event schema above is deliberately small enough to implement in an afternoon — but every week you ship without it, you permanently lose the data you needed to answer next month's questions.


Part 3: The six layers of metrics that matter#

Part 1 gave you the tree; this part gives you the working definitions — what each metric is, how to compute it, what a good value looks like, and which trap it hides. Every metric below is computable from the 2.2 event schema plus the eval/tracing layers it links to.

3.1 Business outcome layer#

Metric Definition Data source Trap
Deflection rate Share of contacts resolved without a human agent Ticket system + task_completed.outcome=ok Deflecting by giving up early or wrong answers — pair with reopen rate
Cost per resolved outcome Total feature cost ÷ verified resolutions cost records (11A.1, 8.2) ÷ outcome events Denominator must be verified resolutions, not "answer shown"
Time saved Baseline handle time − actual handle time, per task HR/ticket timestamps before and after launch Measuring against an imagined baseline — measure the baseline first; no earlier lesson covers this, so do it in week 0
Revenue influenced Revenue on journeys where the feature participated Attribution model you define and document Last-touch attribution flattery — declare the model, don't fudge it

3.2 Product usage layer#

Metric Definition Why it matters for AI
Activation % of eligible users completing their first successful task within N days of exposure AI features die at activation: a confusing first answer teaches users to never return
Feature retention % of activated users returning in week 2 / week 4 The honest quality signal — users return to what works
Task completion task_completed.ok ÷ task_started Separates "opened it" from "finished it"; abandonment mid-answer is the silent killer
Sessions per task How many conversations a task takes AI-specific friction: users re-asking because the first answer missed
Coverage % of eligible traffic where the feature is offered A copilot used on 30% of tickets measures a different product than one on 90%

3.3 Quality layer#

This is where AI metrics stop resembling web metrics. The eval methodology is Module 10A's; the product-facing definitions:

Metric Definition Notes
Acceptance rate (unedited) draft_accepted ÷ (draft_accepted + draft_edited) The headline "did they use it as-is" number. Pair with edit distance — "accepted after heavy edits" isn't acceptance
Edit distance Mean normalised Levenshtein between draft and sent version 0 = untouched. Rising distance = drafts getting worse or users getting pickier — check which
Groundedness / citation precision Share of answer claims supported by retrieved sources 10A.6, 3.1 owns the offline version; online it's a sampled-judge metric
Eval-suite score The regression suite's pass rate on the production prompt/model config Offline metric used as an online guardrail — run nightly, alert on drop (10A.8)
Abstention correctness Right-to-say-"I don't know" rate on unanswerable inputs 10A.6 owns the 2×2 matrix; product view: abstention that annoys vs hallucination that misleads
Override/escalation rate Humans rejecting or escalating AI output Rising escalation can mean quality dropped or the autonomy dial was set too high (13A.3)

3.4 Experience layer#

Metric Definition Notes
TTFT / latency p50/p95 Time to first useful token/output, and total task time Percentiles, not means — 11A.2, 2.3; p95 is what your unluckiest users feel
Abandonment rate abandoned ÷ task_started Mid-stream abandonment is an experience metric and a cost metric (you paid for tokens nobody read)
Clarification loops Questions asked ÷ tasks Too many = ambiguity failures (13A.4); zero = the feature guesses dangerously
Perceived speed User-reported or behavioural proxy (scroll-up, immediate re-ask) 13A.2 owns the design side

3.5 Safety layer#

Metric Definition Notes
Policy violation rate Outputs tripping guardrail/policy checks ÷ outputs Module 12 owns detection; here it's a product threshold
Injection success rate Retrieved-content attacks that changed behaviour ÷ probes Measured by red-team probes and canary strings (12.8)
PII leakage incidents Confirmed leaks ÷ period Near-zero tolerance; one incident is a SEV, not a metric
Over-refusal rate Benign requests refused ÷ benign requests The safety-quality trade-off made visible — a guardrail that refuses everything is safe and useless
Escalation-to-human rate Share of tasks handed to a person Product metric and cost metric: escalations are the expensive path

3.6 Cost layer#

Covered in depth in Part 6. The product-level metrics: cost per task, cost per successful task, cost per session, cost per tenant, gross margin, spend vs budget — all computable from cost_usd on events plus the cost records of 03.7.

3.6a Metrics specific to agents and long-running tasks#

An agent (a model that chooses tools across several steps) changes what "a task" is, so a few extra product metrics earn their place. The eval-side definitions (trajectory grading, pass@k and pass^k) are 10A.7, Part 4 and 10A.7, Part 5; the product view:

Metric Definition What it tells you Trap
Task success (verified) Tasks whose end state is correct in the system of record ÷ tasks started The only success number that counts for an agent; the agent's own "done" message is not evidence Counting self-reported completion (08A.14's false completion)
Steps and tool calls per success Mean and p95 of model turns and tool calls on successful tasks Efficiency, and early warning of loops: a rising p95 precedes a cost spike Optimising the mean while a tail of runaway runs grows
Budget-trip rate Runs stopped by step, time or spend limits ÷ runs How often your safety nets fire; a high rate means the budgets or the agent are wrong Raising the limit to make the number go down
Tool error rate Tool calls returning errors ÷ tool calls, by tool Which integration is the weak link; a bad tool description shows up here first Averaging across tools with very different volumes
Human takeover rate Tasks handed to a person mid-run ÷ tasks The cost and autonomy-fit signal; pair with takeover reason Treating every takeover as failure: a correct, early escalation is a success
Consistency across repeats Share of tasks that succeed on every one of k attempts (pass^k) on a fixed eval set Whether users can rely on it, not just whether it can work once Reporting pass@k (any success) as if it were reliability
Time to completion p50 and p95 task duration, started to verified done Whether the wait fits the expectation set in 13A.2 Quoting the mean of a long-tailed distribution

Cost per successful task (Part 6) is the number that ties these together: an agent that succeeds 70% of the time in an average of 9 steps costs far more per success than the per-call price suggests, because failed and runaway runs still bill.

3.7 The decision table: which metrics for which shape#

Product shape North-star candidate Must-have guardrails Vanity trap
Support copilot Cost per resolved ticket Groundedness, escalation rate, CSAT-on-resolved Drafts generated
Document intelligence Straight-through processing rate Field accuracy on golden set, abstention correctness Pages processed
Consumer assistant Weekly tasks completed Cost per task, safety violations, retention Messages sent
Voice agent Verified task completions Latency percentiles, barge-in success, cost per minute Call minutes
Internal tool / copilot Time saved per user-week Acceptance rate, error rate, cost per seat Seats licensed

The metric spec itself is a one-page document — copy this skeleton and fill it in before the second sprint:

markdown
# Metric spec: <feature name> — v0.1 — <date> — owner: <name>

## North-star
<one metric> = <formula: numerator / denominator, with the event fields it reads>
Why it passes the four tests: <customer value / predicts the business outcome /
actionable / simple enough to compute identically everywhere>

## Guardrails (must-not-regress — a breach vetoes ship)
| Metric | Threshold | Action on breach |
|---|---|---|
| <e.g. groundedness on sampled judge> | >= <x>% | <page on-call / freeze releases / auto-rollback> |
| <e.g. cost per started task> | <= $<x> | <same> |
| <e.g. policy-violation rate> | <= <x>% | <same> |

## Layers (one checked metric per layer for v1; add as the product earns them)
| Layer | Metric | Definition & denominator | Source events / fields |
|---|---|---|---|
| Business outcome | <deflection rate / cost per resolved ticket / ...> | <...> | task_completed.outcome, cost records |
| Usage | <activation / week-2 retention / task completion> | <...> | task_started, task_completed |
| Quality | <acceptance unedited / edit distance / eval score> | <...> | draft_accepted, draft_edited, judge_score |
| Experience | <latency p50/p95 / abandonment> | <...> | answer_shown.latency_ms, abandoned |
| Safety | <policy violations / escalation rate> | <...> | escalated, guardrail scan results |
| Cost | <cost per started / per successful task> | <...> | cost_usd on events + cost records |

## Instrumentation
- Event schema: ai_product/metrics.py JSONL ([2.2](#22-the-product-event-schema))
- Join keys: request_id/trace_id -> traces; session_id -> conversation;
  case_id -> eval cases; variant -> experiments
- Measurement fields (latency_ms, cost_usd, judge_score, edit_distance)
  ride on exactly ONE event per task
- Retention: raw events <90d>, aggregates forever — <privacy review ref>
- Review cadence: weekly product metrics review; monthly metric-definition audit

What this means for you as an engineer: pick one metric per layer for your feature's first release — not the full table. A metric you don't check is decoration; a metric you check weekly is instrumentation. Add layers as the product earns them. The spec above is what "checked weekly" means in practice: every number has a definition, a denominator, a source and an owner.


Part 4: Experimentation for LLM features#

Deep-dive

4.1 What "experimenting on an LLM feature" means#

A product experiment asks: does change B make users better off than change A, on the metrics we agreed? For LLM features the "change" is usually one of:

Change type Examples Where it's covered
Prompt / behaviour New system prompt, few-shot set, output format 04.10, Part 8
Model / tier Sonnet → Haiku on easy queries, new snapshot 11B.5 routing, 11C.2, 6.3
UX / autonomy Autonomy dial position, disclosure copy, streaming style 13A.3, 13A.4
Retrieval / context Chunk size, reranker, citation policy 07.x, 06.10
Feature on/off Rollout itself, holdouts This part

The experiment design — randomisation, sample size, duration, guardrails, peeking, SRM checks — is lesson 10A.9, Part 4's job, and it is excellent; this part covers what is different when the system under test is an LLM, and the product-level decisions around the experiment itself.

4.2 What to randomise: user, session or conversation?#

The randomisation unit is the entity assigned to a variant — the single most consequential design choice (10A.9, 4.1).

Unit Good for The catch
User (or account/tenant) Almost everything: retention, quality, cost effects compound per user Slowest to power; needs sticky assignment so a user's experience is consistent
Session / conversation Within-session comparisons, latency and UX changes Carry-over: a bad first answer poisons the rest of the session; users may see both variants across sessions
Request / task Model-tier routing, prompt A/B on single-turn tasks Highest interference risk: shared caches, rate limits and provider-side state can leak across arms
Time (switchback) Marketplace-style interference, when user-level is impossible 04.10, 8.3 and 10A.9, 4.6 own the design; use when carry-over is the smaller evil

Sticky assignment is non-negotiable. A user who gets variant A on Monday and B on Tuesday can't tell you which they preferred — they've experienced a coin flip, not a product. Deterministic bucketing on user_hash (the same hash your analytics uses) gives sticky, auditable assignment with no lookup table; 04.10 implements it for prompt variants.

4.3 Sample size and minimum detectable effect#

Before launch, compute the sample you need — 10A.9, 4.1 gives the formula and ab_sample_size.py computes it for rate metrics. The product-level discipline:

  • Decide the MDE before you look at data. "We'd ship on a +2pp acceptance lift" is a decision; "+whatever is significant" is a recipe for noise-mining.
  • Budget the experiment's own cost. Every task in the experiment arms costs real money (Part 6); a two-week experiment on 5k tasks/day at $0.27/task is a ~$19k experiment. Write that number in the decision memo (4.9).
  • Power check the slices you care about. An experiment powered for the overall effect is usually underpowered for "does it work for German-language tickets?" — either pre-declare the slice as exploratory or don't slice.

ai_product/experiment.py implements the arithmetic:

python
# ai_product/experiment.py — statistics for product experiments on AI features.
#
# Pure standard library (math.erf, random.Random, statistics.NormalDist).
# Experiment *design* — randomisation unit, duration, guardrails, peeking,
# SRM/A-A checks — is lesson 10A.9's job; this module is the arithmetic you
# run on the counts once the experiment ends, plus the sample-size planning
# you do before it starts.
#
# Covers:
#   two_proportion_z_test   read a binary-metric result (acceptance,
#                           resolution, completion) as a z-test
#   bootstrap_diff_ci       percentile bootstrap CI for a difference of
#                           means (edit distance, handle time, judge score)
#   bootstrap_prop_ci       percentile bootstrap CI for one proportion
#   sample_size_per_arm     users needed per arm for a rate metric
#   mde_for_sample          the smallest detectable effect at a given n
#
# Usage:
#     python experiment.py demo
from __future__ import annotations

import math
import random
import statistics

_ND = statistics.NormalDist()


# ---------------------------------------------------------------------------
# Normal-distribution helpers
# ---------------------------------------------------------------------------

def norm_cdf(z: float) -> float:
    """Standard normal CDF via erf — no scipy needed."""
    return 0.5 * (1.0 + math.erf(z / math.sqrt(2.0)))


def norm_ppf(p: float) -> float:
    """Inverse standard normal CDF (statistics.NormalDist, Python 3.8+)."""
    return _ND.inv_cdf(p)


# ---------------------------------------------------------------------------
# Two-proportion z-test (read the result)
# ---------------------------------------------------------------------------

def two_proportion_z_test(x_t: int, n_t: int, x_c: int, n_c: int) -> dict:
    """Two-sided z-test for p_treatment - p_control on binary outcomes.

    x_* = number of successes, n_* = number of units in each arm.
    Uses the pooled proportion under H0 for the standard error — the
    textbook two-proportion z-test. Returns the effect, CI and p-value.
    """
    if n_t == 0 or n_c == 0:
        raise ValueError("both arms need n > 0")
    p_t, p_c = x_t / n_t, x_c / n_c
    p_pool = (x_t + x_c) / (n_t + n_c)
    se = math.sqrt(p_pool * (1 - p_pool) * (1 / n_t + 1 / n_c))
    diff = p_t - p_c
    if se == 0:
        return {"diff": diff, "z": 0.0, "p_value": 1.0,
                "ci95": (diff, diff), "p_t": p_t, "p_c": p_c}
    z = diff / se
    p_value = 2 * (1 - norm_cdf(abs(z)))
    # 95% CI on the *unpooled* difference (Wald interval)
    se_diff = math.sqrt(p_t * (1 - p_t) / n_t + p_c * (1 - p_c) / n_c)
    ci = (diff - 1.96 * se_diff, diff + 1.96 * se_diff)
    return {"diff": diff, "z": z, "p_value": p_value, "ci95": ci,
            "p_t": p_t, "p_c": p_c}


# ---------------------------------------------------------------------------
# Bootstrap confidence intervals (fixed seed -> reproducible)
# ---------------------------------------------------------------------------

def _percentile_ci(boots: list[float], alpha: float) -> tuple[float, float]:
    boots.sort()
    lo = boots[int((alpha / 2) * len(boots))]
    hi = boots[min(int((1 - alpha / 2) * len(boots)), len(boots) - 1)]
    return lo, hi


def bootstrap_diff_ci(a: list[float], b: list[float], *,
                      resamples: int = 10_000, seed: int = 13,
                      alpha: float = 0.05) -> dict:
    """Percentile bootstrap CI for mean(a) - mean(b).

    Resamples each arm with replacement and takes the difference of means.
    `seed` makes the result reproducible — always report it alongside the CI.
    Works for any per-unit metric: edit distance, handle time, judge score.
    """
    if not a or not b:
        raise ValueError("both samples must be non-empty")
    rng = random.Random(seed)
    la, lb = len(a), len(b)
    boots = []
    for _ in range(resamples):
        ma = sum(a[rng.randrange(la)] for _ in range(la)) / la
        mb = sum(b[rng.randrange(lb)] for _ in range(lb)) / lb
        boots.append(ma - mb)
    lo, hi = _percentile_ci(boots, alpha)
    return {"diff": sum(a) / la - sum(b) / lb, "ci": (lo, hi),
            "resamples": resamples, "seed": seed, "alpha": alpha,
            "n_a": la, "n_b": lb}


def bootstrap_prop_ci(x: int, n: int, *, resamples: int = 10_000,
                      seed: int = 13, alpha: float = 0.05) -> dict:
    """Percentile bootstrap CI for a single proportion x/n.

    Parametric bootstrap: redraw x' ~ Binomial(n, x/n) — honest for binary
    outcomes when you only kept the count, not the raw rows.
    """
    if n == 0:
        raise ValueError("n must be > 0")
    rng = random.Random(seed)
    p_hat = x / n
    boots = []
    for _ in range(resamples):
        # sum of n Bernoulli(p_hat) draws == Binomial(n, p_hat)
        boots.append(sum(1 for _ in range(n) if rng.random() < p_hat) / n)
    lo, hi = _percentile_ci(boots, alpha)
    return {"p": p_hat, "ci": (lo, hi), "resamples": resamples,
            "seed": seed, "alpha": alpha, "n": n}


# ---------------------------------------------------------------------------
# Sample size and minimum detectable effect (plan before you start)
# ---------------------------------------------------------------------------

def sample_size_per_arm(p_baseline: float, mde: float, *,
                        alpha: float = 0.05, power: float = 0.8) -> int:
    """Units needed per arm to detect a change of `mde` (absolute, e.g.
    0.03 = 3 points) on a proportion metric, two-sided test.

    Normal approximation with unpooled variances — the standard quick
    formula. Round UP: being one user short of power is still short.
    """
    if not (0 < p_baseline < 1):
        raise ValueError("p_baseline must be in (0, 1)")
    if mde <= 0:
        raise ValueError("mde must be > 0")
    p_treat = p_baseline + mde
    if not (0 < p_treat < 1):
        raise ValueError("p_baseline + mde must stay in (0, 1); mde is an "
                         "absolute difference (e.g. 0.03 = 3 points) — for a "
                         "decrease, pass the lower rate as p_baseline")
    z_a = norm_ppf(1 - alpha / 2)
    z_b = norm_ppf(power)
    var = p_baseline * (1 - p_baseline) + p_treat * (1 - p_treat)
    n = ((z_a + z_b) ** 2) * var / (mde ** 2)
    return math.ceil(n)


def mde_for_sample(n_per_arm: int, p_baseline: float, *,
                   alpha: float = 0.05, power: float = 0.8) -> float:
    """Inverse of sample_size_per_arm: the smallest absolute effect your
    sample can detect at the given power. Use it to sanity-check an
    experiment that ended early.

    Raises ValueError when the implied comparison rate leaves (0, 1) —
    i.e. the sample is too small to bound an effect at this baseline.
    For a decrease, analyse the lower rate as the baseline instead."""
    if n_per_arm <= 0:
        raise ValueError("n_per_arm must be > 0")
    if not (0 < p_baseline < 1):
        raise ValueError("p_baseline must be in (0, 1)")
    z_a = norm_ppf(1 - alpha / 2)
    z_b = norm_ppf(power)
    mde = 0.05
    for _ in range(50):
        p_t = p_baseline + mde
        if not (0.0 < p_t < 1.0):
            raise ValueError(
                f"cannot bound the MDE: n={n_per_arm} per arm at baseline "
                f"{p_baseline} implies a comparison rate outside (0, 1). "
                "The sample is too small for this baseline — collect more "
                "data, or for a decrease analyse the lower rate as the "
                "baseline.")
        var = p_baseline * (1 - p_baseline) + p_t * (1 - p_t)
        new_mde = (z_a + z_b) * math.sqrt(var / n_per_arm)
        if abs(new_mde - mde) < 1e-9:
            break
        mde = new_mde
    return abs(mde)


# ---------------------------------------------------------------------------
# Demo: the support copilot's draft-acceptance experiment
# ---------------------------------------------------------------------------

def demo() -> None:
    print("=== two_proportion_z_test: draft acceptance, control vs treatment ===")
    # control: 612 unedited accepts / 2000 drafts; treatment: 702 / 2000
    r = two_proportion_z_test(x_t=702, n_t=2000, x_c=612, n_c=2000)
    print(f"  control {r['p_c']:.1%}  treatment {r['p_t']:.1%}  "
          f"diff {r['diff']:+.2%}")
    print(f"  95% CI [{r['ci95'][0]:+.2%}, {r['ci95'][1]:+.2%}]  "
          f"z={r['z']:.2f}  p={r['p_value']:.4f}")

    print("\n=== bootstrap_diff_ci: mean edit distance, treatment vs control ===")
    # per-draft normalised edit distances (0 = sent as-is). Treatment drafts
    # needed *less* editing — a continuous metric, so bootstrap not z-test.
    control_edits = ([0.0] * 40) + ([0.05, 0.08, 0.12, 0.2, 0.35] * 12)  # 100 drafts
    treat_edits = ([0.0] * 55) + ([0.03, 0.06, 0.1, 0.15, 0.25] * 9)    # 100 drafts
    b = bootstrap_diff_ci(treat_edits, control_edits, seed=20261107)
    print(f"  mean(control)={sum(control_edits)/len(control_edits):.3f}  "
          f"mean(treatment)={sum(treat_edits)/len(treat_edits):.3f}")
    print(f"  diff {b['diff']:+.3f}  95% CI [{b['ci'][0]:+.3f}, {b['ci'][1]:+.3f}]"
          f"  (seed={b['seed']}, {b['resamples']} resamples)")

    print("\n=== sample_size_per_arm / mde_for_sample ===")
    for mde in (0.02, 0.03, 0.05):
        n = sample_size_per_arm(0.30, mde)
        print(f"  baseline 30%, detect {mde:.0%} lift -> {n:,} drafts per arm")
    n = sample_size_per_arm(0.30, 0.03)
    print(f"  with only {n//4:,} per arm you can detect "
          f"{mde_for_sample(n//4, 0.30):.1%} — plan or extend before launch")


if __name__ == "__main__":
    demo()
Output13 lines
=== two_proportion_z_test: draft acceptance, control vs treatment ===
  control 30.6%  treatment 35.1%  diff +4.50%
  95% CI [+1.59%, +7.41%]  z=3.03  p=0.0024

=== bootstrap_diff_ci: mean edit distance, treatment vs control ===
  mean(control)=0.096  mean(treatment)=0.053
  diff -0.043  95% CI [-0.071, -0.017]  (seed=20261107, 10000 resamples)

=== sample_size_per_arm / mde_for_sample ===
  baseline 30%, detect 2% lift -> 8,391 drafts per arm
  baseline 30%, detect 3% lift -> 3,760 drafts per arm
  baseline 30%, detect 5% lift -> 1,374 drafts per arm
  with only 940 per arm you can detect 6.1% — plan or extend before launch

How to read it as a product decision: the treatment arm's +4.5pp acceptance lift is statistically real (CI excludes zero) and practically meaningful (it's bigger than the 3pp MDE you pre-registered) — but only if the guardrail metrics held. The z-test answers "is the difference real"; it cannot answer "should we ship" — that's what guardrails and the decision memo are for.

4.4 The AI-specific traps#

Experiments on deterministic systems fail in known ways; LLM features add four more:

Interference through shared caches. Prompt caches, semantic caches and embedding caches are shared infrastructure. If variant B's requests hit cache entries written by variant A — or worse, a semantic cache returns variant A's answer to variant B's query — the arms contaminate each other and the measured difference shrinks toward zero. Defences: include variant/prompt_version/model_resolved in every cache key (11B.3 owns cache design), use sticky routing on gateways (11B.5), and check whether your caching layer is even experiment-aware before you start.

Novelty and learning effects. Users react to newness: a new UI gets a honeymoon boost that fades in weeks; a "new AI assistant" announcement changes behaviour independent of quality. Countermeasures: run experiments for full business cycles (include weekends), analyse week-2+ separately from week-1, and prefer longer experiments on retention metrics. Kohavi, Tang and Xu's book (cited in Further resources) treats carry-over and novelty as first-class validity threats; for AI features the novelty effect is larger because the thing being tested is visibly new.

Silent model updates. Providers ship new snapshots under the same alias (02.9, 8.1–8.3, 10A.9, 5.1's model-version drift). A two-week experiment can straddle an unannounced upgrade and measure two different systems. Defences: pin dated snapshots for experiments (02.9, 8.3), log model_resolved on every event, and check the resolved-model distribution before reading results.

Quality is multi-dimensional. An experiment on a probabilistic system can't read one metric. The treatment might win acceptance rate while losing groundedness — users accept plausible-sounding wrong answers faster. Pre-register a primary metric (the one you're optimising), guardrail metrics (must-not-regress: safety violations, cost per task, escalation rate, p95 latency, groundedness on sampled judge scoring), and diagnostic metrics (explain why, never decide on them alone). 09.10, 4.5 states the rule crisply for multimodal: "A/B tests answer 'do users prefer/complete more with variant B'; eval suites answer 'is variant B still correct'. You need both."

4.5 Interleaving and side-by-side preference#

For ranking and retrieval comparisons, interleaving merges two systems' outputs and credits clicks — more sensitive than A/B at small scale (10A.9, 4.2; Radlinski and Craswell's interleaving work, WSDM 2013, is the canonical reference). For generative outputs the product-level equivalent is side-by-side human preference: show users output A and output B (randomised position — position bias is real, 10A.5 covers judge-side bias) and ask which was better. Use it for high-stakes UX comparisons (tone, formatting, verbosity) where a single-answer A/B can't isolate preference; it's expensive per data point, so reserve it for decisions that matter. LLM-judged pairwise comparison (10A.4) is the scalable version — with the caveat that the judge is another model with its own biases; calibrate it against human labels first (10A.5).

4.6 Shadow traffic and canaries for model/prompt changes#

Before a change touches users, run it on live traffic invisibly:

  • Shadow mode (10A.9, 4.3): the candidate model/prompt processes real requests but users see the production answer. You get quality/cost/latency data on the actual traffic distribution — the thing offline evals can't give you.
  • Canary rollout (10A.9, 4.4): serve the change to 1–5% of traffic while watching guardrail metrics; auto-rollback on threshold breach.
  • Feature flags and kill switches (11C.4, 1.6): the mechanism that makes canaries and experiments reversible in seconds. An experiment you can't kill is a bet, not a test.

For model-upgrade experiments specifically — treating a provider snapshot change as an experiment rather than an ops event — 11C.2, 6.3 owns the playbook (shadow suite → canary → promote/rollback). The product addition: define success criteria before the shadow run — which metrics, what delta counts as "better", what cost increase is acceptable — so the upgrade decision is a decision, not a vibe.

4.7 Reading results honestly#

10A.9, 4.7 owns the statistics: confidence intervals over p-value thresholds, Simpson's paradox when slicing, multiple-comparisons awareness, and the LLM-specific issues (judge drift, non-stationary traffic). The product-level additions:

  • Analysing heterogeneous effects. The average effect hides the story: a prompt change that helps English tickets and hurts German ones averages to "neutral". Pre-declare 2–4 slices (language, tenant tier, query type, task difficulty) before launch; analyse them as secondary hypotheses with the multiple-comparisons caveat — a slice "win" at p<0.05 across 10 slices is expected by chance once. Report slices as "exploratory, needs confirmation", not as findings.
  • The peeking problem. Checking the dashboard daily and stopping when p<0.05 inflates false positives well above the nominal 5% — by several-fold in simulations, with the size depending on how often you look and how large the sample gets (Johari et al., KDD 2017; see 10A.9, 4.1). Pre-register the end date; if you must look, do sequential testing properly — alpha spending or always-valid p-values — or accept that you're exploring, not confirming. Naive daily peeking with a fixed p<0.05 threshold is not sequential testing; it's just a false-positive machine.
  • Twyman's law. "Any figure that looks interesting or different is usually wrong" (Kohavi et al.) — the surprising result is the one to re-check first: SRM, instrumentation gaps, a mid-experiment deploy, a provider update.

4.8 Holdouts: measuring what never ends#

A holdout is a small group (typically 1–5%) that never receives the feature — not during the experiment, not after launch. It answers the question experiments can't: what is the cumulative, novelty-free effect of having this feature at all? Run a holdout for major launches and revisit it quarterly; if the feature's measured benefit decays to zero against the holdout, that's the signal to fix or kill it.

The costs are real and must be acknowledged: holdout users get the worse product (an ethical/product trade-off — keep it small and time-boxed), and the analysis needs the same statistical care as an experiment (the holdout is just a permanent control arm). For AI features specifically, holdouts also guard against metric capture: if the north-star improves for treated users partly because the metric itself changed behaviour, the holdout reveals the secular trend.

4.9 The decision memo#

Every experiment ends with a written decision — not a dashboard screenshot. Template (copy-ready):

markdown
# Decision memo: <feature/change> — <date>

## Question
Does <variant B> improve <primary metric> vs <variant A> for <population>,
without regressing <guardrail metrics>?

## Design
- Randomisation unit: <user | session | task | time>
- Arms: <A = ..., B = ...>
- Assignment: <deterministic hash on user_hash | platform>
- Duration: <dates>; pre-registered end: <date>
- Sample: <n per arm>; MDE: <x pp>; power: <80%>
- Primary metric: <definition + denominator>
- Guardrails: <metric: threshold>
- Diagnostics: <metrics that explain but don't decide>
- Experiment cost: <$ estimate>

## Results
- Primary: <A=x%, B=y%, diff +z pp, 95% CI [..]>
- Guardrails: <each metric vs threshold — pass/fail>
- Slices (exploratory): <language, tenant tier, task type>
- Anomalies checked: <SRM, model_resolved distribution, deploys in window>

## Decision
<Ship | Iterate | Kill> — because <one paragraph>.
Rollback criteria if shipped: <metric threshold → action>.
Follow-ups: <eval cases to add, slices to confirm, holdout decision>.

Fill it before reading results where possible (pre-registration), and file it where the team will actually find it — the memo is the institutional memory that prevents re-running the same experiment in six months.

What this means for you as an engineer: the experiment's real deliverable isn't the p-value, it's the decision memo. If you can't write the memo, you don't understand the experiment well enough to run it.


Part 5: The data flywheel#

Deep-dive

5.1 The loop#

flowchart LR
    T["Production traffic<br/>(real user tasks)"] --> S["Sampled review<br/>(10A.9 review queues,<br/>13A.3 review_queue.py)"]
    S --> L["Labelled cases<br/>(what went wrong,<br/>why it matters)"]
    L --> E["Eval datasets<br/>(10A.2 schema,<br/>versioned)"]
    E --> F["Prompt / model /<br/>retrieval changes"]
    F --> D["Deploy via<br/>11C.2 CI/CD +<br/>canary"]
    D --> M["Measure online<br/>(this lesson's<br/>metric tree)"]
    M --> T

Each turn of the wheel makes the next one cheaper: better prompts need fewer review hours; better evals catch regressions before users do; production failures become permanent regression tests. Lesson 10A.9, Part 6 owns the signal→case mechanics; lesson 10A.2, 2.2 owns dataset construction from production logs. This part covers the product decisions: what to label, how much review to buy, and how not to poison the loop.

5.2 From signal to labelled case#

The pipeline, concretely:

  1. Detect candidates. Signals that something went wrong: thumbs-down, escalation, abandonment mid-answer, judge-score below threshold, assertion-monitor failures (10A.9, Part 3), user reports.
  2. Sample for review. Not everything needs a human: stratified sampling guarantees coverage of each route/language/slice (10A.9, 3.2) plus a random baseline so rare failures aren't crowded out. 13A.3's review_queue.py is the product-side queue with confidence routing.
  3. Label with a taxonomy. Open-code failures into categories first (10A.1, Part 4), then label against the taxonomy — free-text "it was bad" labels can't aggregate.
  4. Convert to eval cases. Each confirmed failure becomes an EvalExample (10A.2) with input, expected behaviour and the failure tag. Dedup against existing cases; a case that already exists means the eval gate has a hole, not that you need a duplicate.
  5. Fix and verify. The fix ships through the normal pipeline (11C.2); the eval suite proves it; production metrics confirm it.

5.3 Labelling workflows and economics#

Review is the flywheel's cost centre — budget it deliberately:

  • Who labels. Domain experts for correctness judgements (support leads, not engineers); trained reviewers for taxonomy tagging; engineers for ambiguous cases. Inter-annotator agreement matters (10A.2, 4.3) — two reviewers disagreeing 30% of the time means your taxonomy is fuzzy, not that reviewers are bad.
  • How much. Enough to (a) estimate failure-mode frequencies, (b) fill each taxonomy bucket with cases, (c) calibrate the judge. Beyond that, marginal labels buy little — switch to judge-scored sampling.
  • When the loop isn't worth it. Low-volume features (a few hundred tasks/week) can't feed a flywheel — rely on golden sets and periodic audits instead. The flywheel pays when volume × failure-cost is high: support copilots, document pipelines, voice agents.

5.4 Feedback-loop bias — the flywheel's own failure modes#

The loop can corrupt itself:

Bias Mechanism Defence
Survivorship Only successful-looking sessions reach review; the failures that mattered never get labelled Sample all outcomes, including abandoned and escalated; stratify by outcome, not just by route
Position bias Users click/accept the first suggestion; feedback reflects position, not quality Rotate suggestion order; measure acceptance by position before trusting the aggregate
Verbosity bias Longer, confident-sounding answers get higher ratings regardless of correctness Judge-scored sampling on a fixed rubric; pair thumbs with edit distance and outcome
Sycophancy loop Optimising for approval produces agreeable wrong answers; users rate them up; metrics improve while quality falls Guardrail on groundedness/correctness independent of approval; periodic blind audits (1.6)
Popularity loop The eval set drifts toward whatever the current model does well Anchor with a stable golden set and public benchmarks; track eval-set composition over time
Consent gap Production data used for evals/fine-tuning that users didn't consent to 12.4 rules: purpose limitation, retention, deletion propagation to derived copies

What this means for you as an engineer: the flywheel is a system, not a feature — it needs an owner, a budget and a bias audit. Assign the review queue a named owner before launch; "everyone's job" is nobody's.


Part 6: Unit economics — cost per successful task#

6.1 What "unit economics" means for an AI feature#

Unit economics is the arithmetic of one unit of value: what it costs to deliver one successful task, what you charge for it, and what's left. For an AI feature the unit is usually a resolved ticket, a processed document, a completed voice task — not an API call. The distinction matters because the bill is per-call while the value is per-outcome, and the gap between them is where AI products lose money.

The layers of cost, in the order they appear on the invoice:

flowchart LR
    subgraph variable ["Variable cost (per task)"]
        L["LLM tokens<br/>input / cached / output / reasoning"]
        T["Tools & retrieval<br/>embeddings, vector DB,<br/>web search, STT/TTS"]
        R["Human review<br/>sampled approvals,<br/>escalations"]
    end
    subgraph fixed ["Fixed cost (allocated)"]
        I["Infrastructure<br/>hosting, storage,<br/>observability, ops time"]
    end
    variable --> CPS["Cost per started task"]
    I --> CPS
    CPS --> CS["Cost per successful task<br/>= started cost / success rate"]
    CS --> GM["Gross margin<br/>= (price - cost) / price"]

6.2 Cost per successful task — the number that decides pricing#

Lesson 11A.1, 8.2 defines cost per resolved outcome at the trace level; lesson 03.7 owns per-call cost computation; lesson 11B.1 owns the levers. Lesson 11B.2, Part 5 is the token-cost view of the same units (a per-developer cost anchor, the heavy-user problem and reported margins), and lesson 11B.6 owns budgets, attribution and chargeback. This lesson's contribution is the product formula — the one that goes into a pricing decision:

text
cost_per_started_task =
      llm_cost_per_attempt × llm_attempts_per_task      # retries & regenerations bill too
    + tool_cost_per_attempt × llm_attempts_per_task     # retrieval/tools per attempt
    + review_cost_per_task                              # human review, expected value
    + infra_cost_per_task                               # allocated fixed cost

cost_per_success = cost_per_started_task / success_rate

The two terms people forget:

  • llm_attempts_per_task > 1. Retries, regenerations, escalated drafts and multi-step agent runs all bill. A "one-call" feature with a 30% retry rate has a 1.3× cost multiplier hiding in it.
  • success_rate < 1. The 40% of tasks that fail still cost money — you paid for the tokens, the retrieval and possibly the review. Dividing by success rate is what turns "cost per call" into "cost per outcome".

6.3 ai_product/unit_economics.py — the calculator#

python
# ai_product/unit_economics.py — unit economics for an AI feature *as a product*.
#
# Pure standard library. This is the product-decision layer on top of the
# per-call cost tracking of lesson 03.7 and the trace-level attribution of
# lesson 11A.1: it answers "what does one *successful* task cost us, and do
# we make money at this price?" — including the costs that never appear on
# an invoice line: retries, failures, human review and idle infrastructure.
#
# Prices are parameters, never constants: copy them from the provider's
# pricing page on the day you decide (lesson 02.9 Part 6, lesson 03.7 Part 4).
#
# CostModel is the per-ticket adapter lesson 13B.2's scripts/cost_report.py
# imports: same arithmetic, support-desk shape, named scenarios.
#
# Usage:
#     python unit_economics.py demo
from __future__ import annotations

from dataclasses import dataclass


@dataclass
class ModelPrice:
    """USD per 1M tokens. `output` covers visible AND reasoning tokens —
    providers bill thinking at the output rate (lesson 02.9, 6.4)."""
    input: float
    cached_input: float
    output: float


@dataclass
class TaskProfile:
    """One 'task' = one user job the feature attempts (a drafted reply, a
    classified ticket, a processed document — not one API call)."""
    input_tokens: int            # per model attempt, incl. history + retrieval
    cached_fraction: float       # share of input served from prompt cache
    output_tokens: int           # per attempt, visible + reasoning
    llm_attempts_per_task: float # expected billed model calls per started task
                                 # (retries, regenerations, escalated drafts)
    tool_cost_per_attempt: float # embeddings, vector search, web search, STT...
    review_cost_per_task: float  # expected human-review cost per started task
    infra_cost_per_task: float   # allocated fixed cost: hosting, storage, ops
    success_rate: float          # share of started tasks ending outcome=ok
    price_per_success: float     # what the customer pays per successful task
    tasks_per_month: int = 0     # for the monthly roll-up (0 = skip)


def llm_cost_per_attempt(price: ModelPrice, t: TaskProfile) -> float:
    """USD for ONE model attempt: uncached + cached input + output."""
    cached = t.input_tokens * t.cached_fraction
    fresh = t.input_tokens - cached
    return (fresh * price.input
            + cached * price.cached_input
            + t.output_tokens * price.output) / 1_000_000


def cost_per_started_task(price: ModelPrice, t: TaskProfile) -> float:
    """Everything a started task costs, win or lose: model attempts, tools,
    review and infrastructure. Failed and retried attempts still bill."""
    return (llm_cost_per_attempt(price, t) * t.llm_attempts_per_task
            + t.tool_cost_per_attempt * t.llm_attempts_per_task
            + t.review_cost_per_task
            + t.infra_cost_per_task)


def cost_per_success(price: ModelPrice, t: TaskProfile) -> float:
    """The number that decides pricing: cost divided by *successful* tasks,
    not by calls. A 60% success rate means 40% of spend buys nothing."""
    return cost_per_started_task(price, t) / t.success_rate


def gross_margin(price: ModelPrice, t: TaskProfile) -> float:
    """(price - cost) / price. Negative = selling losses per success."""
    c = cost_per_success(price, t)
    return (t.price_per_success - c) / t.price_per_success


def monthly_rollup(price: ModelPrice, t: TaskProfile) -> dict:
    """Scale to a month: tasks -> revenue, cost, margin."""
    if t.tasks_per_month <= 0:
        return {}
    started = t.tasks_per_month
    successes = started * t.success_rate
    revenue = successes * t.price_per_success
    cost = started * cost_per_started_task(price, t)
    return {"tasks": started, "successes": successes,
            "revenue": revenue, "cost": cost, "margin": revenue - cost}


def sensitivity_table(price: ModelPrice, t: TaskProfile, *,
                      success_rates: list[float],
                      prices: list[float]) -> list[list[str]]:
    """Gross margin % over a grid of success rates x price points.
    The two knobs a product team actually argues about."""
    rows = [["price \\ success"] + [f"{s:.0%}" for s in success_rates]]
    for pr in prices:
        row = [f"${pr:.2f}"]
        for s in success_rates:
            tt = TaskProfile(**{**t.__dict__, "success_rate": s,
                                "price_per_success": pr})
            row.append(f"{gross_margin(price, tt):+.0%}")
        rows.append(row)
    return rows


def print_table(rows: list[list[str]]) -> None:
    widths = [max(len(r[i]) for r in rows) for i in range(len(rows[0]))]
    for r in rows:
        print("  ".join(c.ljust(w) for c, w in zip(r, widths)))


@dataclass
class CostModel:
    """Per-ticket cost model for support-desk products.

    This is the adapter lesson 13B.2's `scripts/cost_report.py` imports as
    `CostModel`: it wraps the same arithmetic as `TaskProfile` /
    `cost_per_success` in a ticket-level shape — model + retrieval/tools +
    infra + human time, divided by the share of tickets that resolve.

    All money is USD. "Resolved" means resolved without escalation;
    `resolution_rate` is the share of started tickets that reach it, and it
    applies to every scenario (a human-only desk still has unresolved
    tickets).

    Human time: `human_review_minutes_per_ticket` is the human minutes spent
    per ticket *in the assisted scenarios* — reviewing AI drafts.
    `agent_hourly` is the loaded hourly cost of the human (wages plus
    overhead). For `human_only`, pass `human_handle_minutes_per_ticket`: a
    full handle is longer than a review pass, and reusing the review minutes
    would understate the baseline. If you leave it None, the review minutes
    are reused — a floor, not a realistic handle time.
    """
    input_tokens_per_ticket: int
    output_tokens_per_ticket: int
    price_in_per_mtok: float
    price_out_per_mtok: float
    retrieval_cost_per_query: float        # one retrieval/tool-call unit, USD
    tool_calls_per_ticket: float
    infra_per_ticket: float
    human_review_minutes_per_ticket: float
    agent_hourly: float                    # loaded USD per hour
    resolution_rate: float                 # share resolved w/o escalation
    cached_input_fraction: float = 0.0     # prompt-cache hit rate on input
    # defaults to price_in — no cache discount assumed (conservative)
    price_cached_per_mtok: float | None = None
    llm_attempts_per_ticket: float = 1.0   # retries/regenerations bill too
    human_handle_minutes_per_ticket: float | None = None

    def __post_init__(self) -> None:
        if not (0.0 < self.resolution_rate <= 1.0):
            raise ValueError("resolution_rate must be in (0, 1]")
        if min(self.tool_calls_per_ticket, self.infra_per_ticket,
               self.cached_input_fraction, self.llm_attempts_per_ticket) < 0:
            raise ValueError("costs and rates can't be negative")

    def _llm_cost_per_ticket(self) -> float:
        """USD for all billed model attempts on one ticket."""
        cached_price = (self.price_in_per_mtok
                        if self.price_cached_per_mtok is None
                        else self.price_cached_per_mtok)
        fresh = self.input_tokens_per_ticket * (1 - self.cached_input_fraction)
        cached = self.input_tokens_per_ticket * self.cached_input_fraction
        per_attempt = (fresh * self.price_in_per_mtok
                       + cached * cached_price
                       + self.output_tokens_per_ticket * self.price_out_per_mtok
                       ) / 1_000_000
        return per_attempt * self.llm_attempts_per_ticket

    def _ai_cost_per_ticket(self) -> float:
        """Model + retrieval/tools + infra — identical in every AI scenario."""
        return (self._llm_cost_per_ticket()
                + self.tool_calls_per_ticket * self.retrieval_cost_per_query
                + self.infra_per_ticket)

    def _human_cost_per_ticket(self, scenario: str) -> float:
        """USD of human time per started ticket for the scenario."""
        per_minute = self.agent_hourly / 60.0
        if scenario == "all_copilot":
            # the AI resolves autonomously; humans touch only escalations
            return ((1 - self.resolution_rate)
                    * self.human_review_minutes_per_ticket * per_minute)
        if scenario == "copilot_assist":
            # AI drafts; a human reviews every ticket
            return self.human_review_minutes_per_ticket * per_minute
        if scenario == "human_only":
            minutes = (self.human_review_minutes_per_ticket
                       if self.human_handle_minutes_per_ticket is None
                       else self.human_handle_minutes_per_ticket)
            return minutes * per_minute
        raise ValueError(
            f"unknown scenario {scenario!r}: expected 'all_copilot', "
            "'copilot_assist' or 'human_only'")

    def cost_per_started_ticket(self, scenario: str) -> float:
        """USD per started ticket for 'all_copilot' | 'copilot_assist' |
        'human_only'."""
        if scenario == "human_only":
            return self._human_cost_per_ticket(scenario)
        return (self._ai_cost_per_ticket()
                + self._human_cost_per_ticket(scenario))

    def cost_per_resolved_ticket(self, scenario: str) -> float:
        """USD per ticket resolved without escalation — the 13B.2 metric.
        Failed and escalated tickets still cost money, so the denominator
        is resolutions, not starts."""
        return self.cost_per_started_ticket(scenario) / self.resolution_rate


def support_copilot() -> TaskProfile:
    """The Module 13B support copilot (lesson 13B.2): an agent-assists draft.

    Per attempt ~6,000 input tokens (ticket + retrieved handbook + history),
    ~30% of it a cacheable prefix; ~400 output tokens including reasoning.
    ~1.3 billed attempts per started task (regenerations + a retry). Tools
    (embeddings + vector search) ~$0.002/attempt. 20% of drafts get a human
    review averaging 3 minutes at a $25/h loaded cost -> $0.25/task.
    """
    return TaskProfile(
        input_tokens=6_000, cached_fraction=0.30, output_tokens=400,
        llm_attempts_per_task=1.3,
        tool_cost_per_attempt=0.002,
        review_cost_per_task=0.25,
        infra_cost_per_task=0.001,
        success_rate=0.60,
        price_per_success=1.50,
        tasks_per_month=50_000,
    )


def demo() -> None:
    # Prices copied from the 02.9/03.7 November-2026 snapshot (standard tier,
    # short prompts). They WILL change — re-check the pricing page.
    prices = {
        "claude-haiku-5-5":  ModelPrice(0.10, 0.01, 0.50),
        "claude-sonnet-5-5": ModelPrice(2.00, 0.10, 10.00),
        "gpt-6.1-sol":       ModelPrice(2.00, 0.10, 10.00),
        "gemini-3.8-flash":  ModelPrice(0.75, 0.075, 3.75),
    }
    t = support_copilot()
    print("=== cost per successful task by model (support copilot) ===")
    print(f"{'model':18s} {'$/attempt':>10s} {'$/started':>10s} "
          f"{'$/success':>10s} {'margin':>8s}")
    for name, p in prices.items():
        print(f"{name:18s} ${llm_cost_per_attempt(p, t):>9.4f} "
              f"${cost_per_started_task(p, t):>9.4f} "
              f"${cost_per_success(p, t):>9.4f} {gross_margin(p, t):>7.0%}")

    print("\n=== the surprise: the model bill is the small line ===")
    p = prices["claude-sonnet-5-5"]
    llm = llm_cost_per_attempt(p, t) * t.llm_attempts_per_task
    total = cost_per_started_task(p, t)
    for label, usd in [("model calls", llm), ("tools", 0.002 * 1.3),
                       ("human review", 0.25), ("infra", 0.001)]:
        print(f"  {label:14s} ${usd:.4f}  ({usd / total:.0%} of started-task cost)")

    print("\n=== sensitivity: gross margin at $1.50/success ===")
    print_table(sensitivity_table(p, t,
                                  success_rates=[0.50, 0.60, 0.70, 0.80],
                                  prices=[0.75, 1.00, 1.50, 2.00]))

    print("\n=== monthly roll-up (sonnet, 50k tasks/mo, 60% success) ===")
    m = monthly_rollup(p, t)
    print(f"  successes {m['successes']:,.0f}  revenue ${m['revenue']:,.2f}  "
          f"cost ${m['cost']:,.2f}  margin ${m['margin']:,.2f}")

    print("\n=== CostModel: cost per resolved ticket, three scenarios ===")
    print("    (the adapter lesson 13B.2's scripts/cost_report.py imports)")
    cm = CostModel(
        input_tokens_per_ticket=4_200, output_tokens_per_ticket=900,
        price_in_per_mtok=0.15, price_out_per_mtok=0.60,  # cheap alias tier
        retrieval_cost_per_query=0.0004, tool_calls_per_ticket=1.8,
        infra_per_ticket=0.002,
        human_review_minutes_per_ticket=2.5, agent_hourly=28.0,
        resolution_rate=0.72,
        human_handle_minutes_per_ticket=8.0,  # a full handle > a review pass
    )
    for s in ("all_copilot", "copilot_assist", "human_only"):
        print(f"  {s:15s} ${cm.cost_per_resolved_ticket(s):.4f}")


if __name__ == "__main__":
    demo()
Output28 lines
=== cost per successful task by model (support copilot) ===
model               $/attempt  $/started  $/success   margin
claude-haiku-5-5   $   0.0006 $   0.2544 $   0.4240     72%
claude-sonnet-5-5  $   0.0126 $   0.2700 $   0.4499     70%
gpt-6.1-sol        $   0.0126 $   0.2700 $   0.4499     70%
gemini-3.8-flash   $   0.0048 $   0.2598 $   0.4330     71%

=== the surprise: the model bill is the small line ===
  model calls    $0.0164  (6% of started-task cost)
  tools          $0.0026  (1% of started-task cost)
  human review   $0.2500  (93% of started-task cost)
  infra          $0.0010  (0% of started-task cost)

=== sensitivity: gross margin at $1.50/success ===
price \ success  50%   60%   70%   80%
$0.75            +28%  +40%  +49%  +55%
$1.00            +46%  +55%  +61%  +66%
$1.50            +64%  +70%  +74%  +78%
$2.00            +73%  +78%  +81%  +83%

=== monthly roll-up (sonnet, 50k tasks/mo, 60% success) ===
  successes 30,000  revenue $45,000.00  cost $13,497.70  margin $31,502.30

=== CostModel: cost per resolved ticket, three scenarios ===
    (the adapter lesson 13B.2's scripts/cost_report.py imports)
  all_copilot     $0.4591
  copilot_assist  $1.6258
  human_only      $5.1852

Read the numbers as a product decision:

  • The model tier barely matters here. Haiku vs Sonnet changes cost-per-success by about $0.03 (6%) — because human review dominates the cost stack at 93%. The expensive model is nearly free relative to the review it might save. This is the single most common unit-economics surprise in copilot products: optimise the human-in-the-loop cost before the token cost.
  • Success rate is the biggest lever. Moving success from 50% to 80% at $1.50 lifts gross margin from +64% to +78% and nearly doubles the margin per started task ($0.48 to $0.93). Quality improvements pay for themselves twice: better product and better unit economics.
  • The margin table is the pricing conversation. At $0.75/success you're still profitable but thin; at $1.50 you're comfortable; the table tells you exactly how much quality regression you can absorb before pricing breaks.

CostModel is the same arithmetic in a per-ticket shape, and it exists because lesson 13B.2's scripts/cost_report.py imports it directly. Its three scenarios are the three ways a support desk can be staffed: all_copilot (the AI resolves autonomously; humans touch only the escalated share), copilot_assist (AI drafts, a human reviews every ticket — the shape this lesson's support_copilot() profile models) and human_only (the baseline with no AI). The demo's spread — $0.46 vs $1.63 vs $5.19 per resolved ticket — is the unit-economics argument for the copilot in one table. Two honest caveats: the model assumes resolution_rate applies to every scenario, and human_only needs human_handle_minutes_per_ticket set to a real handle time — reusing review minutes would understate the baseline and make the copilot look useless. Swap in your own measured minutes before quoting the numbers to anyone.

6.4 Pricing models and their traps#

Model How it works Best for The trap
Seat-based Per user/month, unlimited use Internal tools, predictable budgets Heavy users subsidised by light ones; no cost signal to the customer
Usage-based Per task/message/API call Developer tools, variable workloads Unpredictable bills; customers fear the invoice; you absorb the retry/failure cost invisibly
Outcome-based Per resolved ticket, per extracted field, per booked call Services with verifiable outcomes Verification cost; disputes over what counts as "resolved"; Goodhart risk (1.6)
Tiered Base + usage overage, or feature tiers Most SaaS Complexity; the tier boundaries become the product
Freemium / free tier Free up to N tasks, then pay Consumer, PLG Abuse and free-rider cost; the free tier must be engineered cheap (6.6)
Enterprise flat Annual contract, SLA, dedicated capacity High-volume B2B Cost overruns on your side; needs the unit-economics sheet to price safely

Outcome-based pricing deserves a special warning. Charging per resolved ticket aligns your incentive with the customer's — but it invites the Goodhart failure from 1.6: the cheapest "resolution" is a confident wrong answer. If you price on outcomes, you must verify outcomes (reopen rate, CSAT sampling, audit sample) — the verification cost belongs in review_cost_per_task. Hybrid structures (a platform fee plus per-outcome or per-usage charges) are a common way to share the verification and variance risk between vendor and customer; treat any single-model pricing as a starting hypothesis, not a conclusion.

A public example of how much the definition matters (as of November 2026, from the vendor's own pricing page, intercom.com/pricing): Intercom prices its Fin support agent at $0.99 per "outcome", billed once per conversation, and counts an outcome when the customer confirms the issue is resolved, when they do not ask for more help after Fin responds, or when Fin completes a workflow including handoffs. Notice what that makes you decide as a buyer or builder: a "resolution" that is inferred from silence is cheaper to detect than one the customer confirms, but it can count a customer who simply gave up. Whichever definition you adopt, write it into the contract, sample it against reopen rate and CSAT, and model the dispute rate in review_cost_per_task. This is an illustration of the trap, not a judgement of any vendor's product.

6.4a SLAs and contractual quality for AI features#

Every B2B AI product eventually faces the question the pricing table can't answer: what can you contractually promise when the core component is probabilistic? An internal SLO (13A.5, 5.4, 11A.2) is a target you set for yourself; a customer SLA is a promise with money attached. They are different instruments and must not share a draft.

  • "The model is nondeterministic" is not a defence. 13A.7, 4.2 is the cautionary case: a tribunal held the company liable for what its chatbot said — your contract can't outsource responsibility to sampling variance either. What you commit to must be something you can measure and stand behind.
  • Commit to measured floors, not aspirations. Write quality commitments against the metrics in your spec — "groundedness ≥ X on the published eval set, measured monthly over a trailing 30-day window" — with the measurement window, the eval-set version and the dispute process named in the contract. An SLA on an undefined metric is unenforceable for both sides.
  • Decide what "up" means during degradation. Your fallback ladder (11C.3) means the product can be "up" while the primary model is down — is degraded-mode service inside the SLA or a breach? Answer it in the contract, because the customer will answer it for you in a dispute.
  • Price the risk. Liability caps, service credits and exclusions for customer-supplied data or out-of-scope use belong in the same negotiation as the price — and the unit-economics sheet should carry the expected cost of credits, not just inference.
  • Beware the Goodhart SLA. A contractual quality floor rewards gaming the measured metric — the same trap as 1.6. If the SLA is "resolution rate ≥ 90%", expect pressure to resolve-by-deflection; pair every contractual metric with a guardrail metric.

Whether to publish an SLA at all is a product decision: early-stage features often ship "best efforts" terms and graduate to formal SLAs once the metric tree (Part 3) has months of honest data behind it. 13B.6's launch review is where the evidence for that decision gets assembled.

6.5 The cost curve: models and prices move#

Your unit economics are a snapshot of a moving target. The price history and the counter-trends (tokenizer changes, reasoning tokens, scheduled increases) are 11B.2, Part 3; the product view is:

  • Model prices change on announced schedules. 02.9, 6.8 documents introductory pricing with end dates (Gemini 4 Argon and 3.8 Flash both have dated increases as of November 2026). A margin model built on intro pricing is a margin model with an expiry date — put the price-change date in the spreadsheet.
  • New models reset the frontier. A model that was too expensive last quarter may be the cheap tier this quarter (02.9 tracks the landscape; 11B.5 owns routing between tiers). Re-run the unit-economics sheet on every model release — it's a 15-minute exercise that can save a bad contract.
  • Your own traffic mix drifts. If easy queries grow faster than hard ones, average cost falls — but so does average quality. Segment the economics by task difficulty, not just in aggregate.

6.6 Cost caps and budgets as product features#

The most underrated product decision in this lesson: the spend limit is a feature, not just a guardrail. Users, tenants and your own finance team all need to know "what happens when we hit the cap":

Mechanism What it does UX requirement
Per-user / per-tenant spend limit Hard cap on cost_usd per period Clear messaging before the cap; graceful degradation, not a wall (13A.4 owns the failure-state design)
Fair-use policy Soft cap with throttling or model downgrade Tell users the policy exists; don't surprise them mid-task
Degraded mode on budget Auto-switch to cheaper model / retrieval-only / queue 11C.4, 1.6 owns the mechanism; the product decision is which degradation users will tolerate
Budget alerts Warn at 50%/80%/100% of budget Alert the owner, not just the user — finance needs lead time
Cost-per-tenant reporting Show each customer their usage Enterprise features live or die on this report

The engineering side of these mechanisms is in 11B.6 (budget hierarchy, reserve-then-settle, downgrade or refuse) and 11B.7 (kill switches and spend alerts).

Design rule (borrowed from 11C.4): decide the degraded mode at design time, not during the incident. "What does the user see when the budget runs out?" answered in a design doc beats answered in a panic.

6.7 Levers and their product trade-offs#

Lesson 11B.1, Part 4 owns the optimisation playbook (the full treatment of each lever, with its engineering detail); lesson 11B.5 owns routing. The product-level view — what each lever costs you in UX or quality:

Lever Cost effect Quality/UX risk When it's safe
Prompt caching −30–70% input cost Low; prefix must stay stable Almost always — structure prompts for cache hits (04.x, 11B.3)
Smaller model tier −50–90% on easy tasks Quality drop on hard tasks With a router/cascade that escalates on failure (11B.5, 2.9)
Lower reasoning effort −30–60% output cost Worse on multi-step reasoning Per-task-type, not global — easy queries don't need max thinking (02.8)
Batch/async tier −50% Latency: minutes not seconds Only for non-interactive work (nightly jobs, evals, document batches)
Retrieval trimming −input tokens Missed context → wrong answers With retrieval evals proving the trim is safe
Human review sampling −review cost Missed bad outputs reach users Risk-tiered: sample high-risk, audit low-risk (13A.3)
Cheaper provider/route −10–40% Behavioural differences between hosts Evaluate the exact endpoint you serve (02.9)

What this means for you as an engineer: unit economics isn't a finance exercise you hand off — it's a design constraint you carry into every architecture decision. The cost_per_success number should sit next to the latency SLO and the quality threshold in every design review.


Part 7: Rollout and launch strategy#

Deep-dive

7.1 The stages#

An AI feature doesn't launch — it earns launch, stage by stage. Each stage has entry criteria, success criteria and exit criteria; skipping a stage is how prototypes become incidents.

Stage Who sees it Purpose Entry criteria Success criteria Exit criteria
0. Offline Nobody Prove it works at all Eval suite green on golden set Eval pass rate ≥ bar; failure modes catalogued Ready for dogfood
1. Dogfood Your own team Find the embarrassing failures cheaply Deployed to internal tenants only Team uses it daily for 1–2 weeks; top failure modes fixed or accepted Ready for design partners
2. Private beta 3–10 design partners Real workflows, real data, real feedback NDA/data agreements; support channel staffed; rollback tested Partners complete real tasks weekly; quality metrics hold; no SEV incidents Ready for staged rollout
3. Staged rollout 1% → 5% → 25% → 50% → 100% Catch scale and long-tail failures Guardrail dashboards live; on-call briefed; kill switch tested Guardrails green at each stage for a full business cycle GA or rollback
4. GA Everyone Run the business Launch review passed (11C.4, 7.2) North-star trending up; unit economics on plan Ongoing: quarterly metric review

Waitlists and invite-only launches sit between stages 2 and 3: they validate demand and pace onboarding, but they are not a substitute for dogfooding — a waitlist measures interest, not quality.

7.2 What each stage is actually testing#

  • Dogfood tests robustness on real-ish data: your team's actual documents, tickets and queries break assumptions that fixtures never will. The output you want is a ranked failure list, not compliments.
  • Private beta tests workflow fit: does the feature slot into how people actually work, or does it demand they change how they work? Watch for workarounds — a beta user who exports your output to edit elsewhere is telling you the edit-in-place UX failed.
  • Staged rollout tests scale and tail risk: the 1% slice hits the weird queries, the huge documents, the non-English inputs, the abusive users. Each stage should run for at least one full weekly cycle before expanding — weekend traffic differs from weekday.
  • GA tests operational readiness: the launch review (11C.4, 7.1–7.2) is the gate; this lesson's metric tree is what the review checks against.

7.3 Geography, segments and enterprise pilots#

  • Geography: roll out by region when data-residency, language coverage or regulatory requirements differ (02.9, Part 9). A feature that's fine in English may be materially worse in the next language — check per-language metrics before expanding.
  • Segments: B2B features often launch per-tenant or per-plan-tier first; the metric spec (1.2) should be sliceable by tenant_hash from day one so "how is Acme's rollout going" is a query, not a project.
  • Enterprise pilots: a paid or contracted pilot is the strongest signal — but define success criteria in the contract's language: which metric, what threshold, what happens if it's missed. A pilot without exit criteria is a free trial with extra steps.

7.4 Communication plan#

Launch is a communications exercise as much as a technical one:

Audience What they need When
Internal (support, sales, success) What the feature does, what it can't do, how to escalate, what to say when it's wrong Before private beta
Beta partners Expected quality level, feedback channel, known limitations At beta onboarding
All users at GA What changed, what "AI" means here, how to give feedback, how to opt out At launch + in-product disclosure (13A.3)
Leadership Metric tree status, unit economics, risk register Weekly during rollout

The support team's readiness is a launch gate, not an afterthought: every failure state in 13A.4's taxonomy needs a support macro and an engineering escalation path before GA.

7.5 When quality regresses after launch#

The playbook, in order:

  1. Detect — the metric tree fires (guardrail threshold breached, eval-suite score dropped, user reports spiking). 10A.9, Part 5 owns drift detection; 11A.2 owns the alerts.
  2. Contain — kill switch or feature flag off, degrade to the designed fallback (11C.4, 1.6). Rollback is a pointer move, not a redeploy.
  3. Diagnose — was it us (prompt/model/config change) or them (provider snapshot update, traffic-mix shift)? Check model_resolved and prompt_version distributions on the events (4.4).
  4. Fix — prompt hotfix through the 11C.2 pipeline, model pin/rollback, or retrieval fix. Freeze unrelated releases while the regression is live.
  5. Learn — the failure becomes eval cases (Part 5); the postmortem follows 11C.4, 1.7.

What this means for you as an engineer: the rollout stages are where the metric tree earns its keep. A feature that can't tell you "are we better than last week, on the metrics that matter" isn't ready for the next stage — regardless of how good the demo looked.


Part 8: Roadmapping with uncertainty#

Deep-dive

8.1 Why AI roadmaps are different#

A normal roadmap assumes the technology is stable and the uncertainty is in execution. An AI roadmap has uncertainty in capability: a model release can make next quarter's roadmap obsolete in a week, or make this quarter's "impossible" feature trivial. 02.9 documents how fast the landscape moves; the roadmap must assume it will keep moving.

8.2 Assumption mapping#

Before committing roadmap items, list the assumptions each depends on and rank them by cheapest test:

Assumption Cheapest test If false
"The model can extract fields at 95% accuracy on our documents" 50-document golden-set eval (hours, not weeks) Descope to human-in-loop or kill
"Users will accept AI-drafted replies" Wizard-of-Oz prototype (13A.1) Pivot to copilot-assist only
"Cost per task stays under $0.10 at scale" unit_economics.py sensitivity table Reprice, reroute, or kill
"Latency p95 stays under 8s for voice" Load test on real provider, measure not assume Change architecture or provider
"The provider won't deprecate this model mid-contract" Check lifecycle page + pin snapshot Multi-provider abstraction (03.11)

The discipline: test the assumption that kills the project first, not the one you're most curious about.

8.3 Time-boxed experiments#

For roadmap items too big to commit and too important to ignore: time-boxed experiments — a fixed period (2–6 weeks) with a fixed budget and a pre-registered decision rule. "Spend 3 weeks and $2k testing whether voice agents can handle our call volume; ship to 5% if resolution ≥ X and cost ≤ Y, kill otherwise." The time box is the point: without it, experiments become zombie projects.

8.4 Saying no#

The roadmap's most valuable output is what it doesn't contain. Saying no criteria:

  • The feature's north-star can't be articulated (1.3).
  • The unit economics don't work at any plausible price (Part 6).
  • The quality bar requires a capability the current models don't have — and no experiment can close the gap in the timeframe.
  • The maintenance cost (evals, monitoring, incident response) exceeds the value for the team's size.
  • It's a demo, not a product — works once on the happy path, fails on the 95th percentile (13A.1 owns this distinction).

A roadmap with no "no" column is a wishlist.

8.5 Portfolio view: now / next / later#

Horizon What goes there Review cadence
Now Features with proven unit economics, working evals, staffed support Weekly metrics review
Next Time-boxed experiments, beta features, cost-reduction levers Monthly decision review
Later Capability-dependent bets (wait for model X), strategic options Quarterly revisit; kill stale items explicitly

The "later" column is where AI roadmaps die — items sit for a year becoming someone's quiet disappointment. Review them quarterly and either promote, kill, or restate the trigger condition ("revisit when reasoning models support X").

Make release-watching a ritual, because capability is the input that moves: subscribe to each provider's model and changelog pages (02.9 tracks the landscape as of November 2026), and treat every new tier as a roadmap event, not just a cost event. When a new model ships, re-run the 6.3 sensitivity sheet against your TaskProfiles and re-score the Later column — a capability that was too expensive last quarter may now be the cheap tier, and a "wait for model X" item may have quietly become buildable. The same release watch feeds 6.5: prices, deprecations and new tiers all land on the same changelog.

What this means for you as an engineer: your roadmap credibility comes from what you didn't build as much as what you did. A team that ships three things well beats a team that ships ten things poorly — and the metric tree is how you prove which is which.


Where you'll use this#

This lesson is the measurement and economics spine for the rest of Modules 13A and 13B and beyond:

  • 13B.1 Capstone Planning uses the metric spec and unit-economics sheet as scoping inputs — a capstone without a north-star and a cost model isn't scoped, it's dreamed.
  • 13B.2–13B.5 Capstone Builds instrument their products with the 2.2 event schema, run metrics.py on their traffic, and fill the unit-economics sheet for their specific shape (copilot, document pipeline, voice agent).
  • 13B.6 Shipping applies the Part 7 rollout stages and the decision-memo discipline to the launch.
  • Module 14B Career — the metric tree, experiment memos and unit-economics sheets are exactly the artefacts that make a portfolio project legible to employers: they show you built a product, not a demo.
  • Every AI job you'll ever have — the questions "what's the north-star", "what does a resolved ticket cost", "how do we know the new model is better" are the questions this lesson teaches you to answer with numbers instead of opinions.

Common misconceptions#

Misconception Reality
"More metrics = better decisions." A dashboard of 40 numbers with no north-star produces arguments, not decisions. One metric per layer, checked weekly, beats everything.
"The eval score is the product metric." Eval scores are offline quality measures. Product metrics are what users do and what it costs. You need both — 10A.9, 1.1 owns the distinction.
"A/B testing is only for growth teams." Every prompt change, model swap and UX tweak is an experiment candidate. The discipline is the same; the stakes are higher because the system is probabilistic.
"Statistical significance means we should ship." Significance answers "is the difference real". Shipping also needs practical significance (is it big enough to matter), guardrails passing, and a decision memo.
"Cost per API call is the unit cost." The unit is the successful task. Retries, failures, review and infra all belong in the denominator — 6.2.
"Cheaper model = better margins, always." Only if quality holds. A cheaper model that drops success rate 10% can raise cost per success — run the sensitivity table before deciding.
"We can A/B test prompts like we A/B test button colours." Prompt experiments face cache interference, novelty effects and silent model updates that UI experiments never see — 4.4.
"Thumbs-up rate measures quality." It measures politeness, position and frustration-escape as much as quality — 10A.9, 2.5 quantifies the bias; Goodhart makes it worse when it's a target.
"Once launched, the metrics take care of themselves." Metrics drift, definitions diverge, dashboards accumulate contradictions. Quarterly metric reviews and a named owner per metric are the maintenance cost.
"Holdouts are unethical / wasteful." A 2–5% holdout for a bounded period is standard practice and the only way to measure cumulative effect. The ethical obligation is to time-box it and act on what it shows.
"Unit economics is a finance problem." It's a design constraint. The pricing model, the autonomy dial, the review sampling rate and the model tier are all unit-economics decisions made in design, not in a spreadsheet after launch.

Key takeaways#

  • The metric tree has six layers — business outcome, usage, quality, experience, safety, cost — and a healthy product has numbers at every layer. Pick one north-star that reflects customer value and is actionable; pair it with guardrails that veto bad wins.
  • Goodhart's law is the central risk. Any metric made a target degrades: thumbs-up rates reward sycophancy, usage metrics reward nagging, resolution rates reward confident wrongness. Defend with guardrails, denominator discipline and qualitative audits.
  • Instrument early, join everything. Product events join to traces via request_id/trace_id and to eval cases via case_id; the 2.2 schema is small enough to implement on day one. Hash identifiers, never send content you don't need, and write the retention schedule down.
  • metrics.py computes the scorecard — completion, acceptance, edit distance, escalation, abandonment, latency percentiles — per feature/variant/day, with denominators printed so nobody argues about them.
  • Experiment design is 10A.9's job; this lesson adds the AI traps — cache interference, novelty effects, silent model updates, multi-dimensional quality — plus holdouts, model-upgrade experiments and the decision memo.
  • experiment.py does the arithmetic — two-proportion z-test for binary metrics, bootstrap CIs for continuous ones, sample-size and MDE calculators — all stdlib, all reproducible.
  • Unit economics decides pricing. Cost per successful task — not per call — is the number that matters; retries, failures, review and infra all count. The support-copilot example shows human review can dominate the model bill by more than 10× ($0.25 of review against $0.016 of model calls).
  • Every cost lever is a product decision. Caching, smaller models, lower reasoning effort, review sampling — each trades quality or UX for margin. Run them through the eval gate with an explicit acceptable-regression budget.
  • Pricing models have traps. Outcome-based pricing aligns incentives but invites Goodhart and needs verification; usage-based is unpredictable for buyers; seat-based hides cost signals. Choose deliberately, price on cost-per-success, and revisit when model prices change.
  • Cost caps are features. Spend limits, fair-use policies and degraded modes need designed UX before launch — "what happens at the cap" is a design-doc question, not an incident question.
  • Roll out in stages. Dogfood → private beta → staged % → GA, each with entry/success/exit criteria. The metric tree is the instrument that tells you when to advance or roll back.
  • Roadmap with assumptions, not dates. Map assumptions to cheapest tests, time-box experiments, maintain a "later" column with explicit kill/revisit triggers, and say no when the north-star or unit economics can't be articulated.

Terms introduced in this lesson#

Term One-line definition
Metric tree The six-layer hierarchy of product metrics: outcome → usage → quality → experience → safety → cost
North-star metric The single number that best captures whether the product delivers value; must be valuable, predictive, actionable and simple
Overall Evaluation Criterion Experimentation literature's name for the primary decision metric (Kohavi, Tang, Xu)
Guardrail metric A must-not-regress number that vetoes a release or winning variant
Vanity metric A number that rises whether things are going well or badly; can't distinguish them
Leading vs lagging indicator A metric that predicts the outcome vs one that confirms it after the fact
Goodhart's law "When a measure becomes a target, it ceases to be a good measure" (Strathern 1997, after Goodhart 1975)
Product event A sparse per-task analytics record (task_started, task_completed, draft_accepted...) joining to traces and eval cases
Join key The shared identifier (request_id, session_id, case_id, variant) that links product events to traces, evals and experiments
Acceptance rate (unedited) Share of AI drafts used without human edits — headline quality-usage metric
Edit distance Normalised Levenshtein between AI draft and human-sent version; 0 = untouched
Straight-through processing rate Share of documents shipped with zero manual correction
Deflection rate Share of contacts resolved without a human agent
Holdout A small permanent control group that never receives the feature, for measuring cumulative effect
Decision memo The written record of an experiment's question, design, results and decision
Data flywheel The loop: production traffic → labelled cases → eval sets → better prompts/models → deploy → measure
Feedback-loop bias Corruption of the flywheel by survivorship, position, verbosity or sycophancy effects
Cost per successful task Total cost of started tasks ÷ successful outcomes — the pricing-decision number
Gross margin (AI feature) (price − cost per success) / price
Outcome-based pricing Charging per verified result (resolved ticket, extracted field) rather than per use
Cost cap / spend limit A product feature bounding per-user/tenant/feature spend, with designed degradation
Time-boxed experiment A roadmap probe with fixed duration, budget and pre-registered decision rule
Assumption mapping Listing what a roadmap item depends on and testing the cheapest-to-falsify first
Dogfooding Running the feature on your own team's real work before external users see it
Staged rollout Gradual traffic increase (1% → 5% → 25% → 50% → 100%) with guardrail checks per stage

All terms are also collected in the glossary.


Exercises#

All exercises run without API keys.

  1. Metric spec (Part 1): For the support copilot in 13B.2, write the one-page metric spec: pick a north-star, three guardrails with thresholds, and five diagnostic metrics. Justify each choice against the four north-star tests in 1.3.
  2. Goodhart audit (1.6): Your manager proposes "increase weekly active users of the AI assistant by 20%". Write three ways this metric gets gamed, and redesign it so the gaming paths close.
  3. Aggregation (2.3): The lesson ships events_sample.jsonl with this lesson. Add 10 synthetic events for a third variant and re-run metrics.py. Does the treatment arm's higher acceptance rate survive? What would you need to conclude anything?
  4. Sample size (4.3): A prompt change is expected to lift task completion from 62% to 65% — a 3-point lift. Use experiment.py's sample_size_per_arm to compute the required sample. If the feature only sees 400 tasks/day split across two arms, how long must the experiment run? Is that acceptable?
  5. Z-test and memo (4.7, 4.9): Using the z-test output in the lesson (control 30.6%, treatment 35.1%, p=0.0024), draft the "Results" and "Decision" sections of the decision memo. What additional information do you need before writing "Ship"?
  6. Heterogeneous effects (4.7): The experiment wins overall but you suspect it only works for English-language tickets. Design the slice analysis: which slices, what correction for multiple comparisons, and how would you report an underpowered slice honestly?
  7. Unit economics (6.3, 6.4): Build the unit-economics sheet for the support copilot under three price scenarios — $0.75, $1.50 and $2.50 per resolved ticket — using support_copilot() and sensitivity_table across success rates 50–80%. At which price/success combinations does gross margin go negative, and which single lever (price, success rate, model tier, review sampling) moves the margin most? Then swap in a document-intelligence TaskProfile (12,000 input tokens, 50% cached, 800 output tokens, 1.1 attempts/task, $0.004 tool cost, $0.02 review cost at 5% sampling, $0.005 infra, 85% success rate, $4.00 per document): which cost line dominates now, and does the model-tier choice matter more or less than for the copilot?
  8. Pricing model (6.4): Your voice agent costs $0.18 per completed booking call and saves customers an estimated $4 in handle time. Compare seat-based, per-minute, and per-booking pricing for a customer doing 500 calls/month. Which aligns incentives best, and what's the verification burden of each?
  9. Rollout plan (Part 7): Write the stage-gate table for your own capstone project: entry/success/exit criteria for dogfood, private beta and first staged rollout. What's the single most likely failure at each stage?
  10. Roadmap (Part 8): Take one item from your capstone plan and write its assumption map: three assumptions, the cheapest test for each, and the "if false" consequence.
  11. Guardrails for a voice agent (3.7): Pick a north-star and three guardrail metrics for the realtime voice agent in 13B.5. Justify the north-star against the four tests in 1.3, and for each guardrail state the metric, the threshold and the action on breach — using the voice row of the 3.7 decision table as your starting point.
  12. Agent metrics (3.6a): For an agent that books travel, pick the verified-success definition (what does the system of record show?), the budget limits you would set, and the two metrics you would put on the on-call dashboard. Which one would you alert on first, and why?
Hints and worked numbers for the exercises
  1. A defensible support-copilot spec: north-star "cost per resolved ticket" (or resolved tickets per agent-hour), guardrails on groundedness (sampled judge), escalation latency and cost per started task, diagnostics such as acceptance rate, edit distance, time to first useful output, abandonment and citation click-through. Test each against the four tests in 1.3 and write why a rejected candidate (for example "drafts accepted") fails the "actionable and not gameable" test.
  2. Ways to game weekly active users: default-on prompts and nudges, counting opens rather than tasks, re-labelling any page view as "use". A redesign: weekly tasks completed with an accepted outcome, paired with a guardrail on acceptance quality and a retention check.
  3. With a handful of events the acceptance difference is noise: you need a pre-computed sample size (see 4) and the same instrumentation on both arms before any conclusion.
  4. sample_size_per_arm(0.62, 0.03) returns 4,039 per arm (two-sided, 5% significance, 80% power), so about 8,078 tasks in total. At 400 tasks a day that is roughly 20 days, so plan about three weeks, which also spans full weekly cycles. Whether that is acceptable depends on the cost of the experiment (4.3) and how long you can run a prompt change before the model or traffic shifts.
  5. "Results": state both rates, the +4.5 point difference and its 95% interval (+1.6 to +7.4 points), and the guardrail outcomes. Before writing "Ship" you need: guardrails (groundedness, cost per task, escalation, p95 latency) passing, an SRM check, the model_resolved distribution, a novelty check on week 2 versus week 1, and the slice results.
  6. Pre-declare 2 to 4 slices (language, tenant tier, ticket type), mark them exploratory, use a stricter threshold or a correction for the number of slices, and report an underpowered slice as "no evidence either way, needs more data", never as "no effect".
  7. With support_copilot() and Sonnet prices, cost per success is about $0.45 at 60% success and about $0.54 at 50%, so margin stays positive at $0.75 even at 50% success (about +28%); the sheet only turns negative below roughly $0.54 per success at 50% success. Success rate and review cost move margin most; the model tier moves it least. For the document profile on Sonnet prices, started-task cost is about $0.052: model calls about $0.023 (44%), review $0.020 (38%), tools $0.004 (8%), infra $0.005 (10%). Here the model tier matters much more: Haiku-tier prices cut started-task cost to about $0.031. Check these against your own run, since prices are parameters.
  8. Per-booking pricing aligns best (customer pays only for success) but needs a verified definition of "booking"; per-minute rewards slow calls; seats ignore volume. At 500 calls a month your cost is about $90 (500 × $0.18) if every call is completed, so even a $1 per booking price leaves a wide margin; the question is what the customer will pay relative to the $4 they save, and who verifies the bookings.
  9. Typical most-likely failures: dogfood finds the embarrassing long-tail inputs, private beta finds a workflow mismatch (users export to edit elsewhere), staged rollout finds the cost or latency tail at the 5% to 25% step.
  10. A good assumption map names the assumption that would kill the project first and gives a test that costs hours (a 50-example eval, a Wizard-of-Oz session), not weeks.
  11. For the voice agent: north-star "tasks completed to a verified outcome"; guardrails such as p95 turn latency, barge-in success rate and cost per minute; each with a threshold and a named action (page, freeze, roll back).
  12. Verified success: the booking exists in the reservation system with the right dates and traveller; limits: maximum steps, wall-clock time and spend per run; dashboard: verified task success and budget-trip rate (the first tells you users are served, the second tells you the safety nets are firing). Alert first on a drop in verified success, since a rising trip rate usually follows it.

Check yourself#

  1. What are the six layers of the AI-product metric tree, and which layer does "eval suite score" belong to?
  2. Why is "cost per API call" the wrong denominator for pricing an AI feature?
  3. What four tests must a north-star metric pass?
  4. Name three AI-specific vanity metrics and why each fails.
  5. How does Goodhart's law apply to a thumbs-up rate target?
  6. What are the three event layers, and which join keys connect them?
  7. Why must user_hash be a hash and not a raw user ID in product events?
  8. What is the difference between the randomisation unit "user" and "task", and when would you choose each?
  9. What are the four AI-specific experimental traps, and what's the defence for each?
  10. What is a holdout, and what question can it answer that an A/B test cannot?
  11. When should you use a two-proportion z-test vs a bootstrap confidence interval?
  12. Why does the support-copilot example show model tier choice barely matters for unit economics?
  13. What are the three components of cost per successful task that people most often forget?
  14. What's wrong with outcome-based pricing, and what mitigates it?
  15. What are the four rollout stages, and what does each one actually test?

Further resources#


The ai_product package so far#

Files introduced across the capstone to date (this lesson adds the last three; 13A.7 adds case_card.py, 13B.1 adds scope_check.py and scaffold.py, and 13B.6 adds the final launch_review.py, system_card.py and demo_script.py; the consolidated map is 13B.1's appendix):

text
ai_product/
  feature_brief.py      # 13A.1 — the AI feature brief + use-case scorer
  events.py             # 13A.2 — the stream event contract
  smoother.py           # 13A.2 — perceived-speed token pacing
  progress.py           # 13A.2 — stage/progress states
  approval.py           # 13A.3 — human-in-the-loop approval gate
  review_queue.py       # 13A.3 — reviewer inbox
  feedback.py           # 13A.3 — feedback capture -> eval pipeline
  failure_ui.py         # 13A.4 — signal -> typed UserMessage
  copy_catalog.py       # 13A.4 — i18n copy catalogue
  markdown_safety.py    # 13A.4 — rendering-safety sketch
  a11y_lint.py          # 13A.4 — WCAG checklist linter
  ports.py              # 13A.5 — ModelPort/RetrieverPort/JobStorePort abstractions
  jobs.py               # 13A.5 — in-process job runner (states, idempotency)
  app.py                # 13A.5 — FastAPI app factory over the ports
  metrics.py            # 13A.6 — THIS LESSON: product-event aggregator
  experiment.py         # 13A.6 — THIS LESSON: experiment statistics (z-test, bootstrap)
  unit_economics.py     # 13A.6 — THIS LESSON: cost-per-success + pricing calculator

← 13A.5 — Architecture Patterns for AI Applications | Module 13A overview | 13A.7 — Case Studies: How Real AI Products Are Built, and How They Fail →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close