Ultra deep dive · Post-training · Systems
RL Data Platform
How a research data idea becomes human and AI-assisted feedback in the training mix of a frontier model: campaign scoping and launch, samples from live model endpoints, feedback interfaces, quality and annotator integrity, pipelines and lineage, data value, AI in the loop, workforce and operations, with three reference workloads traced at every level.
Summary
- An RL data platform is a loop, not a labelling tool: a data idea becomes a campaign, the campaign draws samples from live model endpoints, people judge them through purpose-built interfaces, structured feedback passes quality checks, becomes a training signal, enters the training mix, and the resulting model produces the next samples. Five north-star metrics run it: time to first sample, request-to-mix latency, cost per useful label, label quality and the researcher self-serve rate (The loop, North-star metrics).
- Cost per useful label is a product of three factors you can diagnose separately: cost per assignment × overhead × 1/yield. For reference workload W1 that is $3.00 × 1.263 / 0.92 ≈ $4.12 per useful comparison. An interface that cuts mean time from 4.5 to 4.0 minutes saves 11%; doubling overlap costs 17%. Generating the samples is under 1% of the bill ($344 against $75,780 of labour) (Metrics, Unit economics).
- Inter-rater agreement sets a ceiling and an information content. W1's 72% pairwise agreement implies each rater is right about 83.2% of the time, so a request for 85% accuracy against single labels is infeasible, and the 18,400 useful comparisons are worth about 8,100 noise-free ones. Overlap is a measurement cost, not a way to buy signal (Scoping, Reward models).
- Individual raters cannot be judged from production gold. W1's 5% gold gives each rater about 8.4 gold items, a standard error near 0.14. Judge raters on qualification gold (a sequential test needs about 23–29 items), weight their work with an annotator-reliability model, and act only when two independent signal families agree: that raises flag precision from 0.40 to 0.91 (Measuring quality, Detection).
- Generation cannot sit on the rater's path. A W1 pair takes about 16 s at the median and 30 s at p95 to generate, against a 2 s target, so a pre-generated buffer of 2,000 pairs serves raters and turns an endpoint outage into a countdown: about 60 minutes of runway at 150 active raters. Pin checkpoints by digest, never by alias, and let only one layer retry (Generation path, Reliability).
- Request-to-mix is a value stream whose constraint is collection capacity. W1's 21-day baseline has a flow efficiency of 39%. The plan of record reaches 7.0 days with a templated spec, a one-day pilot, a 4.0-day collection that needs about 10.5% more scheduled rater-hours, QA and export streaming behind collection, and a pre-booked retraining slot. Reserve rater-hours at launch (Request-to-mix path).
- Data value is measured, not assumed. A leave-W1-out ablation gains 4.0 ± 0.9 points of reward-model accuracy, about $18,900 per point; the scaling curve gives about one point per doubling, so the next point costs about $75,800. A follow-up campaign on near-identical checkpoints added 0.1 point because 41% of its pairs were low-margin (Data value).
- AI belongs in the loop as a routed first pass and as assistance, measured against humans. A judge calibrated on W1's overlap keeps 56% of items at human-level agreement and cuts cost per useful comparison from $4.12 to about $1.99. Showing an AI hint before the expert judges makes experts follow wrong hints 27% of the time against a 10% baseline; showing it after keeps them at 12%. Humans stay essential for criteria, expert judgement, ground truth and novel failures (AI judges, Interface experiments, Where humans remain essential).
- The data path must be replayable. Keep raw feedback as immutable events, derive every training example with a versioned transform, and block training on an export contract. Inverted sides, ties exported as votes and partial credit read as full credit were all recoverable by re-export because the raw records were intact (Data model, Lineage, Runbooks).
Reference workloads used in this book
The book traces three reference workloads. All their numbers are illustrative, identical at every level and not drawn from any organisation's data. Chapters refer to them as W1, W2 and W3 and keep workload-specific material in "Worked example" callouts; this box is the specification those callouts assume.
W1 · Pairwise preference campaign for coding helpfulness (illustrative). The primary workload. A researcher needs comparisons to improve a coding reward model.
| Parameter | W1 value |
|---|---|
| Goal | 20,000 pairwise comparisons for a reward model: 10,000 coding prompts × 2 response pairs |
| Generation | Two responses per comparison from live endpoints (current checkpoint vs candidate); pre-generated buffer of 2,000 pairs; time to first sample p50 ≤ 2 s, p95 ≤ 5 s |
| Overlap and gold | 10% of items (2,000) labelled by 3 raters, 18,000 by one → 24,000 labels. Gold is 5% of assignments → ≈ 25,260 assignments |
| Rater pool | 150 trained vendor raters × 20 h/week = 3,000 rater-hours/week |
| Time and cost | Median 4.0 min, mean 4.5 min per label → ≈ 1,895 rater-hours ≈ 0.63 pool-weeks. $40/h → labour ≈ $75,780. QA rejects 8% → ≈ 18,400 useful comparisons → ≈ $4.12 per useful comparison |
| Quality | Gold accuracy threshold 80%; pairwise agreement on overlap 72%; ties 8%; 4% of raters flagged for low effort (median time under 40 s) |
| Request-to-mix | Baseline 21 days: scoping 3, guidelines + pilot 4, collection 6, QA 3, pipeline/export 2, reward-model retrain + mix inclusion 3. Target 7 days |
W2 · Expert review of long agentic transcripts (illustrative). 2,000 agent transcripts, mean 60 steps and about 25,000 tokens. Experts mark the first failing step, label the failure type and write a corrected continuation of about 400 words. 40 domain experts × 15 h/week; 35 min per transcript → ≈ 1,167 expert-hours; 10% double-reviewed (+≈ 117 h). $120/h → ≈ $140,000 (+≈ $14,000), about $70 per transcript. Agreement on the first failing step: 58% exact, 81% within ±2 steps. Interface: render ≤ 1.5 s, jump-to-step, replay of recorded tool outputs.
W3 · A new feedback type: rubric data for non-verifiable RL (illustrative). Legal drafting, 3,000 prompts. Experts write a rubric of 8–12 weighted items (mean 10) per prompt, about 25 min each → 1,250 expert-hours. Graders score 4 responses per prompt against it, about 2 min each → 400 hours. An AI grader then applies the rubrics as the RL reward, gated on item-level human–AI agreement ≥ 0.8. Needs a new schema (rubric, item, weight, score), a new interface and a new export to the RL reward service.
One-Pager: The RL Data Platform End to End
An RL data platform is a production system whose output is training signal. Its users are researchers who need data, the people who give feedback, and the training jobs that consume it. Its dependencies are model endpoints it does not run. This page puts the whole system on one screen: the loop, the components, the decisions, the numbers and the build order. The defaults are general; the numbers are those of reference workload W1 (Reference workloads).
The Loop on One Screen
Work moves left to right along the top row, from a research need to stored feedback, and right to left along the bottom row, from quality checks to a new model. Two returns close the loop: a new checkpoint becomes the source of the next samples, and evaluation turns gaps into the next data idea. Every stage runs on the shared services underneath (The end-to-end loop, Service architecture).
The Components
- Intake and campaign spec. Turns "we need 20k coding pairs" into a typed spec: consumer and decision, task, guidelines version, population, overlap, gold, budget, stopping rule. Design choice: the spec is a data model with a validator that computes labels, assignments, hours and cost on every edit and refuses infeasible targets, such as an accuracy above the agreement ceiling or a cost above the cap (Scoping, The spec).
- Launcher and pilot. Preview, dry run and calibration rounds before production labels. Design choice: a dry run on 150 items through every stage, synthetic labels included, catches a 2% render or export defect with probability 0.95; a pilot sized for ±5 points of agreement (310 items for W1) decides go or revise on interval bounds, not point estimates (No-code launcher, Pilots).
- Prompt selection. Chooses which prompts reach humans. Design choice: deduplicate, keep a difficulty band where the current checkpoint sometimes succeeds, fill stratified quotas, and spend only part of the budget on active selection (30% by reward-model ensemble disagreement in W1), with a per-cluster cap so the active slice cannot take over (Prompt selection).
- Sampler and buffer. Calls live endpoints and packs responses into items. Design choice: generate ahead into a buffer with watermarks and backpressure, address checkpoints by immutable digest, run a client-side token bucket below the provider limit, allow exactly one retry layer, and fall back to serving overlap repeats and gold when the runway is short (Generation path, Time to first sample, Reliability).
- Assignment. Answers "next item for this rater" with a lease. Design choice: a pull queue with time-limited leases (15 minutes in W1, above the 99th-percentile label time), gold mixed in per pull, overlap with distinct raters, skill segments, and a per-rater cap of twice the fair share so fast, low-effort raters cannot take a fifth of the campaign (Assignment).
- Feedback interfaces. Pairwise comparison with strength and tie, rubric editor and scorer, long-transcript reviewer. Design choice: randomise sides per assignment and record what was shown where, instrument active time and paste events, give transcript reviewers jump-to-step and recorded tool-output replay, and reveal any AI suggestion only after the person has judged (Interface types, Transcripts, Designing for quality).
- Feedback store and data model. The source of truth. Design choice: immutable, versioned events (submitted, retracted, QA verdict) folded into derived records; schemas in a registry with a compatibility rule; a new feedback type is new event types plus a transform, never an in-place migration (Data model).
- Quality service. Scores every label as it arrives. Design choice: production gold watches the pool for drift while qualification gold judges individuals; an annotator-reliability model (Dawid–Skene) turns single labels into soft targets; removal requires two independent signal families; review tiers sample 5% (peer) and 1% (expert) (Measuring, Aggregating, Detecting, Program).
- Pipeline: transforms, gates, lineage. Converts accepted feedback into training examples. Design choice: pairs grouped by prompt with an explicit tie policy and vote-share weights; six blocking gates (schema, row rules, near-duplicates, decontamination against evaluation suites, PII and secrets, dataset rules); content-addressed dataset versions with a lineage graph that can find and remove one rater's labels downstream (Transforms, Validation, Lineage).
- Mix interface and data value. Hands datasets to reward models and RL, and measures what they were worth. Design choice: an export contract (row count, tie count, label shares) checked when the training job starts; ablations on a pinned evaluation set with paired standard errors; scaling curves and source-level Shapley values for budgeting (Consumers, Data value).
- AI in the loop. Critique and retrieval assistance for humans; AI judges as a routed first pass. Design choice: route by judge confidence with a threshold calibrated on human overlap labels, a random human audit of kept items, and provenance on every label; never pre-fill the verdict being collected (Assistance, Judges, Boundary).
- Workforce and vendors. Crowd, managed vendors, domain experts and internal staff. Design choice: vendors' workers open the platform's own interface, so gold, timing and experiments are identical across vendors; results are reconciled against vendor records; pay is set from the measured mean time including overhead; harmful content goes only to opted-in people under an exposure budget (Populations, Vendors, Pay, Welfare).
- Control plane. Dashboards with an item inspector for researcher self-serve, access control on pseudonymous ids, secret scanning before anything is served, retention rules, a cost ledger with estimate-at-completion, and runbooks for endpoint outage, quality collapse, fraud, schema break, data leak and vendor shortfall (Self-serve, Governance, Cost, Runbooks).
The Decisions
| # | Decision | Default | Deviate when | Read |
|---|---|---|---|---|
| 1 | Signal type | Pairwise preference with a strength rating and an explicit tie for subjective quality such as helpfulness. Responses from two pinned checkpoints, sides randomised. | A cheap, trusted check exists (unit tests, a verifier): use it, not people. The domain is expert and non-verifiable: rubrics written by experts and applied by a calibrated grader (W3). Agent transcripts: first failing step plus a corrected continuation (W2). | Signals, Interfaces |
| 2 | Overlap | Single-label most items; multi-label about 10% with 3 raters to estimate agreement and flip rate. Treat overlap as measurement. | The data is an evaluation set or must exceed the single-label ceiling: 3 raters on those items. Agreement is unknown for a new task: more overlap in the pilot only. | Reward models, Aggregation |
| 3 | Gold | Qualification gold judges individuals with a sequential test; about 5% production gold detects drift across the pool; a smoothing prior for new raters. | Gold cannot be written for the task (expert judgement): adjudicated double review replaces it, as in W2's 10%. | Measuring, Pilots |
| 4 | Generation mode | Pre-generated buffer from digest-pinned checkpoints, sized to cover an endpoint outage (runway, not latency, sets its size); flush on checkpoint change. | Live multi-turn sessions or strictly on-policy samples: on-demand generation with streaming and warm capacity, and an interface that tolerates the wait. | Generation, Latency |
| 5 | Assignment | Pull queue, leases above the p99 label time, per-rater cap at 2× fair share, skill segments, no repeats of an item to a rater. | Scarce experts on long items: push scheduling of specific items to named experts with adjudication queues. | Assignment |
| 6 | AI assistance | Critiques and retrieved context, revealed after the person's own judgement; never a pre-filled verdict for the label being collected. | A randomised experiment shows the follow-wrong rate within a set guardrail (5 points in W2) and the time saving holds. | Assistance, Experiments |
| 7 | AI judges | First pass on every item; keep its label above a threshold calibrated so kept labels agree with humans at least as often as humans agree with each other (lower bound); audit 5% of kept items; record provenance. | Judge–expert agreement trails expert–expert agreement, or the label is a value judgement about whose preferences count: no coverage. Policy or checkpoint changes: recalibrate before restoring coverage. | Judges, Boundary |
| 8 | Data model | Append-only events with versioned schemas in a registry; derived records and datasets rebuilt by replay; responses stored once by content hash. | A one-off throwaway dataset: a flat file is acceptable, provided the raw labels and the side each response was shown on are kept. | Data model, Lineage |
| 9 | Quality enforcement | Continuous during collection; act on a rater only when two independent signal families agree; review, retrain, then remove. | Evidence of fraud that has no innocent explanation (shared accounts, identical answer vectors with shared wrong answers): pause at once and walk lineage. | Detection, Program |
| 10 | Population | Managed, trained vendor raters through the platform's own interface for general tasks; domain experts for criteria, gold, adjudication and expert labels. | Throughput matters more than consistency and the task is simple: a self-serve panel, with stronger gold and detection. Value judgements: the population is part of the specification. | Populations, Vendors, Vendors landscape |
| 11 | Request-to-mix | Templated spec, one pilot round, QA and export streaming behind collection, rater-hours reserved at launch, a pre-booked training slot. | The pool cannot supply the reserved hours: cut work per useful comparison (lower overlap, a faster interface) or accept a longer collection. Never skip the pilot. | Request-to-mix |
| 12 | Pay | Hourly, or per item priced from the measured mean time including unpaid overhead, so a careful worker earns the target rate. | Item times vary widely and are hard to predict (W2): hourly with effort monitoring, not per-item piecework. | Pay and incentives |
Table. The design decisions in roughly the order a campaign meets them, each with the default the book argues for and the condition that justifies deviating.
The Numbers on One Card (W1)
These are the numbers of reference workload W1 (Reference workloads). They are illustrative and the same at every level of the book. Use them as the baseline a real campaign dashboard is compared against (Metric catalogue).
| Area | W1 value | Default target or alert |
|---|---|---|
| Volume | 20,000 comparisons → 24,000 labels → about 25,260 assignments (1,263 gold), about 168 per rater. 1,895 rater-hours: 0.63 pool-weeks, 4.42 pool-days (Spec) | Launcher refuses a reservation above the pool's free capacity |
| Cost | $3.00 per assignment; labour $75,780; 18,400 useful comparisons; $4.12 per useful comparison ($4.14 with $344 of generation). Quality spend about $20,500, a quarter of labour, overlap the largest part (Cost, Program) | SLO $4.53 (plan + 10%); alert when estimate-at-completion passes 110% of plan |
| Latency and supply | Pair generation 16 s median, 30 s p95. Served from a 2,000-pair buffer: about 60 min of runway at 150 active raters (33.3 pairs/min) (Generation, Reliability) | TTFS p50 ≤ 2 s, p95 ≤ 5 s; runway alert at 20 min; brownout to overlap repeats and gold |
| Quality | Agreement 72% on 2,000 overlap items (κ ≈ 0.51; implied rater accuracy 0.832; majority of 3: 0.925). Ties 8%. Gold 8.4 items per rater. 6 raters (4%) under 40 s median (Measuring) | Gold ≥ 80%; agreement shifts of about 5 points are outside the ±2-point sampling error; tie rate under 15% in the pilot |
| Signal | Implied flip rate 0.168, about 8,100 clean-equivalent comparisons. 1,472 ties; about 16,930 strict pairs; about 840 split-vote rows at weight 0.67 (Reward models, Transforms) | Export contract: tie count and label shares within 0.5 points of the data card; side balance within 3 standard errors |
| Value | Leave-W1-out ablation 64.5% → 68.5%: +4.0 ± 0.9 points, about $18,900 per point. One point per doubling; next point about $75,800. Shapley 7.09 of 18.5 points (Data value) | Report the interval; a follow-up must beat its scaling-curve prediction |
| Request-to-mix | Baseline 21 days (3 · 4 · 6 · 3 · 2 · 3), flow efficiency 39%. Plan of record 7.0 days: 0.5 · 1.0 · 4.0 · 0.25 · 0.25 · 1.0, with 474 rater-hours a day, about 10.5% more scheduled hours from the same 150 raters (Request-to-mix) | Collection burn-up below 85% of plan for 12 h: check mean time, active rater-hours, buffer depth, in that order |
| AI routing | Judge keeps 56% of items; human share 0.468 with a 5% audit; $1.99 per useful comparison; 1,895 → 887 rater-hours (Judges) | Page when the audit's upper bound falls below 0.72; coverage to zero until recalibrated |
Table. W1 on one card. Chapter 1 sketches a simpler 7-day plan that compresses collection into 3 days and would need about 1.47 times the whole pool; the plan of record, from the request-to-mix path, instead overlaps QA and export with a 4.0-day collection and needs about 10.5% more scheduled rater-hours.
Build It Step by Step
The order follows dependencies: each step gives the next one something real to run against. Chapter 12 builds a minimal version of every step and runs it end to end (A minimal platform).
- The spec and its arithmetic. A typed campaign spec and a pure function that returns labels, assignments, hours, cost, useful labels and warnings (such as 8.4 gold items per rater). Every later screen and check reuses it (The spec, Launch checklist).
- The event log and schemas. Envelope plus typed payloads, a schema registry, a fold from events to records, and a replay that rebuilds everything from raw events (Data model).
- The sampler and buffer. Digest-pinned model references, watermarks, a client rate limiter, one retry layer with jittered backoff, and a runway metric (Generation, Reliability).
- Assignment. Leases, gold mixing, overlap with distinct raters, fair-share caps and near-duplicate removal (Assignment).
- The first interface. Pairwise comparison with strength and tie, randomised sides recorded per assignment, and timing and paste instrumentation (Interface types, Designing for quality).
- Quality and the dashboard. Gold scoring, agreement with intervals, effort flags, the reliability model, and the campaign dashboard with an item inspector (Measuring, Aggregating, Self-serve).
- Transform, gates and registry. The pair transform with tie policy and weights, the six validation gates, content-addressed dataset versions, lineage, and the export contract the training job checks (Transforms, Validation, Lineage).
- Launcher and pilot. Preview, a dry run through every stage with synthetic labels, and a pilot procedure with go/revise rules (Launcher, Pilots).
- The test ladder. Unit tests, replay of recorded campaigns, a shadow campaign, then staged rollout, with the gates written down before results are seen (Test ladder).
- Launch with runbooks. Capacity reservations, alerts on runway, burn-up, agreement and cost, an on-call rotation and the six runbooks (Launch and run, Runbooks).
- Measure value. Ablations on a pinned evaluation set, scaling curves and source-level attribution, so the next campaign is budgeted on evidence (Data value).
- Add a new feedback type. W3's rubric: schema, interface, transform, export to the reward service and the grader agreement gate, through the same ladder (Adding a new type, Data model).
- Add AI in the loop. Judge routing with calibration and audits, then assistance features, each behind a randomised interface experiment (Judges, Assistance, Experiments).
Keep every piece of raw feedback as an immutable event, with what was shown, where, by which checkpoint and to whom, and derive every training example with a replayable transform behind a blocking contract. Labels are the expensive part of the system. Every other mistake in this book is recoverable as long as they survive.
Key Concepts
The core ideas of this book, one card each: a definition, an explanation from basics, why it matters, a common misconception and a diagram. Click a card, or any dotted-underlined term with a badge in the text, to open it in the side panel. To add your own, highlight any phrase and choose Key Concept.
Expert Primer: Mental Models, Debates and Self-Test
This primer condenses the book into what an expert carries around: five ideas that hold across every campaign type, three questions on which informed practitioners still disagree, and ten problems that test whether the ideas can be applied rather than recited. Every item links to the section that develops it.
Five Core Mental Models
1. Agreement is a ceiling, and noise sets how much a label is worth. If two raters agree on a fraction \(a\) of pairs and each errs independently, each is right with probability \(p = \tfrac12(1+\sqrt{2a-1})\). W1's 72% gives \(p \approx 0.832\): no model can score much above 83% against single labels, because the labels themselves are wrong about one time in six. That converts a vague target into a feasibility check: a request for 85% accuracy is pushed back at scoping and replaced with 85% against a 3-rater evaluation set, where the majority is right about 92.5% of the time. The same flip rate, 0.168, scales information: each noisy comparison is worth about \((1-2\varepsilon)^2 \approx 0.44\) of a clean one, so 18,400 useful comparisons carry about 8,100 clean equivalents. Three labels on three different items are worth 1.32 clean comparisons; the same three labels on one item are worth 0.72. Overlap is therefore a measurement instrument, sized to estimate agreement, not a way to buy signal. Low-seventies agreement is normal for subjective comparisons: Ouyang et al. (2022) report 72.6% among trained labelers and Stiennon et al. (2020) 72% labeler to labeler (Scoping, Reward models, Aggregation).
2. Cost per useful label is a product, so diagnose it factor by factor. \(c_u = (r\bar t/60)\,(A/N)\,(1/y)\): wage × mean time gives cost per assignment, assignments per item gives the overhead of overlap and gold, and yield after QA divides the rest. For W1, $3.00 × 1.263 / 0.92 ≈ $4.12. Each factor has its own lever and its own failure: an interface that saves half a minute is −11%; doubling overlap is +17%; yield falling to 0.85 is +8%. When W1's projected cost rose to $4.70, the decomposition split the overrun into a time factor (+6.7%, longer multi-file prompts the researcher actually wanted) and a yield factor (+7.0%, a new cohort at 71% gold accuracy), which need opposite responses: accept the first, requalify the second. Generation is a rounding error at under 1% of cost, so it should be bought for latency and freshness, not optimised for price. Quality itself is a budget line: gold, overlap and review tiers are about a quarter of W1's labour (Metrics, Unit economics, Quality program).
3. Latency problems are capacity problems in disguise. At the rater's click, a buffer converts the generation latency of 16 s into a capacity question: as long as refill exceeds consumption, nobody waits, and when an endpoint fails the buffer's runway (ready items ÷ consumption rate) is the countdown, 60 minutes for 2,000 pairs at 33.3 pairs a minute. Retries are load: nested retries at a 35% failure rate multiplied offered load by about 2.3 in W1's incident and made the outage worse. At the campaign level, request-to-mix is a value stream in which 12.85 of 21 days were waiting and collection, 1,895 rater-hours against a 3,000-hour week, is the constraint. Removing waits gets W1 from 21 days to 7.42 with the current pool; only more scheduled rater-hours (474 a day, +10.5%) or less work per useful comparison gets it to 7.0. Little's law, \(L = \lambda W\), sizes buffers, leases, in-flight vendor tasks and concurrent generations alike (Time to first sample, Reliability, Request-to-mix).
4. Judge people statistically, and act only on converging evidence. A campaign has precise pool-level quality numbers and very imprecise individual ones. W1's 1,263 gold assignments estimate the pool's accuracy to about ±1 point, but each rater sees 8.4 gold items, and 6 of 8 correct has a Wilson interval of about 41% to 93%. Individuals are judged on qualification gold, where a sequential test averages 23 to 29 items, and on an annotator-reliability model over all their work (Dawid and Skene 1979). Base rates dominate accusations: with 4% low-effort raters, one signal at 80% recall and 5% false positives flags more honest raters than guilty ones (precision 0.40); two independent signal families raise precision to 0.91. Some cheating is invisible to the obvious metric: raters who copy a model's answer score 0.77 on gold against 0.80 for honest raters and agree with peers more, not less, while a peer-prediction score conditioned on model labels separates them with AUC 0.98. Veselovsky et al. (2023) estimated that 33–46% of crowd workers used LLMs on a summarisation task (Measuring, Detection, Program).
5. Human effort moves upstream, and human labels remain the measuring stick. The lineage runs from labelling every pair, to writing a constitution (16 principles in Bai et al. 2022), to writing a rubric per prompt (262 physicians wrote 48,562 criteria for HealthBench), to calibrating the model that applies them. Each step cuts cost per item and raises the value of a small amount of carefully checked human text. AI judges take the share of items where they are reliable, 56% in W1, and every routing threshold, anchoring measurement and grader gate is computed against human labels; remove the human stream and the AI components lose their calibration as models change. W3 shows the shape: 1,250 expert-hours of rubric writing, 400 hours of human grading as calibration, a grader gated at 0.8 item-level agreement, and a weekly human audit that caught a grader upgrade falling to 0.74 (Why human data still matters, Judges, Boundary, AI feedback lineage).
Three Fundamental Disagreements
Published work points in different directions on three questions, and the evidence does not yet settle any of them. The table gives the shape of each. The sections below give the strongest case for each side and where practice is converging.
| Debate | Side A | Side B | Emerging synthesis |
|---|---|---|---|
| How much of human feedback can AI feedback replace? | Most of it: AI labels match human labels on many tasks at a tenth of the cost | Little of what matters: judges are biased, trail experts and are exploited by the policy | Calibrated routing with human audits; humans write criteria, label the hard residue and own ground truth |
| Crowd scale or expert depth? | Many cheaper labels, cleaned by aggregation and quality control | Fewer labels from screened experts, each carrying more information | Tiered populations: experts for criteria, gold, adjudication and expert labels; crowd and AI for volume; vendors judged by downstream effect |
| Preference pairs or rubrics and process labels? | Pairs: universal, easy to give, mature reward-model tooling | Rubrics and step labels: more information per item, interpretable, harder to exploit | Signal chosen per domain: verifiers where possible, rubrics for expert non-verifiable work, first-error labels for agents, pairs with strength for overall preference |
Table. The three debates at a glance.
1. How much of human feedback can AI feedback replace?
The case that AI feedback can replace most of it.
- Head-to-head, it works. Lee et al. (2023) found human evaluators preferred RLAIF and RLHF policies about equally on summarisation and helpful dialogue, and estimated AI labelling at about $0.06 per preference example against about $0.67 for human labelling. Zheng et al. (2023) found a strong judge agreeing with human preferences over 80% of the time, the level at which humans agreed with each other (AI judges).
- Constitutional AI trained harmlessness with no human harmfulness labels, from 16 written principles, and produced models that were more harmless at a given helpfulness than RLHF ones (Bai et al. 2022, AI feedback lineage).
- The economics are decisive where it holds. Routing W1 through a calibrated judge keeps 56% of items at human-level agreement, cuts rater-hours from 1,895 to 887 and cost per useful comparison from $4.12 to $1.99, freeing the pool for the items only people can judge (AI judges).
The case that humans remain essential.
- Judges carry systematic biases that a reward model learns and a policy exploits: position, verbosity and self-preference (Zheng et al. 2023). In Lee et al.'s measurements the smallest judge kept the same position after a swap 56% of the time. When W1's candidate checkpoint began writing answers 35% longer, the judge's audited agreement fell from 0.75 to 0.66 while its confidence rose, and the judge preferred the longer answer in 71% of kept items (AI judges).
- Judges that match lay raters trail experts. Szymanski et al. (2024) found dietitians agreeing with an LLM judge 64–68% of the time against 72–75% among themselves, while lay users agreed with the same judge about 80% of the time (Boundary).
- Someone must define the target and measure the judge. Every threshold is computed on human labels, novel failure modes come from people first, and when a label is a value judgement the population giving it is part of the specification (Boundary, Why human data still matters).
Routing, not replacement. Judges take a calibrated first pass, with coverage set by a lower confidence bound against human agreement, a continuous random audit, provenance on every label and coverage dropped to zero when a policy or checkpoint changes until recalibration. Human work concentrates where it is irreplaceable: writing constitutions and rubrics, labelling the low-confidence residue, adjudicating, and supplying the fresh human labels that keep every AI component honest. The human share of labels falls; the expertise per human label rises (AI judges, Boundary).
2. Crowd scale or expert depth?
The case for crowd scale.
- Volume has carried the field. Llama 2 collected 1,418,091 binary comparisons from vendor annotators in weekly batches (Touvron et al. 2023); InstructGPT relied on about 40 contractors, and Anthropic's HH data came mostly from crowd workers on a general marketplace (What labs have published).
- Statistics recovers a lot from noisy labels. Reliability models weight raters by estimated accuracy, majority of three lifts W1's 0.832 to about 0.925, and for training, many single labels beat fewer repeated ones (Aggregation).
- Price is real. Buying W1's 1,895 hours on a self-serve panel at its recommended rate plus fee would cost about $32,470 against $75,780 from a managed vendor, and the reference expert rate of $120/h is three times W1's (Vendors).
The case for expert depth.
- Who labels changes the result. Llama 2 reports that different vendors produced markedly different downstream results, and that a few thousand high-quality supervised examples beat millions of third-party ones (Touvron et al. 2023). PRM800K admitted labelers only after 30 screening questions at 75% agreement with gold (Lightman et al. 2023) (What labs have published).
- Expert items carry more. One W2 review at about $70 yields a step-label sequence, a correction example and an implicit preference pair, and the best automated step attribution on a comparable benchmark is far below expert agreement (Interface types, Process supervision).
- Cheap hours are not cheap labels. A vendor billing $32/h at 5.0 minutes and 20% rejects costs $3.33 per useful comparison against $3.26 for one billing $40/h at 4.5 minutes and 8% rejects; a self-serve panel needs heavier detection, because LLM use by crowd workers is common where text is produced (Vendors, Detection).
Tiers by task, measured by downstream value. Experts write criteria and gold, adjudicate disagreements and label what only they can judge; trained vendor pools carry general comparisons; AI judges carry the confident share. Vendors and populations are compared by cost per useful label and by ablation gains, not by hourly rate or agreement alone, and the platform's own interface runs inside every vendor so the comparison is fair (Populations, Vendors, Data value).
3. Preference pairs, or rubrics and process labels?
The case for preference pairs.
- Comparison is the most general judgement a person can give. It needs no reference answer, works in any domain, and feeds the Bradley–Terry reward models that RLHF was built on, from Christiano et al. (2017) through InstructGPT and Llama 2 (Preference learning to RLHF).
- It is cheap per item and easy to extend: a strength rating lets training drop or down-weight low-margin pairs, and an edit step turns a comparison into a correction, as Llama 3 did (What labs have published, Reward models).
- Rubrics move cost upstream rather than removing it: W3 spends 25 expert-minutes per prompt on the rubric and still needs 400 hours of human grading to admit the AI grader, and a per-rubric agreement estimate from 40 judgements has a standard error of about 0.06 (Transforms).
The case for rubrics and process labels.
- A pair carries at most one noisy bit about two whole responses. W1's 18,400 comparisons are worth about 8,100 clean ones, longer responses win 61% of ordinary pairs but only 39% of length-controlled probes, and a follow-up campaign on near-identical checkpoints trained a reward model at 53% on its own low-margin pairs, near chance (Reward models, Designing for quality, Data value).
- Rubrics extend RL to non-verifiable domains with an interpretable reward. Gunjal et al. (2025) report up to 31% relative improvement on HealthBench over Likert judge rewards, and policies trained on rubrics written without reference answers did worse than on human-grounded ones (AI feedback lineage).
- Step labels locate the error. A process reward model trained on PRM800K solved 78.2% of a MATH subset at best-of-1,860 against 72.4% for an outcome model (Lightman et al. 2023); for agents, the first failing step plus a correction is what a 60-step transcript needs (Process supervision).
No single dominant signal; a portfolio chosen by domain. Verifiable work uses verifiers. Expert, non-verifiable work uses expert rubrics applied by a grader that is gated on human agreement and audited. Agentic work uses first-error labels with corrections, treated as a distribution over nearby steps (W2's 58% exact against 81% within ±2). Pairs with strength remain the default for overall preference and style. The platform consequence is that adding a feedback type end to end, schema to export, has to be routine (Signals, Adding a new type).
Self-Test: Ten Questions
Each question puts an idea from the book into a situation and asks you to compute, diagnose or decide. Answer before opening the worked answer. The "What a memorizer misses" line names the step that separates applying an idea from reciting it. Numbers labelled W1, W2 or W3 are those reference workloads' illustrative values (Reference workloads).
"We want the reward model at 85%." A researcher asks for W1's 20,000 comparisons and an 85% held-out accuracy target. Earlier coding campaigns show 72% pairwise agreement. Is the target feasible, and what do you change?
Answer Infeasible against single labels; use a 3-rater evaluation set
With independent errors, \(a = p^2 + (1-p)^2\), so \(p = \tfrac12(1+\sqrt{2a-1}) = \tfrac12(1+\sqrt{0.44}) \approx 0.832\). A perfect model scores about 83.2% against single labels, so 85% cannot be reached on that evaluation set. With three raters the majority is right with probability \(p^3 + 3p^2(1-p) \approx 0.925\), so 85% is reachable against a 3-rater evaluation set. The validator flags this at scoping with the reason and the alternative. The diagnostic if a model scores 71%: relabel a 300-item slice with three raters and compare accuracy against majority and single labels; a large gap means label noise, a small one model capacity (Scoping).
What a memorizer misses: that agreement is a property of the measuring instrument, so the target has to be stated against an instrument that can resolve it.
"Double the overlap to improve quality." A reviewer proposes 20% overlap instead of 10% for W1, keeping 3 raters. What does it cost, what does it buy for the reward model, and does the spec accept it?
Answer +17% cost, less training signal per dollar, rejected by the cap
Labels rise from 24,000 to 28,000, assignments to about 29,474, cost to about $88,420, above the $80,000 cap, so the validator rejects it. Cost per useful comparison rises from $4.12 to about $4.81 (+17%). For training, each noisy label is worth about \((1-2\times0.168)^2 = 0.44\) clean comparisons; three labels on one item reduce error to about 0.075 and are worth \((1-0.15)^2 \approx 0.72\), while the same three labels on three items are worth 1.32. More overlap improves the estimate of agreement, which 2,000 items already measures to about ±2 points. If quality is the worry, spend on guidelines (the pilot took agreement from 64% to 76%) or on rater qualification (The spec, Reward models, Pilots).
What a memorizer misses: that overlap buys measurement, not signal, and that its cost is visible in the spec before anyone is asked.
Seven days from request to mix. Using W1's numbers, show what a 7-day plan needs from the rater pool, and explain why the book's plan of record overlaps QA and export with collection rather than compressing collection.
Answer 474 rater-hours a day, about 10.5% more scheduled hours
Collection needs \(25{,}260 \times 4.5/60 \approx 1{,}895\) rater-hours; the pool supplies \(3{,}000/7 \approx 429\) a day, so collection takes about 4.42 days at full pool. A plan that keeps QA and export as sequential phases must squeeze collection into about 3 days: \(1{,}895/3 \approx 632\) hours a day, 1.47 times the whole pool, about 70 more raters. The plan of record removes waiting instead: scoping 0.5 day from a template, a 1-day pilot, collection 4.0 days, QA and export running continuously behind collection and finishing a quarter-day each after it, and a pre-booked 1-day retrain: 7.0 days. Collection in 4.0 days needs \(1{,}895/4.0 \approx 474\) hours a day, 3,316 a week, about 10.5% more from the same 150 raters (about 22 h a week each) or about 16 more raters, at unchanged labour cost. With the current pool the same flow gives 7.42 days. Reserve the 474 hours a day at launch, or a second campaign on the same pool will take them (Request-to-mix, The loop).
What a memorizer misses: that the constraint is collection capacity, so the cheapest days come from removing waits elsewhere, and the last ones can only be bought in rater-hours.
The candidate endpoint degrades. W1, day 3, 09:00: one of the candidate deployment's two replicas fails; 35% of requests return 429. The buffer holds 1,400 pairs and 150 raters consume 33.3 pairs a minute. The sampler retries three times and its client library twice underneath. What happens, and what should the platform do?
Answer 42 minutes of runway; retries make it worse; brown out at 20 minutes
Runway is \(1{,}400/33.3 \approx 42\) minutes. Nested retries at a 35% failure rate raise offered load to about 2.23 times the logical rate (2.3 was observed), which lengthens the surviving replica's queue and pushes time to first token past the sampler's deadline, so fewer generations succeed. Idle raters cost \(150 \times \$40/60 = \$100\) a minute; in the book's incident they were starved for 45 minutes, about $4,500. The fixes: exactly one retry layer with jittered backoff that obeys retry-after, a client token bucket below the endpoint's limit, adaptive throttling when the reject rate is high, and an automatic brownout at 20 minutes of runway (667 pairs) that serves overlap repeats and gold, which need no new generation. The candidate cannot simply fail over, because a W1 comparison is only meaningful against that exact checkpoint (Reliability, Runbooks).
What a memorizer misses: that the platform's own retries are part of the outage, and that the buffer's job in an outage is to buy time for a mode switch.
Six of eight. A W1 rater has answered 6 of 8 gold items correctly, below the 80% threshold. Remove them? How should individual raters be judged in W1?
Answer No action; judge individuals on qualification gold
Eight items say almost nothing: the Wilson interval for 6/8 is about 41% to 93%, and with a Beta(8, 2) prior the probability that the rater's accuracy is below 0.8 is about 0.55, a coin flip. At 25 of 40 it is about 0.99, which justifies action. W1 gives each rater only about 8.4 gold items over the whole campaign, because 5% of 168 assignments is small. A sequential test between 0.70 and 0.88 decides after about 23 to 29 gold items on average (a fixed-size test needs 52), so front-load gold into qualification: up to about 4,350 answers, about 326 hours or $13,000, paid once per pool and reused. Keep production gold for pool-level drift, and weight each rater's work by a reliability model rather than a hard cut (Pilots, Measuring).
What a memorizer misses: that gold precise at pool level can be useless at rater level, and that the fix is where gold is spent, not how much.
The reward model got worse. After W1 data entered training, the reward model's held-out gold accuracy dropped. An exporter release mid-collection is suspected. Which single measurement confirms it, how many labels are affected, and do you recollect?
Answer Side balance; about 4,000 inverted; re-export, do not recollect
Measure side balance: the rate at which the candidate wins, split by which side it was shown on. It may differ from 50%, but it must not depend on side. In the exporter's window it was 58% when shown right and 42% when shown left. With 4,000 items per side the standard error of the difference is about \(\sqrt{2 \times 0.25/4{,}000} \approx 0.011\), so a 16-point gap is about 14 standard errors. The exporter ignored the recorded side for half of 8,000 comparisons: about 4,000 of 18,400 useful comparisons (22%) were inverted, lowering effective label accuracy from about 0.83 to about 0.69. Lineage identifies exactly which examples came through the bad version. Because raw feedback records were correct, re-export with the fixed mapper and retrain; discarding the 8,000 comparisons would throw away about $33,000 of recoverable labels. Then make side balance a blocking export check (Signals, Lineage, Validation).
What a memorizer misses: that the bug was in a derived artefact, so the remedy is a replay, and that this is only possible because what was shown, and where, is stored with the label.
Route W1 through a judge. Half of W1's 2,000 triple-labelled items calibrate a judge. The loosest threshold whose kept labels agree with a single human at least 72% of the time (95% lower bound) keeps 56% of items. With a 5% human audit of kept items and $0.06 per judged item, what does W1 cost, and what should trigger a page?
Answer About $36,600, $1.99 per useful comparison
Human share is \(0.44 + 0.56 \times 0.05 = 0.468\), so human cost is \(0.468 \times \$75{,}780 \approx \$35{,}465\), judge cost \(18{,}400 \times \$0.06 = \$1{,}104\), total about $36,569: $1.99 per useful comparison against $4.12, and 887 rater-hours instead of 1,895. The bar is human–human agreement, because a judge that agrees with one rater 72% of the time is, under the same model, right about 83% of the time. Page when the audit's upper bound falls below 0.72. In the book's incident a candidate refresh made answers 35% longer; audited agreement fell from 0.75 to 0.66 on about 258 audits while coverage rose from 0.56 to 0.64, the signature of verbosity bias. Coverage went to zero (about $6,500 a day), the roughly 5,500 judge labels since the refresh were held out of the next export, and recalibration on 300 fresh triple-labelled items gave coverage 0.48, about $2.30 per useful comparison (AI judges).
What a memorizer misses: that a confident judge can be wrong in a correlated way, so the audit, not the judge's confidence, decides coverage, and a model change upstream invalidates calibration.
An AI hint for W2. Showing W2 experts an AI-suggested first failing step before they look cuts mean time from 35.1 to 29.4 minutes. Planted wrong hints are followed 27 times in 100, against a 10% baseline for the same steps without hints. What do you ship, and can the experiment also tell you whether exact agreement improved?
Answer Ship judge-first reveal; agreement is underpowered
Hint-first adds about 17 points of anchoring against a 5-point guardrail: experts stop reading where the hint points, and the labels then encode the AI's errors as human judgement. Reject it. A second arm that reveals the hint only after the expert has flagged a step keeps the follow-wrong rate at 12 of 100 (about 2 points over baseline) and still saves some time; ship that. The time saving is worth about $4,000 per minute saved across 2,000 transcripts at $120/h. Agreement cannot decide the experiment: with 200 double-reviewed transcripts (100 per arm), the minimum detectable effect on 58% exact agreement is about 19.6 points; detecting a rise to 68% would need 362 double-reviewed pairs per arm. Report it descriptively or buy more double review (Interface experiments, Designing for quality, Assistance).
What a memorizer misses: that assistance is judged on how often people follow it when it is wrong, measured with planted errors, and that quality metrics often need more data than throughput metrics.
Admit and watch W3's grader. How many human item-level scores are needed to check W3's AI grader at 0.80 ± 0.02, what does a recurring audit cost, and what does the audit do when the grader is upgraded and agreement reads 0.74?
Answer About 1,537 items, about 5 grader-hours; roll back and gate upgrades
\(n = 1.96^2 \times 0.8 \times 0.2/0.02^2 \approx 1{,}537\) item scores, about 154 responses at 10 items each, about 5 grader-hours at 2 minutes a response. Items within one rubric are correlated, so the effective sample is smaller; gate on slices of many rubrics, not on single rubrics, whose 40 judgements give a standard error near 0.06. W3's 120,000 human item scores more than cover initial calibration; the recurring cost is the audit. At 0.74 on 1,537 items the standard error is about 0.011, so the interval (0.72–0.76) excludes 0.80. Re-run the frozen calibration set: if it also fell (0.75 here), the grader changed, not the policy's outputs. Slice by item type to find where (credit for protective clauses mentioned but not drafted). Roll back to the pinned grader, treat RL checkpoints trained since as suspect until compared on a human-graded evaluation, and gate every grader change on ≥ 0.80 overall and ≥ 0.75 per item type (Why human data still matters, Transforms).
What a memorizer misses: that a rising RL reward with a flat human audit is the signature of a grader problem, and that the frozen calibration set separates "the grader changed" from "the policy moved".
The follow-up that did not help. W1 bought +4.0 points of reward-model accuracy. A follow-up, W1-b, collects another 20,000 comparisons on the same spec for about $75,800. What should it have been expected to add, it added +0.1 (95% interval −0.6 to +0.8): what do you check, and what do you change?
Answer Expect about 1 point; check pair margins; diversify pairs
The scaling curve (65.5, 66.5, 67.5, 68.5% at 2,300 to 18,400 comparisons) gives about one point per doubling, so a second campaign of the same size should add about 1 point, at about $75,800 per point against W1's average of about $18,900. The interval excludes 1.0, so the null is real, not underpowered. Check the candidate causes by their covariates: label noise (agreement 71%, unchanged), redundancy (6% near-duplicates, too few), and margin. 41% of W1-b comparisons were rated only slightly or negligibly better, against 22% in W1, and a reward model trained on them scored 53% on its own low-margin pairs. The pairs came from checkpoints a few hundred RL steps apart, so raters were labelling noise between near-identical responses. Regenerate pairs with more diversity (checkpoints further apart, different temperatures, best and worst of several), filter near-identical pairs by an ensemble's score gap while keeping a 10% unfiltered sample, and judge the pilot on the low-margin share (41% to 20%) before the full ablation (Data value, Prompt selection).
What a memorizer misses: that the value of a label depends on the pair it compares, which is decided by the sampler before any rater sees it.
What an RL Data Platform Is
Reinforcement learning (RL) post-training improves a pretrained language model by rewarding the behaviour people want and discouraging the behaviour they do not. For many skills the reward cannot be computed by a program, so it has to come, directly or indirectly, from human judgment: a rater who says which of two answers is better, an expert who marks the first wrong step in a long agent transcript, a lawyer who writes the checklist a good contract must satisfy. An RL data platform is the software and operating practice that turns a researcher's data idea into that judgment, at scale, with known quality, and delivers it into the data the next model is trained on.
The platform is a loop, not a pipeline. A data idea ("the reward model is weak on coding helpfulness") becomes a campaign, a specification of what to collect, from whom, how much and at what quality. The campaign pulls samples from live model endpoints, shows them to humans in a purpose-built interface, records their feedback as structured data, checks its quality, converts it into a training signal such as reward-model pairs, adds it to the training mix, and produces a new model. That model serves the next round of samples, and its evaluations suggest the next data idea.
The chapter has four parts. The loop walks the figure stage by stage and shows which component receives and produces what. Feedback types explains how each kind of human feedback becomes a distinct training signal. Why human data still matters places human feedback next to programmatic verifiers and AI feedback. North-star metrics defines the five numbers by which such a platform is judged.
The mental model to carry forward: the platform is a factory whose raw material is model output, whose machines are people with good tools, and whose product is a training signal that must arrive quickly, cheaply and correct.
Designing an RL data platform is mostly a matter of managing four coupled quantities. Each is defined and worked in this chapter for reference workload W1 (illustrative numbers).
| Quantity | Symbol | W1 (illustrative) | What sets it | Section |
|---|---|---|---|---|
| Human work per campaign | \(A\) assignments, \(H\) rater-hours | \(A \approx 25{,}260\), \(H \approx 1{,}895\) h | target size, overlap, gold share, time per label | Loop |
| Request-to-mix latency | \(T_\text{mix}\) | 21 d baseline, 7 d target | critical path through six stages | Loop |
| Signal quality ceiling | \(p\) (rater–latent match) | ≈ 0.83 from 72% agreement | task ambiguity, rater skill, interface | Signals |
| Cost per useful label | \(c_u\) | ≈ $4.12 | rate, minutes per label, overhead, rejects | Metrics |
Table. The coupled quantities of the chapter. Values are illustrative workload numbers, not published results.
The couplings matter more than any single value. More overlap raises quality knowledge and cost; a shorter request-to-mix time needs either more rater-hours per day or fewer labels; a stricter quality gate raises the cost per useful label by shrinking its denominator. Each section ends with the default a builder should choose and the conditions under which to deviate.
The chapter builds a small Python package, rldp, that makes the loop executable: one record type per hand-off, one converter per feedback type, a routing policy for human versus AI versus verifier labels, and the five north-star metrics computed from raw events. Every test asserts a W1 number, so a change that breaks the arithmetic of the workload breaks the build. All 19 tests below were run with python3 -m pytest -q rldp/tests and pass.
rldp/
core.py # r-what-loop: Campaign, Sample, Assignment, Feedback, TrainingExample
loop.py # r-what-loop: stage event log, request-to-mix, capacity arithmetic
signals.py # r-what-signals: pairwise -> RM pairs, corrections -> SFT, process labels,
# rubric -> reward, red-team -> evals + safety pairs
route.py # r-what-why: verifier / AI judge / human routing and audit sizing
routing.yaml # r-what-why: the policy as data
metrics.py # r-what-metrics: TTFS, cost per useful label, agreement, self-serve rate
tests/ # test_core, test_loop, test_signals, test_route, test_metrics
The central design choice is that every record carries lineage: the ids of the records it was derived from. A reward-model pair knows which assignments produced it, each assignment knows its rater and sample, each sample knows its checkpoint. Without lineage, the quality problems described in later sections cannot be traced back to a rater, an interface version or a model endpoint, and bad data cannot be removed from a mix after the fact.
In production the platform is judged by a small set of service-level objectives (SLOs): targets for a measured quantity over a window, with an error budget for how often the target may be missed. The SLOs below are the chapter's defaults for a W1-sized campaign; the sections that follow derive each one and work an incident that breaks it.
| SLO | Target (W1, illustrative) | Window | Who feels a breach | Section |
|---|---|---|---|---|
| Time-to-first-sample | p50 ≤ 2 s, p95 ≤ 5 s | 5 min, per campaign | raters (idle paid time) | Loop |
| Export integrity | 0 schema violations; side balance within 3σ | per export | reward-model team | Signals |
| Judge–human agreement (where AI labels) | ≥ 0.80 item-level (W3) | weekly audit | RL team (reward hacking) | Why |
| Request-to-mix | ≤ 7 days | per campaign | researchers | Metrics |
| Cost per useful label | ≤ plan + 10% ($4.12 → $4.53) | per campaign | budget owner | Metrics |
Table. Platform-level SLOs used throughout the chapter. Targets are this book's illustrative defaults, not published industry figures.
Two failure classes dominate operations. Loud failures (an endpoint outage, a crashed export) stop work and are noticed within minutes; their cost is idle paid time. Silent failures (flipped labels, a drifting AI judge, raters pasting model output) keep the dashboards green while the training signal rots; their cost is a worse model discovered weeks later. The incidents in this chapter cover one of each kind per section, and each ends with the validation result that would show the remedy worked.
The End-to-End Loop
The loop is the sequence of hand-offs by which a research question becomes a better model. It is worth walking slowly, because each stage is owned by a different component, receives a different object and produces a different one, and most platform failures happen at a hand-off rather than inside a stage.
1. Data idea. A researcher notices a gap: evaluations show the model is weak at something, or a reward model ranks responses badly on some slice. The output of this stage is a data request, a short statement of what behaviour should change and what evidence would show it changed. 2. Campaign. Scoping turns the request into a campaign spec: the task shown to humans, the guidelines and rubric, which population of raters or experts may work on it, how many items, how many raters per item (overlap), which pre-answered gold items are mixed in to measure accuracy, the budget and the stopping rule. 3. Samples. A sampler selects prompts and calls live model endpoints, usually the current checkpoint and a candidate, to produce the responses humans will judge. Because generation can take many seconds, samples are often produced ahead of time into a pre-generation buffer, a queue of ready-to-show items. 4. Humans. A router assigns items to qualified people; the person sees the item in a feedback interface and makes a judgment. 5. Feedback. The interface records the judgment as a structured record: which samples, which choice, how strongly, how long it took, which interface version. 6. Quality. Checks run on every record and every rater: accuracy on gold items, agreement on overlapped items, time spent, signs of copy-pasted model output. Records that fail are rejected or sent for review. 7. Training signal. A converter turns accepted feedback into what training consumes, for example (chosen, rejected) pairs for a reward model. 8. Training mix. The new data is weighted against every other data source in the next training run. 9. Model. Training produces a checkpoint; it is evaluated, deployed to the endpoints the sampler calls, and the loop starts again.
The figure shows the most useful way to think about timing: the platform runs three nested loops. The assignment loop (request a task, see the sample, judge, submit) repeats thousands of times per campaign and is measured in seconds; when it is slow, paid people wait. The campaign loop (spec, pilot, collect, QA, export) is measured in days; when it is slow, research waits. The model loop (mix, train, evaluate, next idea) is measured in training rounds; when it is slow, the data goes stale because it was collected on samples from a model that no longer exists.
Compared with the predecessor. Classic dataset labelling (image classes, named entities) is a pipeline: a fixed set of items is labelled once and the dataset is frozen. RL feedback differs in two ways. First, the items are model outputs, so they must be generated, and generating them depends on live serving infrastructure. Second, the items go stale: a preference between two responses from last month's checkpoint says less about this month's model. Published practice reflects this. The Llama 2 team collected preference data in weekly batches and sampled from the latest model for each new round so the reward model stayed on-distribution (Touvron et al., 2023); Anthropic's helpful-and-harmless work updated preference models and policies on a weekly cadence with fresh human feedback (Bai et al., 2022).
What changed and what it costs. Treating feedback as a loop buys freshness and lets each round target the model's current weaknesses, but it couples the data platform to model serving (an endpoint outage now idles paid raters) and to training (a schema change now breaks a training run). The platform's job is to make those couplings explicit contracts rather than surprises.
What you would actually do. Build the loop as one system with a shared record format and lineage on every record, even if different teams own different stages. Default to a pre-generated buffer refilled from live endpoints; deviate to purely on-demand generation only when the samples must react to the person's own input, as in live multi-turn sessions. The next section looks at the step in the middle of the loop, where human feedback is turned into a training signal, and why each feedback type needs its own conversion.
The loop has two kinds of capacity limits: human hours, which bound how fast feedback is produced, and generation throughput, which bounds how fast samples are ready. A third quantity, the end-to-end latency, is set by the critical path through the stages. This section derives each one for W1.
Human work. Let \(N\) be the number of items a campaign needs, \(f_o\) the fraction of items that are overlapped and \(k\) the number of raters on an overlapped item. The number of labels is
\[ L = N(1-f_o) + N f_o k . \]Gold items are a fraction \(g\) of assignments (each assignment is one unit of work given to one person), so the assignments \(A\) satisfy \(A(1-g) = L\). With mean minutes per assignment \(\bar t\), the rater-hours are \(H = A\bar t/60\).
Collection time. If the campaign gets a share \(s\) of a pool supplying \(P\) hours per week, spread over seven days (an assumption; many vendor pools work five), collection takes \(D_c = 7H/(sP)\) days. For W1 with the whole pool, \(D_c = 7 \times 1{,}895/3{,}000 \approx 4.4\) days. The baseline's 6-day collection stage is longer than this floor; ramp-up, pilot calibration and sharing the pool with other campaigns plausibly account for the gap (our interpretation; the workload sheet fixes only the stage durations).
Request-to-mix as a critical path. The request-to-mix latency \(T_\text{mix}\) is the time from filing the request to the first training run that consumes the data. If stages run strictly in sequence it is the sum of their durations; if a stage can start before its predecessor finishes (QA can score records as they arrive), only the stages on the critical path, the longest chain of dependent work, count.
Generation throughput and the buffer. With \(R\) raters active at once, the buffer is consumed at \(\lambda = R/\bar t\) items per minute. If the endpoint that refills it fails for \(T_r\) minutes, a buffer of size \(B\) prevents rater idle time only if \(B \ge \lambda T_r\). The buffer's cost is staleness: every buffered item was generated by a specific checkpoint and must be discarded when the campaign switches checkpoints, so \(B\) should not exceed what raters consume before the next planned switch.
| Design choice | Pre-generated buffer | On-demand generation |
|---|---|---|
| Time-to-first-sample | fetch + render (≈ 1 s) | includes generation (often tens of seconds for long code) |
| Outage tolerance | covers \(B/\lambda\) minutes | none |
| Freshness | items as old as the buffer | always current checkpoint |
| Waste | discarded on checkpoint switch | none |
| Fits | pairwise, rating, rubric grading | live multi-turn sessions, interactive red-teaming |
Table. Buffer versus on-demand generation. The generation latency figure is a qualitative assumption; Chapter 4 measures it.
Decision. Default to a buffer sized to the larger of the endpoint's recovery time times peak consumption, and a minimum that keeps time-to-first-sample within target; cap it at the consumption expected before the next checkpoint switch. Spend platform effort on the critical path: for W1, streaming QA and export removes about 4.5 of their 5 days at no human cost, templates and a pre-booked retrain slot remove most of the remaining waiting, and shortening collection below its 4.4-day floor needs more rater-hours or a faster interface.
The loop becomes testable once each hand-off has a record type and each stage writes an event. core.py defines the nouns; each record names the component that produces and consumes it. The Feedback.payload is a dictionary validated per feedback kind, which is how a new feedback type is added without changing the core tables.
# rldp/core.py -- the nouns of the loop, one record type per hand-off.
from dataclasses import dataclass, field
from typing import Literal
FeedbackKind = Literal["pairwise", "rating", "rubric", "critique",
"correction", "process", "redteam"]
@dataclass(frozen=True)
class Campaign: # produced by: scoping; consumed by: sampler, router
id: str
feedback_kind: FeedbackKind
target_items: int # e.g. 20_000 comparisons
overlap_frac: float # share of items labelled by k raters
overlap_k: int
gold_frac: float # share of *assignments* that are gold items
rate_usd_per_h: float
@dataclass(frozen=True)
class Sample: # produced by: model endpoint; consumed by: UI
id: str
prompt_id: str
checkpoint: str # which model produced it (provenance)
text: str
@dataclass(frozen=True)
class Assignment: # one unit of human work
id: str
campaign_id: str
item_id: str
rater_id: str
is_gold: bool = False
@dataclass(frozen=True)
class Feedback: # produced by: human in UI; consumed by: quality
assignment_id: str
item_id: str
rater_id: str
kind: FeedbackKind
payload: dict # kind-specific; validated by a schema per kind
seconds_spent: float
@dataclass(frozen=True)
class TrainingExample: # produced by: transform; consumed by: training mix
kind: Literal["rm_pair", "sft", "process", "rubric_reward", "redteam"]
data: dict
lineage: tuple = field(default_factory=tuple) # ids it was derived from
def assignments_needed(c: Campaign) -> int:
"""Labels = single-labelled items + k * overlapped items; gold is a share of all assignments."""
labels = round(c.target_items * (1 - c.overlap_frac)) + round(c.target_items * c.overlap_frac) * c.overlap_k
return round(labels / (1 - c.gold_frac))
W1 = Campaign(id="w1_pairwise_coding", feedback_kind="pairwise", target_items=20_000,
overlap_frac=0.10, overlap_k=3, gold_frac=0.05, rate_usd_per_h=40.0)
loop.py stores the campaign loop as an append-only list of stage events. Request-to-mix is read off the log rather than reported by hand, which is what makes it trustworthy as a metric.
# rldp/loop.py -- the loop as an append-only event log, plus capacity arithmetic.
from dataclasses import dataclass
STAGES = ["scoping", "guidelines_pilot", "collection", "qa", "export", "retrain_mix"]
@dataclass(frozen=True)
class StageEvent:
campaign_id: str
stage: str # one of STAGES
start_day: float # days since the data request was filed
end_day: float
def request_to_mix_days(events: list[StageEvent]) -> float:
"""Request filed at day 0; the metric ends when retrain_mix ends."""
end = [e.end_day for e in events if e.stage == "retrain_mix"]
if not end:
raise ValueError("data has not reached the mix yet")
return max(end)
def stage_share(events: list[StageEvent]) -> dict[str, float]:
"""Fraction of the end-to-end time owned by each stage (sequential plans only)."""
total = request_to_mix_days(events)
return {e.stage: round((e.end_day - e.start_day) / total, 3) for e in events}
def sequential(durations: dict[str, float], campaign_id: str) -> list[StageEvent]:
t, out = 0.0, []
for s in STAGES:
out.append(StageEvent(campaign_id, s, t, t + durations[s])); t += durations[s]
return out
def collection_days(rater_hours: float, pool_hours_per_week: float, pool_share: float) -> float:
"""Calendar days of collection if the campaign gets `pool_share` of a pool whose
hours are spread evenly over 7 days (an assumption; many pools work 5 days)."""
return rater_hours / (pool_hours_per_week * pool_share / 7)
W1_BASELINE = {"scoping": 3, "guidelines_pilot": 4, "collection": 6,
"qa": 3, "export": 2, "retrain_mix": 3}
The tests pin the W1 arithmetic: 25,263 assignments (the workload sheet rounds to about 25,260), 1,895 rater-hours, a 21-day baseline, a 4.4-day collection floor, the 10.5% extra scheduled hours of the plan of record's 4-day collection, and the 1.47× pool requirement of the 3-day alternative.
# rldp/tests/test_core.py and test_loop.py (excerpt)
import pytest
from rldp.core import W1, assignments_needed
from rldp.loop import sequential, request_to_mix_days, stage_share, collection_days, W1_BASELINE
def test_w1_assignments():
n = assignments_needed(W1)
assert n == 25_263
assert abs(n * 4.5 / 60 - 1_895) < 1
def test_w1_baseline_is_21_days():
ev = sequential(W1_BASELINE, "w1")
assert request_to_mix_days(ev) == 21
assert stage_share(ev)["collection"] == pytest.approx(6 / 21, abs=1e-3)
def test_w1_collection_floor():
assert collection_days(1_895, 3_000, 1.0) == pytest.approx(4.42, abs=0.01)
assert 1_895 / 4.0 / (3_000 / 7) == pytest.approx(1.105, abs=0.001) # plan of record (ch. 8)
assert 1_895 / 3 / (3_000 / 7) == pytest.approx(1.474, abs=0.001) # 3-day alternative
def test_not_in_mix_raises():
ev = [e for e in sequential(W1_BASELINE, "w1") if e.stage != "retrain_mix"]
with pytest.raises(ValueError):
request_to_mix_days(ev)
Debugging tips. If request-to-mix looks too good, check that the clock starts at request filing, not at campaign launch; scoping and pilot are often a third of the total. If assignment counts disagree with a vendor invoice by about 5%, gold items were left out of one of the counts; if they disagree by a fraction of a percent (63 assignments for W1: 25,200 against 25,263), someone computed gold as a share of labels instead of assignments. If the same sample id appears with two checkpoints, the sampler is reusing ids across checkpoint switches and lineage is broken; make the sample id a hash of (prompt, checkpoint, decoding settings, seed).
The loop's most expensive operational coupling is between model serving and paid human time. When the endpoints that produce samples degrade, the pre-generation buffer absorbs the problem for a while; when the buffer runs dry, every rater who clicks "next" waits on a broken endpoint while being paid. The problem matters because it converts a back-end incident into direct labour cost and into quality loss, since raters who are interrupted repeatedly work less carefully afterwards (a plausible effect that this book does not quantify). Its root cause is almost always a buffer sized for normal refill jitter rather than for the endpoint's recovery time.
Symptom. Mid-collection, time-to-first-sample p95 jumps from under 5 s to over 60 s, and the rater-facing error rate rises. Illustrative assumptions beyond the workload sheet: 100 raters active, the candidate endpoint taken down for an unplanned redeploy lasting 120 minutes, buffer at 1,200 pairs when it went down, refill capacity 192 pairs/min when healthy.
Timeline and numbers. Consumption is \(100/4.5 \approx 22\) pairs/min. The buffer lasts \(1{,}200/22 \approx 54\) minutes. For the remaining 66 minutes, raters cannot be served W1 tasks. If they are paid for logged-in time, idle cost is \(100 \times 66/60 \times \$40 \approx \$4{,}400\), about 5.8% of the campaign's $75,780 labour budget, for zero labels. After recovery the buffer refills at a net \(192 - 22 = 170\) pairs/min and is full again about 12 minutes later.
Measurements that separate causes. (1) Buffer depth by campaign and checkpoint: a steady fall points at refill, not at the UI. (2) Generation success rate and latency by endpoint: the candidate endpoint at 0% isolates it. (3) TTFS split into buffer-hit and buffer-miss: hits stayed at about 1 s, so the interface and assignment service were healthy.
Remedy chosen. Resize the buffer to cover the endpoint's observed recovery time at peak draw: \(22 \times 120 \approx 2{,}700\) pairs, rounded to 3,000, with a staleness cap (all buffered pairs discarded on checkpoint switch). Add a fallback: when the buffer for one campaign drops below 15 minutes of draw, the router offers raters tasks from another eligible campaign or calibration gold, rather than idling them. Rejected alternatives: substituting an older candidate checkpoint (changes what the data means, so the labels would no longer answer the researcher's question) and on-demand generation from the current checkpoint alone (pairs need both sides).
Cost and trade-off. A 3,000-pair buffer generated from a checkpoint that is replaced mid-campaign wastes up to 3,000 pairs of generation compute; for W1 that is small next to $4,400 of idle time per incident, but it would not be for an expensive agentic generation.
Validation. A game day in staging takes the candidate endpoint down for 120 minutes at simulated peak draw. The fix is supported if TTFS p95 stays ≤ 5 s throughout and idle rater-minutes stay at zero; it is weakened if p95 holds but rater throughput still drops, which would mean the fallback tasks are not actually being accepted.
Runbook: buffer low.
- Page when buffer depth falls below 30 minutes of peak draw (W1: 660 pairs) for any active campaign.
- Check generation success by endpoint. If one endpoint is down, open an incident with the serving on-call and record its expected recovery time.
- If expected recovery exceeds the buffer's remaining minutes, enable the cross-campaign fallback for the affected pool. Do not substitute a different checkpoint.
- If no fallback campaign is eligible, notify the vendor to pause the shift and log idle time against the incident (it is a cost the campaign owner should see).
- After recovery, confirm refill rate exceeds draw, then disable the fallback once depth exceeds 60 minutes of draw.
# alert: W1 buffer below 30 minutes of peak draw (Prometheus-style rule; metric names are this book's)
- alert: SampleBufferLow
expr: rldp_buffer_pairs{campaign="w1_pairwise_coding"}
/ clamp_min(rate(rldp_assignments_served_total{campaign="w1_pairwise_coding"}[10m]) * 60, 1)
< 30
for: 5m
labels: {severity: page}
annotations:
summary: "Buffer covers under 30 min of draw; check candidate/current endpoint health"
The same pattern, a cheap buffer between an unreliable dependency and paid human time, recurs wherever humans wait on machines: transcript rendering for W2 and AI pre-grading for W3. The next section turns to what happens to feedback after it is collected.
Feedback Types and the Training Signals They Become
Human feedback is never used raw. Each type of feedback is collected because training can consume a particular shape of data, and the platform must convert one into the other. Knowing that conversion is what lets a platform engineer push back on a request ("you asked for 1–7 ratings, but your consumer is a pairwise reward model") and add new feedback types safely.
Pairwise preferences. A rater sees one prompt and two responses and picks the better one, sometimes with a strength ("slightly better", "much better") or a tie. The conversion produces a (prompt, chosen, rejected) triple. Its consumer is a reward model: a network, usually initialised from a language model, that reads a prompt and a response and outputs one number, trained so that the chosen response scores higher than the rejected one. RL then optimises the policy against that number. The training rule comes from the Bradley–Terry model of paired comparisons (Bradley and Terry, 1952): the larger the score gap between two items, the more likely the higher one is preferred. This is the path of Christiano et al. (2017), Stiennon et al. (2020) and InstructGPT, whose roughly 40 contractors ranked 4 to 9 responses per prompt, each ranking expanding into every pair it implies (Ouyang et al., 2022). Llama 2 added the strength label to the loss as a margin (Touvron et al., 2023). The same pairs can also train the policy directly, without a separate reward model, using Direct Preference Optimization (DPO) (Rafailov et al., 2023). Limitation: a pair says which is better, not why, and not whether either is good.
Ratings. A rater scores one response on a scale, often on several attributes (helpfulness, correctness, verbosity). Ratings become regression targets for a multi-attribute reward model, or are turned into pairs by comparing two rated responses to the same prompt. HelpSteer2, about ten thousand response pairs with multi-attribute scores, was used to train reward models that reached 92.0% on RewardBench (Wang et al., 2024). Limitation: absolute scales drift between raters and over time, which pairwise judgments partly avoid.
Rubric scores. An expert writes, per prompt, a checklist of weighted criteria a good answer must meet; graders (human or AI) then mark each criterion as met or not. The weighted fraction of criteria met becomes a reward. Rubrics extend RL to domains with no single correct answer: Rubrics as Rewards reported up to 31% relative improvement on HealthBench over Likert-style judge rewards (Gunjal et al., 2025), and HealthBench itself rests on 48,562 rubric criteria written by 262 physicians (Arora et al., 2025). Limitation: a response can satisfy every listed item and still be bad in a way nobody listed.
Critiques. A person writes what is wrong with a response. Critiques train models that critique, and, paired with a revision, give supervised data for revising. Constitutional AI uses the same critique-then-revise shape with model-written critiques (Bai et al., 2022b). Limitation: free text is expensive to check for quality.
Demonstrations and corrections. A person writes the ideal response, or rewrites the model's response from the point where it went wrong. These become supervised fine-tuning (SFT) examples: prompt plus target text, trained by imitation. A correction yields a free preference pair as well (corrected over original). Llama 2 stopped at 27,540 high-quality SFT annotations, arguing quality mattered more than volume (Touvron et al., 2023). Limitation: demonstrations cap the model at the writer's skill.
Step-level (process) labels. For multi-step work, a person marks each step as correct, incorrect or ambiguous, or marks the first failing step. These train a process reward model (PRM), which scores each step instead of only the final outcome. PRM800K contains about 800,000 step labels on 75,000 solutions to 12,000 math problems; a process-supervised model solved 78.2% of a representative MATH test subset and outperformed outcome supervision (Lightman et al., 2023). Limitation: steps must be well delimited, which is harder in agent transcripts than in math.
Red-team findings. Specialists try to make the model produce harmful output and record successful attacks with a harm category and severity. A finding becomes a regression test, a safety preference pair when a good response is written, and training data for safety classifiers. Ganguli et al. released 38,961 red-team attacks and found RLHF models harder to red-team as they scale (Ganguli et al., 2022). Limitation: findings are biased toward what red-teamers thought to try.
Compared with classic labelling, where a label is the final product, here the label is an intermediate: its value is decided by the consumer it feeds. What you would actually do: start every campaign by naming the consumer and its input format, then choose the cheapest feedback type that produces it. Default to pairwise preferences for reward models of general quality, rubrics where experts can articulate criteria, and corrections where demonstrations would cap quality below what experts can recognise. The next section asks why any of this still needs humans.
Each conversion has a governing equation that tells the platform what the data must look like. This section derives the three that matter most and works them with the reference workloads.
Preferences and Bradley–Terry. Let \(r(x, y)\) be the scalar reward a model assigns to response \(y\) for prompt \(x\). The Bradley–Terry model says the probability that a person prefers \(y_w\) over \(y_l\) is
\[ P(y_w \succ y_l \mid x) = \sigma\big(r(x,y_w) - r(x,y_l)\big), \qquad \sigma(z) = \frac{1}{1+e^{-z}} . \]Maximising the likelihood of observed choices gives the reward-model loss used by InstructGPT (Ouyang et al., 2022):
\[ \mathcal{L}(\theta) = -\,\mathbb{E}_{(x,y_w,y_l)}\Big[\log \sigma\big(r_\theta(x,y_w) - r_\theta(x,y_l)\big)\Big]. \]Two data-shape consequences follow. A ranking of \(K\) responses implies \(\binom{K}{2}\) pairs, so InstructGPT's 4–9 responses per prompt gave 6 to 36 pairs per prompt; because those pairs share a prompt, they were trained together as one batch element to avoid overfitting. Llama 2 subtracts a margin \(m(\text{strength})\) inside the sigmoid, \(\sigma(r_w - r_l - m)\), so pairs labelled "significantly better" must be separated by more (Touvron et al., 2023). Ties carry no direction; they are dropped from pair sets or trained with target 0.5.
Agreement sets a ceiling. Suppose each rater independently matches the latent majority preference with probability \(p\) (a homogeneous-rater simplification). Two raters then agree with probability \(a = p^2 + (1-p)^2\). Solving for \(p\):
\[ p = \tfrac{1}{2}\Big(1 + \sqrt{2a - 1}\Big). \]A reward model evaluated against single held-out labels cannot expect to exceed about \(p\), because the labels themselves disagree with the latent preference \(1-p\) of the time. For comparison, InstructGPT reports training labellers agreeing with each other 72.6 ± 1.5% of the time (Ouyang et al., 2022).
Rubric rewards. For prompt \(x\) with rubric items \(i = 1..n\), weights \(w_i > 0\) and grader scores \(s_i(y) \in [0,1]\), the reward is the normalised weighted score
\[ R(x,y) = \frac{\sum_{i} w_i\, s_i(y)}{\sum_i w_i}. \]When an AI grader supplies \(s_i\), the reward's validity rests on item-level agreement between AI and human graders, which is a measurable quantity with a sampling error (see Why human data still matters).
Process labels. If an expert marks step \(j^*\) as the first failure in a trajectory of \(n\) steps, steps \(1..j^*-1\) get label +1, step \(j^*\) gets −1 and later steps are unlabelled, because once the trajectory has gone wrong, the correctness of later steps is ill-defined. A PRM trained on such labels predicts per-step correctness \(q_j\); Lightman et al. score a whole solution as the probability that every step is correct, which under independence is \(\prod_j q_j\) (Lightman et al., 2023). For W2, each of the 2,000 transcripts contributes \(j^*\) labelled steps, so label volume depends on where agents fail: early failures give few positive labels. W2's exact first-step agreement of 58% (81% within ±2 steps) suggests training with a tolerance window rather than a hard index.
| Feedback | Unit cost driver | Information per label | Default consumer |
|---|---|---|---|
| Pairwise | reading 2 responses | < 1 bit (direction, optional strength) | RM / DPO |
| Rating | reading 1 response | a few bits, scale-dependent | regression RM |
| Rubric | writing items once, cheap grading | one bit per item, reusable | rubric reward via AI grader |
| Correction | writing (W2: ~35 min) | a full target sequence | SFT + pair |
| Process | locating the failure | a step index | PRM |
Table. Information and cost per label by feedback type (qualitative; W2 time from the workload sheet).
Decision. Pick the feedback type by consumer, then by cost per bit the consumer can use. Use pairwise when the consumer is a reward model and raters can judge but not articulate; rubrics when experts can articulate criteria, because the expensive expert step is paid once per prompt and grading can be automated; corrections when the model's errors are localised and experts can fix them faster than they can rank alternatives.
Each feedback type gets one converter: feedback records in, training examples out, with lineage. The pairwise converter contains the most important line in this section: the interface randomises which response appears on the left, so the stored choice is a screen position and must be mapped back to a sample id before anything else happens.
# rldp/signals.py -- one converter per feedback kind (excerpt; full file in the package)
import math
from collections import Counter, defaultdict
from rldp.core import Feedback, TrainingExample
def pairwise_to_rm_pairs(fbs: list[Feedback], keep_ties: bool = False) -> list[TrainingExample]:
"""payload = {prompt_id, shown_left, shown_right, choice: 'left'|'right'|'tie', strength: 1..4}"""
by_item = defaultdict(list)
for f in fbs:
p = f.payload
if p["choice"] == "tie":
vote = "tie"
else: # screen position -> sample id, FIRST
vote = p["shown_left"] if p["choice"] == "left" else p["shown_right"]
by_item[f.item_id].append((vote, p, f.assignment_id))
out = []
for item, votes in by_item.items():
winner, n = Counter(v for v, _, _ in votes).most_common(1)[0]
if len(votes) > 1 and n <= len(votes) // 2:
continue # no majority among overlapped raters: drop
p = votes[0][1]
a, b = sorted([p["shown_left"], p["shown_right"]])
lineage = tuple(aid for _, _, aid in votes)
if winner == "tie":
if keep_ties:
out.append(TrainingExample("rm_pair", {"prompt_id": p["prompt_id"], "a": a, "b": b,
"target": 0.5}, lineage))
continue
loser = b if winner == a else a
strength = max(q["strength"] for v, q, _ in votes if v == winner)
out.append(TrainingExample("rm_pair", {"prompt_id": p["prompt_id"], "chosen": winner,
"rejected": loser, "strength": strength}, lineage))
return out
def sigmoid(x: float) -> float:
return 1 / (1 + math.exp(-x))
def bt_loss(r_chosen: float, r_rejected: float, margin: float = 0.0) -> float:
"""-log sigma(r_w - r_l - m): InstructGPT uses m = 0, Llama 2 a strength-dependent m."""
return -math.log(sigmoid(r_chosen - r_rejected - margin))
def fit_bt(pairs: list[tuple[str, str]], steps: int = 2000, lr: float = 0.05) -> dict[str, float]:
"""One scalar per item by gradient ascent on the Bradley-Terry log-likelihood.
A reward model does the same with r = f(prompt, response) instead of a lookup table."""
s = defaultdict(float)
for _ in range(steps):
g = defaultdict(float)
for w, l in pairs:
d = 1 - sigmoid(s[w] - s[l]) # d/ds_w of log sigma(s_w - s_l)
g[w] += d; g[l] -= d
for k in g:
s[k] += lr * g[k] / len(pairs) * 10
mean = sum(s.values()) / len(s) # identifiable only up to a constant
for k in s: s[k] -= mean
return dict(s)
def correction_to_examples(prompt, steps, first_bad, corrected, lineage):
prefix = steps[:first_bad] # everything the expert judged correct
return [TrainingExample("sft", {"prompt": prompt, "context": prefix, "target": corrected}, lineage),
TrainingExample("rm_pair", {"prompt": prompt, "context": prefix,
"chosen": corrected, "rejected": steps[first_bad]}, lineage)]
def process_labels(n_steps: int, first_bad: int | None) -> list[int | None]:
"""+1 before the first failing step, -1 at it, None (unlabelled) after it."""
if first_bad is None:
return [1] * n_steps
return [1] * first_bad + [-1] + [None] * (n_steps - first_bad - 1)
def rubric_reward(items: list[dict]) -> float:
"""items: [{weight > 0, score in 0..1}] -> weighted mean in [0, 1]."""
tw = sum(i["weight"] for i in items)
if tw <= 0:
raise ValueError("rubric has no positive weight")
return sum(i["weight"] * i["score"] for i in items) / tw
The red-team converter (in the package) emits an eval-split record for every finding and a safety-tagged pair when a safe response was written. The tests check the behaviours that break silently in production: display order must not change the label, overlap uses majority vote, ties are excluded by default, Bradley–Terry recovers a known ordering, and the 72% → 0.83 ceiling from the Design level.
# rldp/tests/test_signals.py (excerpt)
import math, random, pytest
from rldp.core import Feedback
from rldp.signals import pairwise_to_rm_pairs, bt_loss, fit_bt, sigmoid, process_labels, rubric_reward
def fb(aid, item, rater, left, right, choice, strength=2):
return Feedback(aid, item, rater, "pairwise", {"prompt_id": "p1", "shown_left": left,
"shown_right": right, "choice": choice, "strength": strength}, 240.0)
def test_display_order_does_not_change_the_label():
a = pairwise_to_rm_pairs([fb("a1", "i1", "r1", "s_cur", "s_cand", "right")])
b = pairwise_to_rm_pairs([fb("a2", "i1", "r2", "s_cand", "s_cur", "left")])
assert a[0].data["chosen"] == b[0].data["chosen"] == "s_cand"
def test_overlap_majority_and_ties():
votes = [fb("a1", "i2", "r1", "x", "y", "left"), fb("a2", "i2", "r2", "y", "x", "right"),
fb("a3", "i2", "r3", "x", "y", "right")] # x, x, y
out = pairwise_to_rm_pairs(votes)
assert out[0].data["chosen"] == "x" and len(out[0].lineage) == 3
tie = [fb("a4", "i3", "r1", "x", "y", "tie")]
assert pairwise_to_rm_pairs(tie) == []
assert pairwise_to_rm_pairs(tie, keep_ties=True)[0].data["target"] == 0.5
def test_bt_loss_values():
assert bt_loss(0.0, 0.0) == pytest.approx(math.log(2))
assert bt_loss(2.0, 0.0) < bt_loss(2.0, 0.0, margin=1.0)
def test_fit_bt_recovers_order():
random.seed(0); true = {"a": 1.0, "b": 0.0, "c": -1.0}; pairs = []
for _ in range(600):
i, j = random.sample(list(true), 2)
pairs.append((i, j) if random.random() < sigmoid(true[i] - true[j]) else (j, i))
s = fit_bt(pairs)
assert s["a"] > s["b"] > s["c"] and s["a"] - s["c"] == pytest.approx(2.0, abs=0.5)
def test_agreement_implies_ceiling():
p = (1 + math.sqrt(1 - 4 * 0.14)) / 2 # p^2 + (1-p)^2 = 0.72
assert p == pytest.approx(0.8317, abs=1e-4)
assert math.log(p / (1 - p)) == pytest.approx(1.60, abs=0.01)
def test_process_labels_and_rubric():
assert process_labels(5, 3) == [1, 1, 1, -1, None]
assert rubric_reward([{"weight": 3, "score": 1}, {"weight": 1, "score": 0},
{"weight": 1, "score": 1}]) == pytest.approx(0.8)
Debugging tips. If a reward model trained on fresh data scores near 50% on held-out pairs, check side mapping before anything else: compute the chosen rate for each display side; they should match. If overlapped items produce more pairs than items, aggregation ran after conversion instead of before. If rubric rewards cluster at 1.0, the rubric items are too easy for current responses and carry no gradient; the rubric needs harder items, not more of them.
The conversion step is where silent failures concentrate, because a converter that produces well-formed but wrong examples passes every schema check. The most damaging such failure for preference data is a side-mapping flip: the exporter maps a screen position to the wrong sample, so "chosen" and "rejected" are swapped for part of the data. It matters because a reward model trained on partly inverted labels learns a weaker or inverted signal, and RL then optimises toward it. Its root cause is that interfaces randomise display order to control position bias, so every exporter must undo the randomisation, and a refactor that touches this mapping can break it for a subset of items.
Symptom. The reward model retrained with W1 data scores lower on its held-out gold set than the previous version. Illustrative assumptions: exporter v2, deployed mid-collection, ignored shown_left for items whose candidate response was displayed on the left (half of items, by randomisation); 8,000 comparisons passed through v2.
Size. About 4,000 of the 18,400 useful comparisons (≈ 22%) were inverted. With agreement-implied accuracy \(p \approx 0.83\), the effective agreement of a training label with the latent preference falls from 0.83 to roughly \(0.78 \times 0.83 + 0.22 \times 0.17 \approx 0.69\) across the whole set.
Diagnosis. The decisive measurement is side balance: the rate at which the candidate is chosen, split by which side it was shown on. Raters may prefer the candidate (say 58% of the time, an illustrative value), but that rate should not depend on display side. In the v2 window it was 58% when the candidate was shown right and 42% when shown left. On 4,000 items per side the standard error of a difference of proportions is about \(\sqrt{2 \times 0.25/4{,}000} \approx 0.011\), so a 16-point gap is about 14 standard errors: not chance. Lineage then identifies exactly which examples came through v2.
Remedy. Re-export the v2 window with the corrected mapper from raw feedback records (the raw records were correct; only the derived examples were wrong), retrain the reward model, and add side balance as a blocking export check. Rejected alternative: discarding the 8,000 v2 comparisons would cost about \(8{,}000 \times \$4.12 \approx \$33{,}000\) of labels that are recoverable.
Validation. The fix is supported if side balance in the re-export falls within 3 standard errors and held-out gold accuracy of the retrained reward model returns to at least the previous version's; it is weakened if side balance is fixed but gold accuracy does not recover, which would point to a second cause such as a change in rater population during the same window.
Export contract checks (block the export on failure):
| Check | Rule | Catches |
|---|---|---|
| Side balance | |chosen-rate(left) − chosen-rate(right)| ≤ 3 SE | side-mapping flips, position bias in the UI |
| Gold replay | converter output on gold items equals the gold answers 100% | any mapping or aggregation bug |
| Lineage completeness | every example has ≥ 1 assignment id; every assignment exists | orphaned or fabricated examples |
| Count reconciliation | pairs + ties + dropped = aggregated items | double counting of overlap |
| Tie and strength mix | tie rate within ±3 points of campaign mean (W1 8%) | UI changes that alter the label distribution |
Table. Export contract for pairwise data. Thresholds are this book's defaults.
Gold replay is the cheapest high-value check: gold items have known answers, so running the converter over them must reproduce those answers exactly; a mapping bug cannot pass it. The same principle generalises to every feedback type: W2 process labels are replayed against expert-adjudicated transcripts, W3 rubric rewards against hand-computed scores. The next section asks where human labels are required at all.
Why Human Data Still Matters in 2026
Two developments since 2022 have reduced how much RL post-training depends on people, and a platform designer needs to know exactly where each one stops. The first is reinforcement learning with verifiable rewards (RLVR): when a program can check an answer (a math result, a unit test), the program supplies the reward and no human is needed per sample. The term was introduced with the Tülu 3 models (Lambert et al., 2024). DeepSeek-R1-Zero trained reasoning with rule-based accuracy and format rewards only, and its authors avoided neural outcome and process reward models for reasoning because such models are susceptible to reward hacking at scale (DeepSeek-AI, 2025). The second is AI feedback: a capable model judges outputs in place of a person. Constitutional AI trained a harmless assistant with no human labels identifying harmful outputs, only a list of written principles (Bai et al., 2022b), and RLAIF performed comparably to RLHF on summarisation and dialogue tasks (Lee et al., 2023). Strong LLM judges reached over 80% agreement with human preferences, about the level at which humans agree with each other (Zheng et al., 2023).
Neither development removes the need for human data. It changes what humans are needed for. Four boundaries explain where.
1. Non-verifiable domains. Much of what users value has no checker: whether an explanation is clear, whether code is maintainable as well as passing, whether a legal draft protects the client. Even DeepSeek-R1, the emblem of rule-based rewards, used reward models trained on preference data for general queries (DeepSeek-AI, 2025). Someone has to supply the judgments those reward models imitate.
2. Expert judgment. In specialised fields the relevant judgment belongs to a small number of people, and the efficient pattern is to capture it once in a reusable form. HealthBench's 48,562 rubric criteria were written by 262 physicians (Arora et al., 2025); Rubrics as Rewards shows that such rubrics, applied by a model, can serve as RL rewards (Gunjal et al., 2025). The expert is no longer labelling every sample, but without the expert there is no rubric.
3. Verifier limits. Programs check what they check, and RL optimises against exactly that. METR found OpenAI's o3 reward hacking in 39 of 128 runs (30.4%) on its RE-Bench tasks, with exploits that included overwriting a timing function so it reported shorter times and monkey-patching an evaluator to always return a perfect score (METR, 2025); a September 2026 review concluded that no robust mitigation yet exists (Rogero, 2026). Learned rewards degrade the same way: optimising too hard against a proxy reward model lowers the true objective (Gao et al., 2022). Humans are how such gaming is found, labelled and fed back as data.
4. The boundary of AI feedback. An AI judge is a model of human judgment, so its validity has to be measured against humans, continuously, on the platform's own tasks. Judges have known biases toward position, verbosity and their own outputs (Zheng et al., 2023). And "human" data can quietly stop being human: one study estimated that 33–46% of crowd workers on a summarisation task used LLMs (Veselovsky et al., 2023), which would make the human labels partly a copy of the model's own judgment.
Compared with 2022-era RLHF, where humans labelled the samples RL trained on, the 2026 pattern is layered: verifiers where a check exists, AI judges where they have been calibrated, and humans writing checks and rubrics, labelling what neither can judge, auditing both, and finding the ways the policy games them. Human labels per RL step have fallen; the value and difficulty of each human label have risen.
What you would actually do. Route each task class to the cheapest labeller that is measured to be good enough for it, and keep a standing human audit on every automated labeller. Default to humans for new task classes until a judge has been calibrated on them, and to human review of every high-stakes class even after. The next section defines the metrics that tell whether the platform delivering this human data is doing its job.
The decision of who labels a task class (a program, an AI judge, or people) can be made quantitative with three numbers: the labeller's measured agreement with expert humans, the cost per label, and the size of the audit needed to keep the agreement estimate trustworthy.
Calibration against humans. Let \(a_{AH}\) be the agreement rate between an AI judge and human labels on a calibration set, and \(a_{HH}\) the agreement between two humans on the same items. Following the logic used for LLM judges (Zheng et al., 2023), a judge with \(a_{AH} \ge a_{HH}\) is as consistent with humans as humans are with each other on that task class. A fixed threshold, as in W3's item-level 0.8, is simpler to operate and stricter when \(a_{HH}\) is low.
Audit size. Agreement is estimated from a sample of \(n\) items labelled by both the AI and humans. With the normal approximation, the half-width of a 95% confidence interval is \(e = 1.96\sqrt{a(1-a)/n}\), so the sample needed for a desired \(e\) is
\[ n = \frac{z^2\, a(1-a)}{e^2}, \qquad z = 1.96 . \]Contamination of human data. If a fraction \(c\) of nominally human labels were produced by an LLM, the platform's measured human–AI agreement is inflated. Suppose genuine humans agree with the judge at rate \(a_h\) and LLM-produced labels agree at a higher rate \(a_m\). The measured agreement is \(\hat a = (1-c)\,a_h + c\,a_m\). With an illustrative \(a_h = 0.75\), \(a_m = 0.95\) and \(c = 0.33\) (the low end of the crowd-work estimate in Veselovsky et al., 2023), \(\hat a \approx 0.82\): a judge that should fail a 0.8 gate passes it. Contamination does not just add noise; it biases calibration toward the model.
Verifier rewards still need audits. If a verifier passes a fraction \(h\) of outputs that a human would reject (reward hacks plus false passes), RL drives \(h\) up wherever doing so is easier than solving the task. Estimating \(h\) needs human review of passed outputs; at an expected \(h\) of 5% and \(e = \pm 0.02\), \(n \approx 1.96^2 \times 0.05 \times 0.95/0.02^2 \approx 457\) passed samples per audit.
| Task class | Verifier | Measured judge agreement | Stakes | Route | Human role |
|---|---|---|---|---|---|
| Unit-tested code correctness | tests | n/a | low | verifier | audit ~460 passes per round for hacks |
| W1 coding helpfulness | partial | not yet measured | medium | human | label; build calibration set from overlap |
| Same, once judge ≥ 0.80 | partial | ≥ 0.80 | medium | AI first pass | audit ~1,540 items per round |
| W3 legal rubric grading | none | ≥ 0.80 required | high | AI with human review | write rubrics; review disagreements; audit |
Table. A routing table for the reference workloads. Agreement values are gates, not measurements.
Decision. Route by measured agreement and stakes, never by assumed capability. Re-measure agreement whenever the judge model, its prompt or the task distribution changes, because each of those can move agreement without anyone noticing.
The routing decision belongs in configuration, not in code paths scattered across services, so that the policy can be reviewed and changed by the people accountable for data quality. routing.yaml declares the policy; route.py applies it to a task class and a measured judge agreement, and sizes the human audit.
# rldp/routing.yaml -- who produces the label for each task class.
# Agreement numbers are MEASURED on a human-labelled calibration set, never assumed.
defaults:
min_judge_human_agreement: 0.80 # below this, the AI judge may not label alone
audit_margin: 0.02 # CI half-width wanted on audited agreement
max_stakes_for_ai_only: medium # high-stakes classes always keep humans in the loop
classes:
- name: w1_coding_pairwise
verifier: null # helpfulness of code is not fully checked by unit tests
stakes: medium
- name: w3_legal_rubric_grading
verifier: null
stakes: high
- name: unit_tested_code_correctness
verifier: unit_tests
stakes: low
# rldp/route.py -- decide verifier / AI judge / human for a task class, and size the audit.
import math, yaml
STAKES = {"low": 0, "medium": 1, "high": 2}
def audit_size(p: float, margin: float, z: float = 1.96) -> int:
"""Items to label twice (human + AI) to estimate agreement p to +/- margin (normal approx.)."""
return math.ceil(z * z * p * (1 - p) / (margin * margin))
def route(cls: dict, defaults: dict, judge_agreement: float | None) -> dict:
margin = defaults["audit_margin"]
if cls.get("verifier"):
# verifiers can be gamed (reward hacking): keep a small human audit of passes
return {"labeller": "verifier", "human_audit_items": audit_size(0.95, 0.02)}
ok_quality = judge_agreement is not None and judge_agreement >= defaults["min_judge_human_agreement"]
ok_stakes = STAKES[cls["stakes"]] <= STAKES[defaults["max_stakes_for_ai_only"]]
if ok_quality and ok_stakes:
return {"labeller": "ai_first_pass", "human_audit_items": audit_size(judge_agreement, margin)}
if ok_quality: # good judge, high stakes: AI scores, humans review every disagreement + audit
return {"labeller": "ai_with_human_review", "human_audit_items": audit_size(judge_agreement, margin)}
return {"labeller": "human", "human_audit_items": 0}
def load(path: str = "rldp/routing.yaml") -> dict:
with open(path) as f:
return yaml.safe_load(f)
# rldp/tests/test_route.py
from rldp.route import audit_size, route, load
def test_audit_size_w3():
assert audit_size(0.80, 0.02) == 1537 # W3 audit for +/-0.02 around 0.80
def test_routing_decisions():
cfg = load()
d, c = cfg["defaults"], {x["name"]: x for x in cfg["classes"]}
assert route(c["unit_tested_code_correctness"], d, None)["labeller"] == "verifier"
# the agreement values below are hypothetical test inputs, not measurements
assert route(c["w1_coding_pairwise"], d, 0.70)["labeller"] == "human"
assert route(c["w1_coding_pairwise"], d, 0.84)["labeller"] == "ai_first_pass"
assert route(c["w3_legal_rubric_grading"], d, 0.84)["labeller"] == "ai_with_human_review"
The verifier branch sizes its audit for an expected hack-or-false-pass rate of 5% at ±0.02, which is 457 items; the judge branches size theirs from the measured agreement. A None agreement routes to humans: the absence of a measurement is treated as a failed measurement.
Debugging tips. If a task class flips between AI and human routing week to week, the agreement estimate is noisier than the gate margin; increase the audit or add hysteresis (for example, require two consecutive audits above 0.80 to switch to AI, and one below 0.78 to switch back). If audited agreement is suspiciously high, check whether the human audit labels were collected with the AI's label visible: anchoring inflates agreement, so audits must be blind.
Once an AI judge or grader is producing rewards, its agreement with humans becomes a production metric with an SLO, because the RL policy will exploit any drift. The problem matters because a drifted grader is a silent failure: rubric rewards keep rising, training curves look healthy, and the degradation is found only when humans read the outputs. The usual root cause is an unreviewed change to the grader (new model version, edited prompt, changed parsing) or a shift in the responses it grades as the policy improves.
Symptom. During W3 RL training, mean rubric reward climbs steadily while the weekly blind human audit shows human-scored rubric reward flat. Illustrative assumptions: the grader was upgraded to a newer model version between audits; item-level agreement on the audit fell from 0.84 to 0.74.
Measurements that separate causes. (1) Agreement on the frozen calibration set from the original 120,000 human item scores: if it also fell, the grader changed; if it held, the policy's outputs moved into a region the grader handles badly. Here it fell to 0.75, implicating the grader. (2) Agreement by rubric item type: the drop concentrated in items about missing protective clauses, where the new grader credited clauses that were mentioned but not drafted. (3) Standard error at \(n = 1{,}537\) and \(a = 0.74\) is \(\sqrt{0.74 \times 0.26/1{,}537} \approx 0.011\), so the 95% interval (0.72–0.76) excludes the 0.80 gate decisively.
Remedy chosen. Roll back to the pinned previous grader version; mark RL checkpoints trained since the upgrade as suspect and compare them against the last good checkpoint on a human-graded evaluation before deciding whether to discard them; put every grader change behind a gate that re-runs the frozen calibration set and requires ≥ 0.80 overall and ≥ 0.75 on every item type.
Cost and trade-off. The weekly audit costs about 5 grader-hours (154 responses × 2 min). The gate adds one calibration run per grader change. The expensive part is the compute already spent on suspect checkpoints, which grows with every day between audits; auditing twice a week halves the worst-case loss for about 5 more grader-hours per week.
Validation. The fix is supported if the next audit shows agreement ≥ 0.80 and the gap between mean grader reward and mean human-scored reward stops widening. It is weakened if agreement recovers on the frozen set but not on fresh policy outputs, which would mean the policy has learned to exploit the old grader too.
| Signal | Formula | Alert |
|---|---|---|
| Judge–human agreement (fresh) | agree / audited items, blind audit | < 0.80, or 95% CI upper bound < 0.80 |
| Judge–human agreement (frozen set) | same, on the fixed calibration set | any drop > 0.03 after a grader change |
| Reward gap | mean AI reward − mean human-scored reward on audit | rising for 2 consecutive audits |
| Verifier pass audit | human-rejected / passed, sample of ~460 | > 5% or rising |
| Human-ness of human labels | share of free-text feedback flagged as model-written; paste events | > campaign baseline + 3 points |
Table. Monitors for the human–AI boundary. Thresholds are this book's defaults; the human-ness detectors are covered in the quality chapter.
Runbook: grader drift. (1) Freeze promotion of RL checkpoints that used the grader. (2) Run the frozen calibration set on current and previous grader versions. (3) If only the current version fails, roll back and open a review of the change. (4) If both fail on fresh outputs but pass on the frozen set, the policy is exploiting the grader: add the exploited pattern as new rubric items or human-labelled negatives and raise the audit rate. (5) Record the incident's training-compute loss against the grader change, so the cost of ungated changes is visible.
North-Star Metrics
A platform needs a few numbers that say whether it is doing its job, chosen so that improving them improves the models trained on its data. Five cover the loop: two about speed, one about money, one about quality and one about who can use the platform. Each is defined below by what it measures, where its clock starts and stops, why it matters, and how it misleads if used alone.
Time-to-first-sample (TTFS) is the time from a rater asking for the next task to the task's model samples being rendered and usable. It is measured per assignment and reported as percentiles: the median (p50) describes the typical wait, the 95th percentile (p95) the bad waits that break concentration. It matters because raters are paid for their time and every second of waiting is paid for; across 25,000 assignments, every 3 seconds of wait per assignment adds about 21 paid hours. It misleads if it ignores what the rater sees: a fast render of a broken sample is not a success. A related campaign-level quantity, the time from launch to the first labelled item, matters to researchers and is tracked inside request-to-mix.
Request-to-mix latency is the time from a researcher filing a data request to the first training run that consumes the resulting data. It is the metric researchers feel, because it bounds how many data experiments they can run per model generation, and because data collected on an old checkpoint loses value as the model moves on. It misleads if the clock starts at campaign launch (hiding scoping and pilots) or stops at export (hiding the slowest hand-off, into training).
Cost per useful label is everything spent on a campaign divided by the number of labels that actually reach training. "Everything" includes gold items, overlapped labels, rejected work and pilots; "useful" excludes anything QA removed. It matters because it is the honest unit price of human data and the number a data-value analysis compares against model improvement. It misleads if it rewards cutting quality checks, which lowers cost per label while lowering the value of each label more.
Label quality is not one number but a small set: accuracy on gold items (does the rater get known answers right), agreement between raters on overlapped items (is the task well defined), tie or abstain rate (is the task too hard to call), and effort signals such as time per label. The final arbiter is downstream: does the reward model trained on the data get better on held-out human judgments. It misleads if gold items are easier than the real task, or if agreement is high because raters copy the same model.
Researcher self-serve rate is the share of campaigns a researcher takes from request to live data without a platform engineer doing work for them. It matters because engineer involvement is the hidden queue behind request-to-mix: if every campaign needs an engineer, the platform's throughput is its engineering headcount. It misleads if researchers launch campaigns self-serve that are badly scoped, so it is read together with pilot rejection rates.
Compared with generic labelling metrics (labels per hour, cost per label), these five are tied to the loop's purpose: getting a correct training signal into a model quickly. Labels per hour can rise while request-to-mix stays flat, if the bottleneck is scoping or export. What you would actually do: instrument all five from day one, from raw events rather than manual reports, and review them per campaign. Default to request-to-mix as the headline metric for the platform team and cost per useful label as the headline for each campaign; never report cost without quality beside it. Later chapters return to each metric in depth: TTFS in sample generation, quality in the quality program, request-to-mix in the path into the training mix.
Each north-star metric has a formula whose terms point at a design lever. Writing them down shows which levers move which metric, and where measuring a metric needs more data than the campaign naturally produces.
TTFS and buffer misses. Let \(m\) be the probability that a request finds the buffer empty for its campaign (a miss), \(t_h\) the latency of a hit (fetch and render) and \(t_g\) the generation latency paid on a miss. If hits are always fast (\(t_h < 5\) s) and misses always slow (\(t_h + t_g > 5\) s), then \(P(\text{TTFS} > 5\,\text{s}) = m\), so a p95 ≤ 5 s target requires \(m < 0.05\). The miss rate, not the render speed, sets p95; it is a buffer-sizing problem.
Cost per useful label decomposes into three factors. With hourly rate \(r\), mean minutes per assignment \(\bar t\), assignments \(A\), target items \(N\), and QA yield \(y\) (fraction of items kept), the labour cost per useful item is
\[ c_u = \underbrace{\frac{r\,\bar t}{60}}_{\text{cost per assignment}} \times \underbrace{\frac{A}{N}}_{\text{overhead (overlap, gold)}} \times \underbrace{\frac{1}{y}}_{\text{rejects}} . \]The decomposition is the reason interface work is a cost lever: \(\bar t\) multiplies everything.
Gold accuracy needs more gold per rater than a campaign provides. If rater \(j\) answers \(g_j\) gold items with true accuracy \(q_j\), the standard error of the estimate is \(\sqrt{q_j(1-q_j)/g_j}\). To tell whether a rater is above the threshold \(\tau\) one needs the error to be small compared with the distance of \(q_j\) from \(\tau\).
Request-to-mix across a portfolio. For a set of campaigns, report the median and p90 of \(T_\text{mix}\) plus the share of time each stage holds, \(T_s / T_\text{mix}\). For the W1 baseline: collection holds \(6/21 \approx 29\%\); scoping plus pilot hold \(7/21 \approx 33\%\), more than collection, which is why tooling for scoping and launch has a larger lever than faster labelling.
Self-serve rate. \(S = \) (campaigns with zero engineer tickets between request and first labelled data) / (campaigns). Its value as a lever: if a fraction \(1-S\) of campaigns wait a mean of \(d\) days in an engineering queue, the expected request-to-mix contribution of that queue is \((1-S)\,d\). This book does not assign W1 a value for \(S\) or \(d\).
| Metric | Formula | Main lever | W1 (illustrative) |
|---|---|---|---|
| TTFS | p50, p95 of per-assignment latency | buffer miss rate \(m\) | ≤ 2 s / ≤ 5 s |
| Request-to-mix | request filed → first training run using data | critical path, pool share | 21 d → 7 d |
| Cost per useful label | \(r\bar t/60 \cdot A/N \cdot 1/y\) | \(\bar t\), overhead, yield | $4.12 |
| Label quality | gold acc., agreement, ties, effort | guidelines, rater selection, UI | ≥ 80%, 72%, 8%, 4% flagged |
| Self-serve rate | zero-ticket campaigns / campaigns | launcher, validation, preview | not specified |
Table. North-star metrics, formulas and levers. W1 values are illustrative workload numbers.
Decision. Optimise request-to-mix by attacking the largest stage share first, and cost per useful label by attacking \(\bar t\) first, since it multiplies everything. Hold quality fixed while doing either: an improvement in cost or speed that lowers agreement or gold accuracy is not an improvement.
Metrics are only trustworthy if they are computed from raw events by code that has tests, so that a dashboard and a report can never disagree about what "p95" or "useful" means. metrics.py implements all five; the percentile uses the nearest-rank definition so that small samples give an observed value rather than an interpolation.
# rldp/metrics.py -- the five north-star metrics, computed from raw platform events.
import math, statistics
from itertools import combinations
def percentile(xs: list[float], q: float) -> float:
"""Nearest-rank percentile (q in 0..100); the definition dashboards should agree on."""
s = sorted(xs)
return s[max(0, math.ceil(q / 100 * len(s)) - 1)]
def ttfs(latencies_s: list[float]) -> dict:
"""Time-to-first-sample per assignment: 'next task' click -> samples rendered and interactive."""
return {"p50": percentile(latencies_s, 50), "p95": percentile(latencies_s, 95)}
def cost_per_useful_label(labour_usd: float, useful: int) -> float:
"""All money spent (gold, overlap, rejected work included) / labels that reach training."""
return labour_usd / useful
def pairwise_agreement(labels_by_item: dict[str, list[str]]) -> float:
"""Share of rater pairs on overlapped items that gave the same label."""
agree = total = 0
for labels in labels_by_item.values():
for a, b in combinations(labels, 2):
agree += a == b; total += 1
return agree / total
def gold_accuracy(gold_results: list[bool]) -> float:
return sum(gold_results) / len(gold_results)
def low_effort_raters(seconds_by_rater: dict[str, list[float]], floor_s: float = 40) -> set[str]:
"""Raters whose MEDIAN time per label is below the floor (W1 rule: 40 s)."""
return {r for r, xs in seconds_by_rater.items() if statistics.median(xs) < floor_s}
def self_serve_rate(campaigns: list[dict]) -> float:
"""Share of campaigns from request to first labelled data with zero platform-engineer tickets."""
return sum(c["eng_tickets"] == 0 for c in campaigns) / len(campaigns)
Request-to-mix comes from the stage event log in loop.py. The tests assert the W1 numbers and the buffer-miss argument from the Design level: with 4% of requests waiting on generation, p95 meets the 5-second target; with 6%, it does not.
# rldp/tests/test_metrics.py
import pytest
from rldp.metrics import (ttfs, cost_per_useful_label, pairwise_agreement, gold_accuracy,
low_effort_raters, self_serve_rate)
def test_w1_cost_per_useful_label():
labour = 25_260 * 4.5 / 60 * 40 # ~1,895 rater-hours at $40/h
assert labour == pytest.approx(75_780)
useful = round(20_000 * (1 - 0.08)) # QA rejects 8%
assert useful == 18_400
assert cost_per_useful_label(labour, useful) == pytest.approx(4.12, abs=0.005)
def test_ttfs_slo():
lat = [0.8] * 90 + [3.0] * 6 + [12.0] * 4 # 4% buffer misses wait for generation
t = ttfs(lat)
assert t["p50"] <= 2 and t["p95"] <= 5 # W1 SLO met with 4% misses ...
lat = [0.8] * 90 + [3.0] * 4 + [12.0] * 6 # ... and broken with 6%
assert ttfs(lat)["p95"] > 5
def test_agreement_on_overlap():
items = {"i1": ["x", "x", "y"], "i2": ["x", "x", "x"]} # 1/3 and 3/3 rater pairs agree
assert pairwise_agreement(items) == pytest.approx(4 / 6)
def test_quality_gates():
assert gold_accuracy([True] * 41 + [False] * 9) == pytest.approx(0.82) # >= 0.80 passes
assert low_effort_raters({"r1": [30, 35, 200], "r2": [240, 260, 31]}) == {"r1"}
def test_self_serve():
assert self_serve_rate([{"id": "a", "eng_tickets": 0}, {"id": "b", "eng_tickets": 2}]) == 0.5
A metric is only as good as its event definitions. The events the platform must emit for these functions, with the field that anchors each clock:
{"event": "task_requested", "assignment_id": "...", "rater_id": "...", "ts": "..."} # TTFS start
{"event": "task_interactive", "assignment_id": "...", "buffer_hit": true, "ts": "..."} # TTFS stop
{"event": "feedback_submitted","assignment_id": "...", "seconds_spent": 241.0, "ts": "..."}
{"event": "qa_decision", "assignment_id": "...", "accepted": true, "reason": null}
{"event": "stage_changed", "campaign_id": "w1_pairwise_coding", "stage": "export", "ts": "..."}
{"event": "mix_consumed", "campaign_id": "w1_pairwise_coding", "training_run": "...", "ts": "..."} # request-to-mix stop
{"event": "eng_ticket", "campaign_id": "w1_pairwise_coding", "category": "launch_config"}
Debugging tips. If TTFS looks excellent but raters complain, check that task_interactive is emitted by the browser after render, not by the server after it sends the response. If cost per useful label drops suddenly, check whether QA rejects stopped being recorded rather than stopped happening. If agreement jumps after an interface release, check whether the new interface shows a default selection, which anchors raters to the same answer.
Operating the north-star metrics means turning each into an SLO with an owner, a dashboard panel and an alert, and reviewing them per campaign while the campaign is still running, when a problem can still be fixed cheaply. The scenario below shows the most common mid-campaign issue: cost per useful label drifting above plan, with two causes mixed together that need opposite responses.
| Metric | SLO (W1, illustrative) | Alert | Owner |
|---|---|---|---|
| TTFS | p50 ≤ 2 s, p95 ≤ 5 s over 5 min | p95 > 5 s for 10 min; buffer < 30 min of draw | platform on-call |
| Request-to-mix | ≤ 7 days | any stage > its planned share by 1 day | campaign owner |
| Cost per useful label | ≤ $4.53 (plan + 10%) | projected \(c_u\) > plan + 10% | campaign owner |
| Label quality | gold ≥ 80%; agreement within 5 pts of pilot | daily gold < 80%; agreement drop > 5 pts | quality lead |
| Self-serve rate | rising quarter over quarter | ticket category growing 2 months running | platform lead |
Table. SLOs, alerts and owners for the north-star metrics. Targets are this book's defaults.
Symptom. Halfway through collection, projected cost per useful label is $4.70 against the $4.12 plan, a 14% overrun that breaches the $4.53 SLO. Illustrative assumptions: mean time per assignment rose from 4.5 to 4.8 minutes and QA yield fell from 0.92 to 0.86.
Diagnosis by decomposition. Using \(c_u = (r\bar t/60)(A/N)(1/y)\): cost per assignment rose \(4.8/4.5 \approx +6.7\%\); the reject factor rose \(0.92/0.86 \approx +7.0\%\); overhead was unchanged. Combined: \(3.20 \times 1.263/0.86 \approx \$4.70\). Two causes, each about half the overrun. Slicing each factor separates their roots. Time per assignment rose only on prompts from the sampler's later batches, which contain longer multi-file coding prompts: the task got harder, not the raters slower. The yield drop concentrated in a cohort of raters added to keep the schedule, whose gold accuracy was 71% against 84% for the original pool.
Remedy chosen. For the time factor: accept it and re-plan, because the longer prompts are what the researcher needs, and cutting time would mean cutting care. For the yield factor: move the new cohort back to qualification, require 50 gold items at ≥ 80% before they return, and route their pending work to the original pool. Rejected alternative: lowering the gold threshold to 75% to raise yield would cut reported cost while admitting more wrong labels, a false saving that the reward model pays for.
Cost and trade-off. Removing the cohort reduces pool hours, extending collection by about a day. Re-planned cost with yield restored: \(3.20 \times 1.263/0.92 \approx \$4.39\), within the SLO.
Validation. The remedy is supported if daily QA yield returns to ≥ 0.91 within two days of the cohort's removal and the projected \(c_u\) settles near $4.39. It is weakened if yield stays low with the original pool alone, which would mean the harder prompts themselves are raising rejects and the guidelines need a clarification round for multi-file code.
# dashboard panel queries (SQL over the event tables; names are this book's)
-- cost per useful label, projected, per campaign
SELECT c.id,
SUM(f.seconds_spent) / 3600.0 * c.rate_usd_per_h AS labour_usd,
COUNT(*) FILTER (WHERE q.accepted AND NOT a.is_gold) AS useful_labels,
SUM(f.seconds_spent) / 3600.0 * c.rate_usd_per_h
/ NULLIF(COUNT(*) FILTER (WHERE q.accepted AND NOT a.is_gold), 0) AS usd_per_useful
FROM campaigns c JOIN assignments a ON a.campaign_id = c.id
JOIN feedback f ON f.assignment_id = a.id JOIN qa_decisions q ON q.assignment_id = a.id
GROUP BY c.id;
-- side balance (integrity panel): candidate chosen-rate by display side
SELECT shown_side_of_candidate, AVG(CASE WHEN chosen = 'candidate' THEN 1.0 ELSE 0 END)
FROM pairwise_labels WHERE campaign_id = 'w1_pairwise_coding' GROUP BY 1;
Two cautions about the query. It counts useful labels, not aggregated items, so overlapped items appear up to three times; the campaign-level figure divides by aggregated useful items instead, which is how $4.12 is defined. And it uses logged seconds as paid time, which holds only if raters are paid by logged time; for per-task pay, replace the labour term with the per-task price.
Weekly review checklist. (1) For each running campaign, compare projected \(c_u\), \(T_\text{mix}\) and quality against plan; decompose any overrun into its factors before acting. (2) Read the integrity panel (buffer depth, schema errors, side balance) first: most sudden moves in the other metrics start there. (3) For each engineer ticket filed by a researcher, record its category; the largest category is the next self-serve feature. (4) Close the loop with the model team: for each campaign that reached the mix, record the reward-model or policy change it produced, because a cheap, fast, high-agreement campaign that changes nothing is the most expensive kind.
Lineage and Publications
Every human-data platform for RL post-training carries design decisions that were first made, and first measured, in a short list of papers. The pairwise comparison widget dates to 2017, when contractors pressed arrow keys to choose between two one-second video clips. Rater screening against researcher labels, hourly pay, and the habit of measuring labeler–researcher agreement come from the summarisation work of 2020. The ranking interface with four to nine candidate responses and the written labeling guidelines come from InstructGPT. Weekly batches collected on the latest checkpoint come from Anthropic's HH work and Llama 2. Replacing human harmlessness labels with a written constitution, then replacing holistic judgments with per-prompt rubrics, are AI-feedback developments of 2022 to 2025. Step-level labels began with grade-school maths and are now applied to sixty-step agent transcripts. Underneath all of this sits a much older statistics literature on how to combine labels from people who disagree and make mistakes.
This chapter is a reference: one dense pass, organised as a lineage. For each work it gives the problem it attacked, the data-collection mechanism (who labelled, through what interface and format, how many labels, and what quality control was applied), the key result with numbers taken from the source, what it left open, and who picked it up. Dates are arXiv submission or publication dates as the source states them. Numbers that belong to the book's reference workloads (W1 pairwise coding preferences, W2 expert review of agent transcripts, W3 rubric data for legal drafting; see the front matter) appear only in callouts marked "Worked example" and are illustrative, not published results. Where this chapter infers a lineage link that the authors did not state, the text says so.
Four threads run through the chapter. The final section draws them as a map and proposes a reading order.
| Thread | Question it answers for a data platform | Oldest root here | 2025–2026 frontier |
|---|---|---|---|
| Preference learning → RLHF | What do raters look at, what do they click, and how many clicks does a reward model need? | Christiano et al. (2017) | Small, heavily filtered multi-attribute sets (HelpSteer2); arena-scale crowd votes |
| AI feedback, judges, rubrics | Which human labels can a model produce instead, and what must humans still write? | Constitutional AI (2022) | Expert- or LLM-written rubrics as RL rewards; verifying rubric judges on agent tasks |
| Process and agentic supervision | Should humans label outcomes, every step, or the first wrong step? | Uesato et al. (2022) | First-error and per-step human labels on agent trajectories; process reward models for agents |
| Annotation science | How do you know labels are any good, and still human? | Dawid & Skene (1979) | Detecting LLM use by annotators; disagreement treated as data; expert-written benchmarks |
Table. The four threads of this chapter, one section each, followed by the map and reading order.
Preference learning to RLHF: Christiano 2017, Stiennon 2020, InstructGPT, Anthropic HH (Bai 2022), Llama 2 data practices
The line from 2017 to 2024 is a story about the same object, the pairwise comparison, being scaled, standardised and then pruned. Each paper below changed one property of the data: who supplied it, what they saw, how strongly they could express a preference, how the pool was screened, and how often new data was collected against the current model. The final entries in the section (HelpSteer2, Chatbot Arena and DPO) show the two directions the field took after Llama 2: much smaller but more carefully controlled datasets, and much larger but uncontrolled crowd votes, with DPO changing what the data is consumed by.
Christiano et al. (2017), "Deep reinforcement learning from human preferences". Problem: many tasks have goals that are easy to recognise and hard to write as a reward function, and asking a human to score every state is far too expensive. Mechanism: a reward predictor is trained from human comparisons of pairs of short trajectory segments, and a policy is trained by RL against the predictor while the predictor keeps learning from new comparisons. Collection: non-expert contractors received a one- or two-sentence description of each task and watched two clips side by side; segments were one to two seconds long (1.5 s in MuJoCo, 25 timesteps at 15 fps in Atari). The interface was four keys: left, right, equal, and "can't tell"; incomparable pairs were dropped. Contractors answered an average query in 3–5 seconds. The reward predictor was an ensemble (three predictors by default) trained with a softmax preference model that assumes a 10% chance the human answered at random, and queries were chosen where the ensemble disagreed most, an early form of active selection (Christiano et al. 2017). Result: human feedback covered under 1% of the agent's interactions; MuJoCo runs used 700 human queries, the Atari human run 5,500; a Hopper backflip was learned from 900 queries in under an hour. With 700 synthetic labels the method nearly matched RL on the true reward in MuJoCo. Atari was harder: human feedback was similar to or slightly worse than synthetic feedback on most games, and on Qbert it failed to clear the first level. Left open: whether the recipe works for language, where a "clip" is a paragraph that takes minutes to read; how rater error and rater disagreement affect the reward; and what happens when the policy finds outputs the predictor scores highly but humans dislike. Picked up by: Ziegler et al. (2019) moved the method to language-model fine-tuning; Stiennon et al. (2020) scaled it.
The W1 interface is the same four-way choice in a different medium: two coding responses side by side, a preference, an allowed tie (used on 8% of W1 items), and a skip. The cost of reading changes everything downstream: a 2017 query took 3–5 s, a W1 comparison has a median of 4.0 min. That factor of roughly 60 is why W1 pre-generates a buffer of 2,000 pairs and why active selection of which pairs to show matters more for text than it did for clips.
Stiennon et al. (2020), "Learning to summarize from human feedback". Problem: ROUGE and supervised fine-tuning on reference summaries optimise a proxy for quality; the authors wanted to optimise human judgment of summaries directly. Collection: a filtered Reddit TL;DR set of 123,169 posts; labelers compared two summaries and gave a confidence on a 9-point scale; separate quality axes used a 7-point Likert scale. Labelers were sourced through Upwork, Scale and Lionbridge, completed paid training, were retained on speed and agreement with researchers, and were paid hourly regardless of how many comparisons they completed, a deliberate choice against per-item piecework. The released set has 64,832 comparisons, and the paper describes data collection as taking thousands of labeler hours. A voluntary survey of 21 labelers found 45% American and 30% Filipino (Stiennon et al. 2020). Quality control: continuous comparison against researcher labels. Labeler–researcher agreement was 77% ±2% on one subset, against 73% ±4% researcher–researcher; labeler–labeler agreement was 72%, rising to 77% agreement with researchers when the modal label of three labelers was used. Result: the 1.3B human-feedback policy was preferred over the human reference summaries 61% of the time, against 43% for a supervised model ten times larger; the 6.7B policy was preferred about 65% of the time after controlling for length. The reward model transferred to CNN/DM without news-specific training. Doubling data raised reward-model accuracy by about 1.1 points; doubling model size by about 1.8. Left open: over-optimising the reward model eventually made it anti-correlated with human preferences; the reward model preferred longer summaries than humans did; two-thirds of the data concerned relationships, which limited generality. Picked up by: InstructGPT, which kept the labeler screening, hourly pay and agreement measurement and generalised the task from summaries to arbitrary instructions; and the reward-over-optimisation literature.
Ouyang et al. (2022), InstructGPT: "Training language models to follow instructions with human feedback". Problem: large pretrained models do not follow user intent; the question was whether the 2020 recipe could align a general model across the distribution of real API prompts. Collection: about 40 contractors sourced through Upwork and Scale AI. Selection used four screens: agreement with researchers on flagging sensitive content, agreement on rankings, a scored set of demonstrations for sensitive prompts, and a self-assessment of the topics and cultural groups for which the labeler could identify sensitive speech. Soft cutoffs were 75% agreement on the first two and 6/7 on the demonstration score (Ouyang et al. 2022, appendix B). Three datasets were built: about 13k prompts with labeler-written demonstrations for supervised fine-tuning (SFT), 33k prompts for reward modelling on which labelers ranked between K = 4 and K = 9 responses, and 31k prompts for PPO with no human labels. Ranking K responses yields up to K(K−1)/2 comparisons per prompt from one reading, which is the economic reason for the ranking interface. The published instructions tell labelers that for most tasks being harmless and truthful matters more than being helpful. Quality control: training labelers agreed with each other 72.6 ± 1.5% of the time; held-out labelers, who never trained the model, 77.3 ± 1.3%. The reward model reached 72.4% accuracy on training labelers and 69.6% on held-out labelers, the first published check that a reward model generalises to raters who did not produce its training data. Result: 1.3B InstructGPT outputs were preferred to 175B GPT-3 outputs; 175B InstructGPT was preferred to 175B GPT-3 85 ± 3% of the time; hallucination on closed-domain tasks fell from 41% to 21%. Mixing pretraining gradients into PPO (PPO-ptx) reduced regressions on public NLP benchmarks, the "alignment tax". Left open: the authors state that the preferences encoded are those of a small contractor pool and the research team, not broad human values, and that API customers are not representative users. Picked up by: essentially every later chat-model pipeline; directly, Anthropic's HH work and Llama 2.
Bai et al. (2022a), "Training a Helpful and Harmless Assistant with RLHF" (HH-RLHF), with Ganguli et al. (2022) on red teaming. Problem: train a dialogue assistant that is both helpful and harmless, and learn how the two objectives interact. Collection: crowdworkers held open-ended multi-turn conversations with the model; at each turn they saw two responses and chose the more helpful and honest one (helpfulness task) or the more harmful one (red-team task). They could express preference strength, but only comparisons above the weakest strength were kept and all kept comparisons were treated as equal-weight binary labels. About 80% of the data came from US-based "master-qualified" Amazon Mechanical Turk workers and the rest from Upwork; about 20 of the most prolific MTurk workers produced roughly 80% of the data, and workers were not filtered by agreement. Three datasets were collected: a base set from a context-distilled 52B model (44k helpfulness, 42k red-team comparisons), a rejection-sampling set (52k helpfulness, 2k red-team; usually best-of-16), and an "online" set of 22k helpfulness comparisons collected over about five weeks with roughly weekly model and preference-model updates (Bai et al. 2022a). Quality control: agreement between researchers and crowdworkers was about 63% on roughly 320 test samples, which the authors note is lower than in comparable earlier work; they report that workers often preferred responses containing non-functional URLs because they did not fact-check. Result: preference models trained on one objective performed much worse than chance on the other; mixed training handled both, and larger models were more robust to the mix ratio. During much of RL training, reward was roughly linear in the square root of the KL divergence from the initial policy. Crowdworkers preferred the online model to human-written responses about 57% of the time. The red-team design, in which workers try to elicit harm and then pick the more harmful reply, pushed conversations toward harm and produced policies that over-refused. The companion red-teaming study released 38,961 red-team attacks across 2.7B, 13B and 52B models and four model types (Ganguli et al. 2022). Left open: the helpfulness–harmlessness tension; evasive refusals; low expert agreement on open-ended chat; dependence on a small number of prolific workers. Picked up by: Constitutional AI, which replaced the human harmlessness labels; Llama 2, which kept separate helpfulness and safety labels and weekly on-policy batches; and the public HH-RLHF release became one of the most-used open preference sets.
The HH finding that a few prolific workers produced most of the data is an operational risk W1 inherits. With 150 vendor raters at 20 h/week, the workload sheet implicitly assumes roughly uniform throughput; if the top 20 raters instead produced 80% of the 24,000 labels, any systematic bias in those 20 would dominate the reward model. A routing cap of, say, 3% of a campaign's labels per rater (about 720 labels in W1) bounds that influence; this cap is an illustrative design choice for W1, not a published number.
Touvron et al. (2023), Llama 2: data practices. Problem: produce an open chat model competitive with closed ones, and document the human-data pipeline at industrial scale. Collection, SFT: the team stopped at 27,540 supervised fine-tuning annotations under the heading "Quality Is All You Need", reporting that tens of thousands of high-quality examples were enough, that the choice of annotation vendor and platform noticeably changed downstream quality, and that SFT model outputs were often competitive with hand-written data in a manual comparison of 180 examples. Collection, preferences: annotators wrote a prompt and chose between two responses sampled from different model variants and temperatures, rating the strength on four levels (significantly better, better, slightly better, negligibly better/unsure). Helpfulness and safety were labelled separately under different guidelines; safety labels also recorded whether each response was safe (18% of pairs had one safe and one unsafe response, 47% both safe, 35% both unsafe), and pairs where the chosen response was unsafe and the other safe were excluded. Data was collected in weekly batches from the latest model so the reward model stayed on-distribution, with 1,000 examples held out per batch. The total was 1,418,091 comparisons averaging 798.5 tokens and 3.9 turns, against 122,387 for Anthropic Helpful and 176,625 for OpenAI Summarize in the same table (Touvron et al. 2023). The preference strength was used as a margin in the ranking loss, so clearly different pairs pushed the reward model harder. Red teaming: over 350 people, including domain experts in cybersecurity, election fraud, misinformation, law, policy, civil rights and creative writing; violating prompts found per person-hour on the 7B model fell from 1.8 to 0.45 across red-team iterations. Result and quality: the helpfulness reward model reached 63.2% on Meta Helpfulness test data against 58.6% for zero-shot GPT-4; accuracy was higher on clearly different pairs. In the human evaluation of model outputs (not the reward-model data), three raters scored each comparison and inter-rater reliability (Gwet's AC2) ranged from 0.37 to 0.55 on helpfulness, lower when the models were close; on the safety evaluation of about 2,000 adversarial prompts it averaged 0.92. Five RLHF iterations (V1–V5) used rejection sampling, then PPO on top. Left open: no cost or vendor figures; reward-model accuracy in the low 60s on hard pairs; the relationship between collection volume and model quality was not ablated publicly. Picked up by: open post-training recipes that adopted separate helpfulness and safety reward models and margin losses, and the HelpSteer line, which argued for far less but better-controlled data.
Wang et al. (2023, 2024), HelpSteer and HelpSteer2. Problem: open preference data was either large and noisy, or generated by proprietary models with restrictive terms; NVIDIA asked how little permissively licensed human data could train a top reward model. Collection: rather than a single preference, annotators rated each response on five attributes (helpfulness, correctness, coherence, complexity, verbosity) on a 0–4 Likert scale, so a pairwise preference can be derived while the attributes stay available as separate signals. HelpSteer had about 37k samples and trained a Llama 2 70B SteerLM model scoring 7.54 on MT-Bench (Wang et al. 2023). HelpSteer2 has 10,681 prompts with two responses each (21,362 rated samples), annotated through Scale AI by about 1,000 US-based annotators (Wang et al. 2024). Quality control: this is the most completely documented QC pipeline in the lineage and a template for platform design. Three annotators rated each sample initially; two more were added when helpfulness ratings disagreed by more than 2 points (3.41 annotators per sample on average), and only the three most-agreeing were kept. Each annotation had at least two human reviews plus automated checks; untrusted or persistently low-agreement annotators were removed; samples whose helpfulness ratings still differed by more than 2 points (about 10%) were excluded. About half of all annotations were discarded. Quadratic-weighted Cohen's κ on helpfulness rose from 0.465 initially to 0.706 after guideline and process changes and 0.791 after post-processing. Result: a Nemotron-4 340B reward model trained on HelpSteer2 scored 92.0% on RewardBench's primary set, and a Llama 3 70B reward model 88.8%. The authors note that the set is an order of magnitude smaller than HH-RLHF. Released under CC-BY-4.0. Left open: a single US annotator pool; Likert scales whose meaning drifts between annotators; whether a 10k-pair set suffices outside general chat. Picked up by: later multi-attribute and preference-plus-rationale datasets and reward models trained on them; for this book, the HelpSteer2 QC loop is the reference design for Chapter 6.
HelpSteer2 discarded about 50% of annotations to reach κ ≈ 0.79. W1 assumes an 8% QA rejection rate, giving about 18,400 useful comparisons from 24,000 labels at about $4.12 each. If W1 applied a HelpSteer2-style "add raters on disagreement, keep the most-agreeing three" rule to its 2,000 overlap items, the useful yield would fall and cost per useful comparison would rise; at a 50% discard rate the same $75,780 of labour would buy about 10,000 useful comparisons out of 20,000, about $7.58 each. Which choice is right depends on the reward model's sensitivity to label noise, which Chapter 8 shows how to measure.
Chiang et al. (2024), Chatbot Arena. Problem: static benchmarks saturate and do not reflect open-ended use; human preference at scale was the missing evaluation signal. Collection: any visitor submits a prompt, two anonymous models answer side by side, and the visitor votes for one, a tie, or "both are bad"; identities are revealed only after the vote. As of January 2024 the platform had over 240,000 votes (243,329 conversations) from about 90,000 users, covering more than 50 models and over 100 languages (77% English). Statistics: model strength is a Bradley–Terry coefficient estimated by reweighted maximum likelihood, with sandwich robust standard errors; an active-sampling rule picks model pairs whose confidence intervals would shrink most and, in a simulation driven by Bradley–Terry coefficients fitted to 213,576 held-out votes, needed about 35% fewer votes than random sampling to reach one precision target (4,400 against 6,800), with the advantage shrinking to about 5% at a looser target. Quality control: crowd votes agreed with expert labels about 72–83% of the time, against 79–90% expert–expert; an anomalous-user detector combining per-vote p-values with Fisher's method reached about 90% true-positive and 60–70% true-negative rates on a small test set of 50 users (Chiang et al. 2024). Left open: the user base skews toward enthusiasts, prompts are not production prompts, and safety is not evaluated. A 2025 audit argued that undisclosed private testing (27 private variants tested by one lab before a release) and unequal data access (an estimated 19.2% and 20.4% of all Arena data to two providers, against 29.7% for 83 open-weight models combined) let providers overfit the leaderboard, with relative gains of up to 112% on the Arena distribution from limited additional Arena data (Singh et al. 2025). Picked up by: every lab that reports arena scores; for platform builders, the vote interface, the Bradley–Terry aggregation and the anomaly detector are reusable components, and the audit is a reminder that who controls sampling controls the result.
Rafailov et al. (2023), Direct Preference Optimization (DPO), as a consumer of preference data. Problem: RLHF with a separate reward model and PPO is complex and unstable. Mechanism: DPO reparameterises the reward so that the KL-regularised optimal policy has a closed form, which turns preference learning into a classification loss on (prompt, chosen, rejected) triples with no reward model and no sampling during training (Rafailov et al. 2023). Why it matters for data: DPO does not change how labels are collected, but it changes what a label is used for and how stale it may be. A reward model can score fresh on-policy samples; offline DPO learns only from the pairs it was given, so the distribution of those pairs (which checkpoint produced them, how different the two responses are) directly shapes the update. It also made large AI-labelled sets such as UltraFeedback (next section) immediately usable by anyone with a fine-tuning stack. Left open: how much of RLHF's benefit depends on on-policy data, which offline pairs lack. Picked up by: a large family of offline and iterative preference-optimisation methods; for platform design, the practical consequence is that the export format must carry the generating checkpoint and the pair construction method so that consumers can choose on- or off-policy subsets (Chapter 7).
| Work | Who labelled | Interface / format | Volume | Quality control reported |
|---|---|---|---|---|
| Christiano 2017 | Non-expert contractors; authors for some tasks | Two 1–2 s clips; left / right / equal / can't tell | 700 (MuJoCo), 5,500 (Atari) queries | Ensemble; 10% random-response noise model |
| Stiennon 2020 | Upwork, Scale, Lionbridge; hourly pay | Pair + 9-point confidence; 7-point quality axes | 64,832 comparisons | Retention on researcher agreement (77% ±2%) |
| Ouyang 2022 | ~40 screened contractors (Upwork, Scale AI) | Rank K = 4–9 responses; demonstrations | 13k SFT, 33k RM prompts | 4-part screen; held-out labelers 77.3% |
| Bai 2022a | MTurk (~80%) and Upwork crowdworkers | Multi-turn chat; pick better (or more harmful) of two | ~162k comparisons | No agreement filter; researcher–crowd ~63% |
| Touvron 2023 | Vendors (unnamed) | Pair + 4-level strength; helpfulness and safety separate | 1,418,091 comparisons; 27,540 SFT | Weekly batches; held-out 1,000 per batch |
| Wang 2024 (HelpSteer2) | ~1,000 US annotators via Scale AI | 5 attributes × 0–4 Likert per response | 10,681 pairs | 3–5 raters; ~50% discarded; κ 0.465 → 0.791 |
| Chiang 2024 (Arena) | Anonymous public users | Own prompt; A / B / tie / both bad | 243,329 votes (Jan 2024) | Anomaly detection; crowd–expert 72–83% |
Table. Human preference protocols in the RLHF thread, from the cited papers. Bai 2022a total is the sum of the three helpfulness sets and two red-team sets listed in the paper.
AI feedback and constitutions: Constitutional AI / RLAIF, UltraFeedback, judges, rubric-based rewards
Once a reward model could be trained from comparisons, the obvious question was whether a model could produce the comparisons. The answer that emerged between 2022 and 2026 is "for some judgments, if humans write down what to judge". The thread moves the human contribution upstream: from labelling each pair, to writing a short constitution, to writing a rubric for each prompt, and finally to verifying that a model applies the rubric correctly. Each step reduced labelling cost per item and increased the importance of a small amount of carefully written and carefully checked human text.
Bai et al. (2022b), "Constitutional AI: Harmlessness from AI Feedback". Problem: HH-RLHF needed tens of thousands of human red-team comparisons, produced evasive models, and exposed crowdworkers to harmful content. Mechanism: two phases. In the supervised phase, the model answers red-team prompts, critiques its own answer against a randomly sampled principle, revises it, and is fine-tuned on the revisions. In the RL phase, the fine-tuned model produces pairs of responses, a feedback model is asked as a multiple-choice question which response better satisfies a sampled principle, and the normalised log-probabilities become soft preference labels; a preference model is trained on these AI labels and the policy is trained against it (RL from AI Feedback, RLAIF). The chain-of-thought variant clamps label probabilities to 40–60% to avoid overconfident targets. Collection: no human harmlessness labels. The constitution had 16 harmlessness principles. Human input was the principles, about 135,296 human helpfulness comparisons, and 42,496 human-written red-team prompts, extended with 140,335 model-generated prompts for the supervised phase and 491,142 more for RL (Bai et al. 2022b). Result: RL-CAI models were more harmless than RLHF models at a given helpfulness and were "virtually never evasive". Left open: the authors note that the principles were chosen ad hoc and would need broader input; that over-trained models Goodharted into harsh or boilerplate replies; that critiques were sometimes wrong; and that helpfulness still required human labels. Picked up by: RLAIF studies (below), self-critique and self-rewarding methods, and the general practice of writing guidelines as text that both humans and models can apply.
Lee et al. (2023), "RLAIF vs. RLHF". Problem: CAI used AI labels for harmlessness only; does AI feedback match human feedback on ordinary tasks? Mechanism: PaLM 2 models label summarisation and dialogue preferences; chain-of-thought prompting and averaging over both response orders reduce position bias. A "direct" variant (d-RLAIF) skips the reward model and asks the labeller for a score during RL. Result: human raters preferred RLAIF over the SFT baseline 71% (summarisation) and 63% (helpful dialogue) of the time, against 73% and 64% for RLHF; head-to-head, RLAIF and RLHF were preferred about equally (50% and 52%). On harmless dialogue the harmless rate was 64% for SFT, 76% for RLHF and 88% for RLAIF. The best AI labeller agreed with human preferences 78.0% of the time on summarisation, where human inter-annotator agreement was estimated at 73–77%; a small labeller (PaLM 2 XS) reached only 62.7% and preferred the same position after swapping 56% of the time. The authors estimate AI labelling at about $0.06 per example against about $0.67 for human labelling (Lee et al. 2023). Left open: tasks where the AI labeller is systematically wrong, and whether AI labels transfer to domains the labeller model is weak in. Picked up by: the routing designs of Chapter 9, which send items to AI first and humans where AI is unreliable.
Zheng et al. (2023), LLM-as-a-judge (MT-Bench and Chatbot Arena). Problem: evaluate open-ended chat without a human per comparison. Result: GPT-4 as a judge reached over 80% agreement with human preferences, which the authors report as the same level as agreement between humans; the paper names position, verbosity and self-enhancement biases and releases 3,000 expert votes and 30,000 conversations with human preferences (Zheng et al. 2023). Left open: the named biases, and the fact that agreement with average preferences does not guarantee correctness on expert content. Picked up by: almost every later AI-feedback dataset, which uses a strong model as the labeller.
Cui et al. (2023), UltraFeedback. Problem: open preference data was small or narrow; human labelling at the needed scale was too expensive for academic groups. Collection: 63,967 instructions from six public sources (including ShareGPT, FLAN, Evol-Instruct, UltraChat, TruthfulQA and FalseQA); for each, four responses from models sampled out of a pool of 17, giving 255,864 completions. GPT-4 rated every completion on four aspects (instruction following, truthfulness, honesty, helpfulness) on a 1–5 scale using written scoring documentation, wrote a rationale for each score, and saw all four completions at once to keep ratings consistent; it also wrote textual critiques, for over a million feedback items in total. Quality control: GPT-4 agreed with individual human annotators 59.7% of the time and with the majority of three annotators 68.6% (against 33% by chance, as the authors report) (Cui et al. 2023). Result: a 13B reward model (UltraRM) averaged 71.0% across four public preference benchmarks; PPO with UltraRM raised UltraLM-13B's average win rate from 52.9% to 69.7% (16.8 points) while moving nine capability benchmarks by only about one point. Left open: labels inherit GPT-4's biases and errors; rating four completions together introduces dependence between items; the licence position of model-generated labels. Picked up by: many open DPO-trained models used UltraFeedback-derived pairs (this chapter's inference from widespread public use; the paper itself predates them); and the design of decomposed, documented scoring that rubric methods made per-prompt.
Arora et al. (2025), HealthBench: physician-written rubrics. Problem: evaluate health conversations where correctness depends on context and no single reference answer exists. Collection: 262 physicians wrote conversation-specific rubrics for 5,000 multi-turn conversations, yielding 48,562 unique criteria covering accuracy, instruction following and communication; a model grader checks each criterion (Arora et al. 2025). Why it matters: it established, at scale and in public, the pattern in which experts write the criteria once and a model applies them many times. The expert's work product is no longer a label on a response but a reusable grading specification for a prompt. Left open: how faithfully a model grader applies criteria, and how rubric quality is itself checked. Picked up by: rubric-based RL rewards.
Gunjal et al. (2025), "Rubrics as Rewards" (RaR). Problem: RL with verifiable rewards works for maths and code but not for domains such as medicine where answers cannot be checked by a program; Likert-scale judge rewards are coarse. Mechanism: each prompt gets 7–20 self-contained rubric items (about 7.5 on average) labelled Essential, Important, Optional or Pitfall. In the explicit variant, a judge (gpt-4o-mini) marks each item satisfied or not and the reward is the weighted average \( r = \sum_j w_j c_j / \sum_j w_j \) with weights 1.0, 0.7, 0.3 and 0.9 for the four categories; in the implicit variant the judge sees all items and returns one 1–10 score. A Qwen2.5-7B policy is trained with GRPO. Collection: rubrics were written by GPT-4o (medicine) and o3-mini (science), conditioned on the datasets' reference answers; about 20k prompts per domain were released. Result: up to 31% relative improvement on HealthBench and 7% on GPQA-Diamond over Likert judge rewards. Policies trained on human-written rubrics scored 34.8% on HealthBench-1k against 35.9% for reference-grounded synthetic rubrics, but synthetic rubrics written without reference answers fell to 32.0%, which the authors read as evidence that human-grounded guidance matters (Gunjal et al. 2025; published at ICLR 2026). Left open: only medicine and science; dialogue, tool use and agentic tasks untested; fixed weights; pitfall items hard to generate. Picked up by: checklist rewards and rubric verification work.
Viswanathan et al. (2025), "Checklists Are Better Than Reward Models" (RLCF). Mechanism: extract a checklist from each instruction, score each item with an AI judge or, where possible, a verifier program, and combine item scores into the RL reward. Result: on Qwen2.5-7B-Instruct, the only method in their comparison to improve all five benchmarks, including +4 points hard satisfaction on FollowBench, +6 on InFoBench and +3 win rate on Arena-Hard (Viswanathan et al. 2025). Relevance: mixing program verifiers with judged items per rubric is exactly the hybrid a platform must support in its rubric schema.
Huang et al. (2025), "Reinforcement Learning with Rubric Anchors". Problem: extend RL with verifiable rewards to open-ended tasks by using rubrics as the reward anchor. Collection: over 10,000 rubrics, written by humans, by LLMs, or by human–LLM collaboration (the abstract does not give the split). Result: a Qwen-30B-A3B model trained on just over 5,000 samples gained 5.2% on open-ended benchmarks, especially in the humanities, and outperformed the 671B DeepSeek-V3 by 2.4%, while preserving general and reasoning abilities (Huang et al. 2025). Left open: which rubric source (human, model or hybrid) contributes what; the abstract reports the system, not an ablation by author. Relevance: at ten thousand rubrics the rubric bank is itself a dataset that needs versioning, provenance (who wrote each rubric) and quality review, which is the W3 schema problem at scale.
Wang et al. (2025), ProfBench. Problem: rubric benchmarks had concentrated on domains where answers are short or checkable; professional documents need professional judges. Collection: over 7,000 response–criterion pairs evaluated by human experts with professional knowledge in four areas: physics PhD, chemistry PhD, finance MBA and consulting MBA. Result: the best model evaluated, GPT-5-high, reached 65.9% overall; the authors' LLM judges reduced evaluation cost by two to three orders of magnitude while mitigating self-enhancement bias (Wang et al. 2025). Relevance: the expert labels are the calibration set; the cheap judge is what makes the rubric usable as a reward. The pattern is exactly W3's split between expensive expert grading for calibration and AI grading at RL scale.
Xu et al. (2026), Rubric-ARM: "Alternating Reinforcement Learning for Rubric-Based Reward Modeling in Non-Verifiable LLM Post-Training". Mechanism: instead of fixed rubrics, a rubric generator and a judge are trained jointly with RL from preference feedback; rubric generation is treated as a latent action optimised for judgment accuracy, and the two components are updated alternately to reduce gradient variance. Result: the abstract reports state-of-the-art results among the baselines on several benchmarks and improved downstream policy alignment in offline and online RL, without headline numbers (Xu et al. 2026). Relevance: when rubrics are generated rather than written, the human contribution moves to the preference data the generator is trained against and to audits of the rubrics it emits.
Mehta et al. (2026), "ComplexConstraints and Beyond: Expert Rubrics for RLVR". Problem: which rubric-design choices make expert rubrics work both as a measurement and as an RL reward. Collection: expert-authored rubrics with 10–40 atomic criteria per prompt; a public benchmark of 75 prompts and 1,559 criteria, plus a disjoint training set of 1,000 prompts; a second setting covers enterprise agentic tasks (CoreCraft). The paper examines atomicity of criteria, intent-aware criterion design and LLM-judge calibration. Result: a 4B model trained on ComplexConstraints gained 15.5 points in mean criterion pass rate on a held-out split, ending within 0.5 points of an untrained Qwen3 model about 60 times larger, and transferred to AdvancedIF (+8.4) and MultiChallenge (+10.1); RL on CoreCraft transferred to BFCL (+4.5), τ²-Bench (+7.4) and Toolathlon (+6.8) (Mehta et al. 2026). Left open: the abstract gives no head-to-head of expert-written against model-written rubrics. Relevance: it is one of the few public results in which expert rubrics are both the training reward and the evaluation, including for agentic tasks, and its design variables (criterion atomicity, judge calibration) are fields a rubric schema must record.
Peng et al. (2026), RuVerBench: "Can LLM-as-a-Judge Reliably Verify Rubrics in Agentic Scenarios?" Problem: rubric rewards assume the judge applies each item correctly; agent outputs (deep-research reports, code changes) are long and the assumption had not been tested. Collection: 2,458 instances in deep research and agentic coding, each a model output, a rubric item and a human label of whether the output satisfies the item. Result: the strongest judges perform well but still show substantial noise; weaker judges are more sensitive to prompt wording; majority voting helps with diminishing returns; batching several items into one judge call trades accuracy for cost (Peng et al. 2026; accepted to EMNLP 2026 per the arXiv listing). Left open: the abstract does not report annotator agreement, so the human ceiling for this task is not stated there. Relevance: the human labels in such a benchmark are the calibration set every rubric-reward pipeline needs; producing them is a human-data campaign in its own right.
Hong et al. (2026), "Can LLMs Write Reliable Rubrics? A Meta-Evaluation for Experiment Reproduction". Problem: expert-written rubrics, such as the author-co-developed rubrics of PaperBench, are expensive; can models write them? Method: four rubric-generation settings across two backbone models, judged intrinsically (semantic similarity to expert rubrics) and extrinsically (agreement of the resulting scores with scores from the ground-truth rubrics). Result: augmented settings improved alignment and the best came close to the human baseline, but intrinsic gains were smaller, and model-written rubrics were overly fine-grained, skewed toward high scores and adapted poorly across paper domains (Hong et al. 2026). Relevance: a rubric that scores everything high carries little gradient (see Chapter 1's debugging note on rubric rewards clustering near 1.0); a platform that accepts model-drafted rubrics should track the score distribution per rubric author type and keep expert review in the loop. A 2026 survey organises this whole line, rubrics for evaluation, as training rewards and as intrinsic guidance, and reviews their reliability and security threats (Chen et al. 2026).
W3 sits exactly on this line. Experts write rubrics of 8–12 items (mean 10) for 3,000 legal-drafting prompts at about 25 min each (1,250 expert-hours), and graders score 4 responses per prompt against the rubric (about 400 hours). Those 12,000 human-scored responses carry roughly 120,000 item-level judgments, which become the calibration set for the AI grader that will produce the RL reward; W3 targets item-level human–AI agreement of at least 0.8. RaR's 34.8% versus 32.0% contrast is the published argument for paying for expert grounding rather than generating rubrics without references; RuVerBench's finding about batching is the argument for measuring item-level agreement separately for batched and per-item grading before choosing one.
Process supervision and agentic feedback: PRM800K / Let's Verify Step by Step, process labels for agents, transcript-level critique
An outcome label says whether the final answer is right. A process label says which steps were right. For a 60-step agent transcript the difference is the difference between "this run failed" and "this run went wrong at step 23, for this reason, and should have done this instead". The thread shows process labels proving their value in maths, then being produced automatically, then being reduced to the cheaper "first error" form, and finally being applied to agent trajectories, where automated attribution is still weak and expert review remains the reference.
Uesato et al. (2022), "Solving math word problems with process- and outcome-based feedback". Problem: compare supervising final answers with supervising reasoning steps on GSM8K. Result: outcome supervision and process supervision gave similar final-answer error rates, but reasoning errors among correct-answer solutions differed; the best combination reduced final-answer error from 16.8% to 12.7% and reasoning error among correct answers from 14.0% to 3.4% (Uesato et al. 2022). Left open: whether process supervision helps final accuracy on harder problems, and whether human step labels are worth their cost. Picked up by: Lightman et al. (2023).
Lightman et al. (2023), "Let's Verify Step by Step" (PRM800K). Problem: on the harder MATH dataset, does a process reward model (PRM) trained on human step labels beat an outcome reward model (ORM) for selecting among many sampled solutions? Collection: labelers judged each step of model-generated solutions as positive (correct and reasonable), negative (incorrect or unreasonable) or neutral (ambiguous). Candidates were screened on 30 quality-control questions with a 75% agreement threshold against gold labels, and 10–20 quality-control problems were included in each generation of data. A first phase produced about 5% of the data; the second phase, collected over 10 generations, used active learning: show labelers "convincing" wrong-answer solutions, those the current PRM rated highly but whose final answer was wrong. In a small-scale ablation this was estimated to be about 2.6 times as data-efficient as uniform selection. The filtered training set is about 800,000 step labels on 75,000 solutions to 12,000 problems; the unfiltered release has 1,085,590 step labels on 101,599 solutions (Lightman et al. 2023). Result: selecting the best of 1,860 samples on a 500-problem MATH test subset, the PRM solved 78.2%, the ORM 72.4% and majority voting 69.6%; on out-of-distribution STEM questions at best-of-100, 72.9%, 63.8% and 61.3%. Left open: the authors flag possible test-set contamination, unclear generalisation beyond maths, a training set skewed toward wrong-answer solutions by active learning, and unexplained instability when retraining iteratively; the generator was fixed rather than trained with RL. Picked up by: automatic process labelling (Math-Shepherd), process benchmarks (ProcessBench) and agent PRMs.
PRM800K's active-learning rule transfers directly to W2. With 600 expert-hours a week and 35 min per transcript, W2 can review about 1,030 transcripts per week. Sampling transcripts that an automated judge marked as successful but whose outcome check failed (the agent equivalent of "convincing wrong answers") concentrates expert time on the errors the reward signal currently misses. If the 2.6× efficiency estimate held for agents, which is untested, the 2,000-transcript budget would carry information comparable to a much larger uniform sample; the platform should log selection scores so that this can be measured rather than assumed.
Wang et al. (2023), Math-Shepherd: process labels without humans. Mechanism: for each intermediate step, a "completer" model generates N continuations; under hard estimation the step is labelled good if any continuation reaches the known answer, under soft estimation the label is the fraction that do. The main setup used LLemma-7B with N = 8. On 160 manually labelled GSM8K steps, one completer configuration reached about 86% agreement with human labels at N = 4. Result: step-by-step PPO raised Mistral-7B from 77.9% to 84.1% on GSM8K and from 28.6% to 33.0% on MATH; with verification, 89.1% and 43.5%. The authors report their automatic data outperformed PRM800K on MATH and attribute this partly to distribution mismatch (PRM800K solutions came from a different generator) and to having about four times as much data (Wang et al. 2023). Left open: the labels are noisy and the effect of the noise is acknowledged as undetermined. Relevance: human step labels compete with Monte Carlo labels on cost; they win where final answers cannot be checked automatically, which is the agentic and non-verifiable case.
Zheng et al. (2024), ProcessBench. Mechanism: 3,400 competition- and Olympiad-level solutions in which human experts marked the earliest erroneous step (or that all steps are correct); models must identify that step. Result: existing PRMs often failed on problems harder than GSM8K and MATH, scoring below general models prompted as critics and below a PRM the authors trained on PRM800K (Zheng et al. 2024). Relevance: "first error" is a cheaper label than per-step labels and is the format W2 uses; the benchmark shows the expert label remains the reference.
Choudhury (2025), AgentPRM. Mechanism: process reward models for LLM agents trained with Monte Carlo rollouts as targets in an actor-critic loop, plus InversePRM, which learns process rewards from demonstrations without outcome supervision. Result: 3B models trained this way outperformed GPT-4o baselines on ALFWorld; the paper also discusses test-time scaling and reward hacking (Choudhury 2025). Relevance: InversePRM makes expert demonstrations (corrected continuations) a direct source of process reward, which is a reason to store W2's corrected continuations as structured training data rather than free text.
Zhang et al. (2025), "Which Agent Causes Task Failures and When?" (Who&When). Problem: attribute failures in multi-agent systems to an agent and a step automatically. Collection: failure logs from 127 LLM multi-agent systems with annotated responsible agent and decisive step. Result: the best automated method identified the responsible agent 53.5% of the time and the failure step only 14.2% (Zhang et al. 2025). Relevance: step-level attribution in agent logs is far from automatable, which is why expert transcript review is a distinct campaign type.
Lù et al. (2025), AgentRewardBench. Collection: 1,302 web-agent trajectories from four agents across five benchmarks, each reviewed by an expert, used to evaluate 12 LLM judges (Lù et al. 2025). Rule-based success checks in the benchmarks were also compared against the expert labels and under-reported success. Relevance: expert trajectory labels serve as the ground truth for both rule-based and judge-based agent rewards, the same role RuVerBench's labels play for rubric judges.
Deshpande et al. (2025), TRAIL: "Trace Reasoning and Agentic Issue Localization". Collection: a formal taxonomy of agentic error types and 148 human-annotated traces from single- and multi-agent systems, focused on software engineering and open-world information retrieval. Result: the best model tested, Gemini-2.5-pro, scored 11% on locating and classifying the errors (Deshpande et al. 2025). Relevance: like Who&When, it shows how far models are from reading a long trace the way an expert does, and it is a public example of the failure taxonomy that a W2-style review form needs.
Fan et al. (2026), AgentProcessBench. Problem: process benchmarks covered maths; tool-using agents had no human step-level reference. Collection: 1,000 tool-augmented trajectories with 8,509 human-labelled steps, using a ternary scheme that leaves room for exploration (a step can be neither right nor wrong) and an error-propagation rule that reduces ambiguity about steps after a mistake; inter-annotator agreement was 89.1% (Fan et al. 2026). Result: weaker policies show inflated shares of correct steps because they stop early; current models struggle to separate neutral actions from errors; process-level signals add value beyond outcome supervision and substantially improve test-time scaling. Relevance: the closest public analogue of W2's per-step labels, with two protocol choices (a neutral class for exploration, an explicit propagation rule) that a transcript-review guideline should copy, and an agreement figure that shows what a well-specified step-labelling protocol can reach.
Wang et al. (2026), Plan-RewardBench. A trajectory-level preference benchmark for tool-using agents across four task families (safety refusal, tool irrelevance or unavailability, complex planning, robust error recovery), built from natural rollouts and rule-based or minimal-edit perturbations that create hard negatives. Generative, discriminative and LLM-as-judge evaluators all struggled, and accuracy dropped sharply on long trajectories (Wang et al. 2026). Relevance: automated trajectory rewards are weakest exactly where W2's 60-step transcripts sit, which is where expert labels are worth their cost.
In W2, two experts marking the first failing step on the 10% double-reviewed subset agree exactly 58% of the time and within ±2 steps 81% of the time. Against the published 14.2% step-attribution accuracy of the best automated method on Who&When (a different task and dataset, so only an order-of-magnitude comparison), the expert labels are the only signal precise enough to train or audit a step-level reward. The ±2-step tolerance is a platform decision: the export should carry both the exact step and the tolerance band so that consumers can choose.
| Label granularity | Representative work | Who produces it | Cost driver | Platform requirement |
|---|---|---|---|---|
| Outcome | Uesato 2022 (ORM) | Program checker or rater | Reading the final answer | One label per sample |
| Per-step (+ / − / neutral) | PRM800K; AgentProcessBench (agents) | Screened labelers or annotators | Reading every step | Step segmentation; per-step widgets |
| Per-step, automatic | Math-Shepherd | Completer rollouts | Compute: N rollouts per step | Access to a checker for the final answer |
| First error | ProcessBench; Who&When | Experts | Reading up to the first error | Jump-to-step; step anchors in exports |
| Critique + corrected continuation | Transcript review (W2 pattern); InversePRM uses demonstrations | Domain experts | Reading plus writing ~400 words | State replay; continuation editor; failure taxonomy |
Table. Process-label formats and what each demands of the platform. The last column is this book's synthesis.
Annotation science: Dawid–Skene, agreement metrics, crowdsourcing quality, LLM-assisted cheating detection, annotator disagreement as signal
The RLHF papers measure quality mostly as raw pairwise agreement with researchers. The annotation-science literature, much older, supplies the models behind that practice: how to estimate each annotator's error rates without ground truth, how to correct agreement for chance, how many cheap labels equal one expert label, when disagreement is noise and when it is the signal, and, since 2023, how to tell whether a "human" label was written by a model.
Dawid & Skene (1979), "Maximum Likelihood Estimation of Observer Error-Rates Using the EM Algorithm". Problem: several observers label the same items, no true labels are available, and observers differ in reliability. Mechanism: each observer has an unknown confusion matrix (the probability of reporting class \(l\) when the truth is class \(k\)); the true class of each item is a latent variable. The expectation–maximisation (EM) algorithm alternates between estimating each item's posterior over true classes given current confusion matrices and re-estimating confusion matrices and class priors given those posteriors (Dawid & Skene 1979, Applied Statistics 28:20–28). Why it lasted: it gives per-annotator reliability for free, weights good annotators more than majority vote does, and handles any number of annotators per item. Limits: it assumes one true class per item, errors independent across annotators given the truth, and confusion matrices that do not depend on the item; it needs several labels per item to be identifiable. Picked up by: essentially all crowdsourcing aggregation; Snow et al. (2008) used a Dawid–Skene-style correction; for pairwise preferences, the analogous model is Bradley–Terry with annotator effects (Chapter 6).
Snow et al. (2008), "Cheap and Fast — But is it Good?" Problem: can Amazon Mechanical Turk workers replace expert annotators for NLP? Collection: five tasks (affect recognition, word similarity, textual entailment, event temporal ordering, word sense disambiguation) labelled by MTurk workers. Result: on affect recognition, about four non-expert labels per item matched one expert; label throughput was about 840 labels per US dollar overall (3,500 for affect, about 333 for event ordering). A bias-correction step estimated each worker's response likelihoods on a small expert-labelled gold set and combined votes with a naive-Bayes model in the Dawid–Skene spirit, improving accuracy by 4.0 points on entailment and 3.4 on event annotation (Snow et al. 2008, EMNLP 254–263). Left open: tasks needing real expertise, adversarial workers, and the assumption of a single correct label. Picked up by: the crowdsourcing industry and, directly, the gold-item practice used by every RLHF vendor.
Krippendorff's alpha. Problem: raw agreement overstates reliability when some labels are common, and Cohen's κ handles only two coders. Mechanism: \( \alpha = 1 - D_o / D_e \), where \(D_o\) is observed disagreement among the values assigned to units and \(D_e\) the disagreement expected by chance; \(\alpha = 1\) is perfect agreement and \(\alpha = 0\) is chance. It applies to any number of coders, tolerates missing labels (units with only one value drop out of the pairings) and has metrics for nominal, ordinal, interval and other scales (Krippendorff 2011). Commonly quoted thresholds attributed to Krippendorff's 2004 textbook are α ≥ 0.800 to rely on data and 0.667 ≤ α < 0.800 for tentative conclusions (Wikipedia summary; the 2011 note itself states no cutoff). Relevance: the RLHF papers mostly report raw pairwise agreement; HelpSteer2 reports quadratic-weighted Cohen's κ; Llama 2 reports Gwet's AC2. These are not interchangeable, and a platform should compute a chance-corrected statistic alongside raw agreement for every campaign with overlap (Chapter 6).
W1 reports 72% raw pairwise agreement on its 2,000 triple-labelled items, which happens to equal Stiennon et al.'s labeler–labeler figure. Raw agreement hides chance: if raters chose A 46%, B 46% and tie 8% of the time independently of content, chance agreement would be 0.46² + 0.46² + 0.08² ≈ 0.43, and a nominal κ-style correction gives (0.72 − 0.43) / (1 − 0.43) ≈ 0.51. For W1, the chance-corrected 0.51, not the raw 72%, is what should be compared across campaigns with different tie rates.
Disagreement as signal: Aroyo & Welty (2015), Uma et al. (2021), Plank (2022), Gordon et al. (2022). Problem: aggregation methods assume a single true label, but for subjective or ambiguous items annotators disagree for good reasons. Aroyo and Welty argued that the "single correct truth" model behind most annotation is a myth and proposed "crowd truth", in which the spread of annotations across a crowd describes the range of reasonable interpretations (Aroyo & Welty 2015). Uma et al.'s survey compared methods that learn from unaggregated labels: with large datasets carrying many high-quality annotations per item, training directly on soft labels (the distribution of annotator votes) beat training on aggregated or gold labels under both hard and soft evaluation; otherwise combining gold and soft labels worked best (Uma et al. 2021, JAIR 72). Plank argued that human label variation affects data, modelling and evaluation together and compiled datasets that release unaggregated labels (Plank 2022). Jury learning models each annotator individually and lets designers choose whose judgments, and in what proportions, determine a prediction, rather than letting majority vote silently decide (Gordon et al. 2022). Relevance for RLHF data: the RLHF papers above mostly collapse disagreement into one binary label (Bai 2022a explicitly discarded weak preferences and ties). Keeping per-rater labels, rater identifiers and preference strength in the export costs little and allows soft-label or rater-conditioned reward models later; discarding them is irreversible.
Veselovsky et al. (2023a, 2023b): LLM use by crowd workers, and its prevention. Problem: if crowd workers use LLMs to do text tasks, "human" data is partly model output, which undermines its purpose as an independent signal. Method: 44 MTurk workers summarised medical research abstracts (46 summaries after de-duplication, paid $1 each); a fine-tuned e5-base classifier distinguished human from ChatGPT summaries at 0.97–0.99 accuracy on held-out data, and keystroke logging (including copy and paste) provided a separate check. Result: an estimated 33–46% of summaries were LLM-produced (21 of 46 at one classifier threshold, 15 of 46 at a conservative one) (Veselovsky et al. 2023a). A follow-up on a larger population estimated prevalence around 30% without instructions and found that asking workers not to use LLMs and raising the cost of using them (for example, disabling copy and paste) cut use by about half (Veselovsky et al. 2023b). Left open: detectors trained on one model's text age quickly; both studies are on summarisation; prevention halves but does not eliminate use. Picked up by: platform-level integrity checks (paste events, time-on-task, behavioural telemetry) described in Chapter 6, and the debate in Chapter 9 about keeping human data human. Chatbot Arena's anomalous-user detector (above) is a related, statistical form of the same defence for votes.
W1 flags 4% of raters for low effort using median time under 40 s against a 4.0 min campaign median. Time alone does not detect LLM assistance, which can be slow and plausible. Following Veselovsky et al. (2023b), the W1 interface logs paste events into the rationale field and disables pasting by default; a rater whose rationales are flagged by a text classifier and who also shows paste events is routed to audit. The detection thresholds are platform choices to be calibrated on gold items, not published values.
Expert data in 2025–2026. The newest human-data work in the public literature is less about crowds and more about experts producing reusable, verifiable artefacts. Humanity's Last Exam collected 2,500 questions written by subject-matter experts worldwide, each with an unambiguous, verifiable answer that cannot be quickly found online (Phan et al. 2025). GDPval built tasks spanning 44 occupations in the top nine sectors of US GDP, written by industry professionals with an average of 14 years' experience, and compares model deliverables with expert ones (Patwardhan et al. 2025). PaperBench asks agents to replicate 20 ICML 2024 Spotlight and Oral papers and grades them against rubrics co-developed with an author of each paper, 8,316 individually gradable tasks in all; the best agent averaged a 21.0% replication score (Starace et al. 2025). HealthBench (above) had 262 physicians write rubrics; ProfBench and ComplexConstraints (above) used PhD-, MBA- and expert-authored criteria. These are mostly evaluation datasets, but the collection pattern (expert recruitment, adversarial vetting of items, per-item rubrics or reference solutions) is the same one RL training campaigns in non-verifiable domains now use, and RaR's results above show that expert grounding measurably changes a rubric reward. The public literature contains little on the operational side of expert campaigns: pay, throughput, expert disagreement rates and quality control are rarely reported, which is a gap this book's later chapters address with illustrative numbers rather than published ones.
Lineage map and reading order
The map places each work in its thread and era. Read across a row to see one idea mature; read down a column to see what the field could do at one time. Three cross-thread links are drawn as vertical arrows; others are easier to state than to draw. First, the Anthropic HH red-team and helpfulness data, and the crowdworkers who produced it, were the starting point for Constitutional AI, which replaced the harmlessness labels and kept the helpfulness ones. Second, large AI-labelled preference sets such as UltraFeedback became the fuel for DPO-style offline training, so a method in the RLHF row depends on a dataset in the AI-feedback row. Third, the evidence that crowd workers use LLMs (annotation-science row) bears directly on step-level human labels, whose value depends on being independent of the models they supervise; this is drawn dashed because it is this chapter's inference, not a link any paper states. A fourth link, not drawn, runs from Dawid–Skene through Snow et al. to the gold-item and agreement checks of every RLHF paper, and from Bradley–Terry through Christiano et al. to the Chatbot Arena leaderboard.
Reading order. Fourteen works, in an order that builds each idea before it is needed. For each, the reason to read it and what to look for.
- Christiano et al. (2017). The comparison interface, the ensemble reward predictor and query selection by disagreement, in eight pages. Look at the label counts and the 3–5 s response time.
- Stiennon et al. (2020). The first serious labeler-management protocol: screening, hourly pay, agreement with researchers, and the reward over-optimisation curve. Read the appendix on labelers.
- Ouyang et al. (2022), InstructGPT. Labeler screening criteria and thresholds, the ranking interface, the three datasets and the held-out-labeler check.
- Bai et al. (2022a), HH-RLHF. Crowd collection without agreement filtering, the online weekly loop, the helpfulness–harmlessness tension and the frank discussion of data-quality problems.
- Dawid & Skene (1979) and Snow et al. (2008), read together. The statistics of annotator reliability, and the empirical "how many cheap labels per expert" result.
- Touvron et al. (2023), Llama 2, sections 3 and 4. Industrial volumes, preference strength used as a margin, separate safety labels, weekly batches, vendor sensitivity and a 350-person red team.
- Bai et al. (2022b), Constitutional AI. What changes when humans write principles instead of labels, and what still needs human labels.
- Lee et al. (2023), RLAIF vs. RLHF. The cleanest head-to-head of AI and human labels, including position bias and per-example cost.
- Wang et al. (2024), HelpSteer2. The best-documented modern QC pipeline: added raters on disagreement, discard rates, κ before and after.
- Lightman et al. (2023), PRM800K. Step-level labels, gold-question screening and active selection of convincing wrong answers.
- Uma et al. (2021), with Plank (2022). When disagreement is the signal, and why exports should keep unaggregated labels.
- Veselovsky et al. (2023a, 2023b). The evidence that human data can silently become model data, and two mitigations with measured effect.
- Gunjal et al. (2025), Rubrics as Rewards, with Arora et al. (2025), HealthBench and Mehta et al. (2026), ComplexConstraints. Rubric structure, weights, explicit versus implicit aggregation, criterion atomicity, and the value of expert grounding.
- Zhang et al. (2025), Who&When, then Fan et al. (2026), AgentProcessBench and Peng et al. (2026), RuVerBench. How far automation is from step attribution on agent logs, what a human step-labelling protocol for tool-using agents looks like, and how noisy judges are at verifying rubric items on agent outputs: the measurements that define where expert transcript review is still required.
Readers short on time should take items 3, 4, 9, 10 and 13: together they cover screening, crowd collection at scale, modern quality control, process labels and rubric rewards. Readers building quality tooling should add items 5, 11 and 12 before Chapter 6. The DPO paper (Rafailov et al. 2023) is worth reading alongside item 4 by anyone designing exports, because it determines what metadata offline consumers need.
From Research Need to Campaign
A campaign is one bounded collection of human feedback: a fixed task shown to a defined population of raters or experts, on a defined set of model samples, under fixed guidelines, quality checks, budget and stopping rule, producing a dataset meant for one consumer such as a reward model, a supervised fine-tuning mix or a rubric grader. This chapter covers the work that happens before the first production label: turning a research need ("the reward model is weak on coding helpfulness") into a campaign that can be launched, checked and stopped.
That work matters more than its share of engineering effort suggests. A data request that is collected exactly as written can still be useless, because the request was vague about who would consume the data, what signal it should carry, or what agreement careful humans can reach on it. Early RLHF work learned this the hard way: Stiennon et al. (2020) report that their preceding work suffered from a mismatch between the notion of quality the researchers wanted the model to learn and what the labelers actually evaluated, and that they addressed it by moving to batched offline collection and keeping a hands-on relationship with labelers. The fixes in this chapter are the platform versions of those lessons.
The chapter follows that path in order. Scoping asks a fixed list of questions and decides when to push back. The spec turns the answers into a typed, versioned data model from which hours, cost and calendar time are computed rather than guessed. The launcher lets a researcher create a campaign without engineering help, but only through four gates: validation, preview, dry run and launch. The pilot calibrates raters and guidelines on a small sample and sets the statistical rules that later end collection.
What you would actually do: treat the request-to-campaign path as a product with its own metrics (time to a validated spec, pilot rounds per campaign, share of campaigns launched by researchers without engineering help), and invest in it before optimizing collection throughput, because collection is rarely where the first third of the time goes.
The design question for this chapter is where to spend checking effort. A defect in a campaign (an ambiguous guideline, a broken position randomization, an impossible target) costs very different amounts depending on where it is caught. Let \(C_\text{stage}\) be the money already committed when a defect is found at that stage. For a defect that invalidates the affected labels, the loss is roughly the labour spent on them, so catching it earlier is worth the difference in committed spend.
| Where the defect is caught | Work already spent (W1) | Typical latency of the check |
|---|---|---|
| Scoping review | $0 of labour | hours |
| Spec validation | $0 | milliseconds to seconds |
| Dry run, 150 items | ≤ 11.3 rater-hours ≈ $450 if vendor raters do it | minutes to an hour |
| Pilot round, 310 overlapped items × 3 raters | 930 labels × 4.5 min ≈ 70 h ≈ $2,790 | about a day of pool time |
| After production collection | 25,260 assignments ≈ 1,895 h ≈ $75,780 | days |
The ratio between the last row and the pilot row is about 27: a defect that a pilot would have caught costs roughly 27 times as much when it is found after collection, before counting the calendar days. That ratio justifies the gates, and it also bounds them: a gate that costs more than the expected loss it prevents is waste. If a class of defect occurs in a fraction \(p_d\) of campaigns and would destroy a share \(s\) of a campaign costing \(C\), a gate that catches it with probability \(\pi\) is worth running when \(\pi\, p_d\, s\, C\) exceeds the gate's cost. For W1, a pilot (\(\approx\$2{,}790\)) pays for itself if it has, for example, a 50% chance of catching defects that occur in 15% of campaigns and ruin half of the data: \(0.5 \times 0.15 \times 0.5 \times 75{,}780 \approx \$2{,}840\). These defect rates are illustrative assumptions; the launcher section shows how to estimate them from launch history.
The second quantity is time. The illustrative W1 baseline spends 3 days scoping and 4 on guidelines and pilot. The levers are templates (most campaigns are variants of a previous one), a spec format that computes feasibility instantly instead of in a planning meeting, and pilots sized by statistics rather than habit. What you would actually do: make every stage produce a machine-checkable artefact, measure each stage's elapsed time, and set a default of one pilot round with a cap of three.
The Build blocks in this chapter share one small codebase. Everything is plain Python 3.12+ (pydantic v2 and PyYAML for the spec) and TypeScript (strict mode, React 18 types for the component sketch). All of it is runnable and tested; the test counts below are from running it while writing this chapter.
camp/
py/scoping.py # Intake -> list[Flag]: block / push_back / note, with the arithmetic behind each
py/campaign_spec.py # CampaignSpec (pydantic): fields, cross-field rules, plan(), JSON Schema export
py/w1.yaml, w3.yaml # the two reference specs
py/pilot_stats.py # Wilson CI, sample sizes, detection probability, SPRT, design effect, stop rules
py/pilot_decide.py # one calibration round -> go / revise / rescope
ts/launcher-core.ts # form -> config, instant validation, plan, preview sampler, dry-run judge, wizard reducer
ts/Launcher.tsx # React component sketch wired to the core
ts/launcher-core.test.ts
$ cd py && python3 -m pytest -q
$ cd ts && tsc -p . && node --test dist/*.test.js
Results from the last run:
28 passed # Python: scoping, spec, stats, pilot decisions
# tests 5 # pass 5 # fail 0 # TypeScript: launcher core, including parity with the Python plan
The design rule that ties the pieces together is a single source of truth for each fact. The spec model in Python is authoritative; the TypeScript validator repeats only the checks that need to be instant in a form, and a parity test asserts that both compute the same W1 plan (24,000 labels, 25,264 assignments, $75,792). When the two disagree, the server wins and the parity test fails in CI rather than in a researcher's browser.
w1.yaml and calling plan() returns 24,000 labels, 25,264 assignments (the example sheet rounds to 25,260), 1,894.8 rater-hours, $75,792, 18,400 useful comparisons, $4.12 per useful comparison and 0.63 weeks of pool capacity. warnings() returns one warning: only 8.4 gold items per rater. That warning is the thread that runs through the pilot section.Debugging tip: when a number in the launcher looks wrong, call plan() on the stored spec, not on the form. Most discrepancies come from unit conversions in the form layer (percent versus fraction, minutes versus seconds).
In production the request-to-campaign path is a service with users (researchers), a backlog (requests) and failure modes (campaigns that launch and then produce unusable data). It needs service level objectives like any other: an SLO is a target for a measured indicator over a window, chosen so that missing it is worth acting on. The starting set below is the one this chapter's sections derive and stress-test.
| Indicator | Definition | Objective | Act when |
|---|---|---|---|
| Time to validated spec | request filed → spec passes server validation | p80 ≤ 1 working day | p80 > 2 days over 4 weeks |
| Template reuse | campaigns created from an existing spec | ≥ 70% | < 50%: templates do not fit demand |
| Self-serve launch rate | launched without an engineer editing the config | ≥ 80% | < 60% |
| Pilot rounds per campaign | calibration rounds before go | median 1, cap 3 | any campaign at round 3 |
| Post-launch defect rate | campaigns paused for a defect a gate should have caught | ≤ 5% | any defect that cost > 10% of budget |
| Data reaching the mix | campaigns whose data entered a training mix or eval within 30 days | ≥ 75% | < 50%: scoping is admitting weak requests |
The last row is the one most teams omit and the one that tells whether scoping works. A platform can be fast and cheap while most of what it collects is never used; only a metric attached to the consumer catches that.
The validation for the whole chapter is simple to state: after adopting these practices, the share of the request-to-mix time spent before the first production label should fall, and the post-launch defect rate should not rise. A faster path with more paused campaigns means the gates were thinned rather than improved.
Turning a Vague Data Need into a Scoped Campaign
Scoping is the conversation, and the record of it, that converts a research need into the answers a campaign spec requires. Its input is usually one sentence ("we need more preference data on coding"), and its output is a set of decisions: which model or evaluation will consume the data and what decision depends on it; which feedback type carries the needed information; who is able to judge it; how much is needed and what ends collection; what it may cost and how long it may take; and what risks need review. A request without these answers can still be collected, which is the danger: the platform will happily turn a vague request into twenty thousand labels that answer a different question.
Before platforms existed, this step lived in the researchers' heads and in a shared document. The published record shows why that is fragile. In the summarization work, Stiennon et al. (2020) describe a mismatch in their earlier work between the notion of quality the researchers wanted the model to learn and what the labelers actually evaluated; their remedy was closer contact with labelers, written instructions, a shared chat for questions and regular feedback. Ouyang et al. (2022) similarly report screening labelers and answering edge-case questions in a shared chat, and they changed the task's priorities between collection for training (helpfulness first) and final evaluation (truthfulness and harmlessness first). Each of these is a scoping decision made explicit: what is being judged, by whom, and to what standard.
The questions have an order, because later answers depend on earlier ones. The figure lists them; each is paired with the answer that justifies pushing back.
Consumer and decision. The consumer is the model or evaluation that reads the data; the decision is what changes if the data is good (for example "the candidate reward model replaces the current one if held-out accuracy improves"). Without both, nobody can say whether the campaign succeeded, so no stopping rule or quality bar can be set. This is the only question whose failure stops scoping outright.
Signal. The feedback type (a pairwise preference, a rubric score, a corrected continuation, a step-level label) determines what the consumer can learn. If part of the judgment can be computed by a program, such as whether code passes its unit tests, a verifier is cheaper and more consistent than people; humans should be asked about what the program cannot judge, such as readability or whether the answer addressed the question.
Separability. If careful raters disagree often, no amount of data makes the consumer exceed the agreement that exists. A target set above that level is impossible, not merely expensive. The Design & Numbers level turns this into a number called the label-noise ceiling.
Population, volume, budget and risk. The raters must be able to judge the task: Touvron et al. (2023) caution that different annotation vendors and platforms can lead to markedly different downstream results, so the pool is part of the experiment, not a procurement detail. Volume needs a stopping rule, not just a number. Budget and calendar time must fit the pool's capacity. Content risks (harmful material, personal data, licensed text) go to review before launch.
When to push back. Push back is the right response when an answer makes the campaign unlikely to change the consumer's decision: no named consumer; a target above the ceiling; a population that cannot judge the task; a volume with no rule for when it is enough; a plan that exceeds capacity or budget; or a judgment a verifier could make. Push-back is a proposal, not a refusal: each flag comes with a concrete alternative (label the evaluation set with three raters, use unit tests for correctness, add a plateau check).
Compared with a product requirements document, a scoping record is narrower and more quantitative: every answer must become a field in the spec. Its cost is a short delay before anything is collected; its benefit is that the campaign's success criterion exists before the data does. What you would actually do: make the seven questions an intake form whose answers prefill the spec, require the first question to be answered before anything else, and run the feasibility arithmetic automatically so push-back arrives with numbers attached.
Scoping becomes quantitative through three checks that can be computed from the intake answers before any data exists: feasibility (hours, cost, calendar), the label-noise ceiling, and the verifier share.
Feasibility. Let \(N\) be the number of items, \(r\) the mean labels per item including overlap (an overlap share \(o\) labelled by \(k\) raters gives \(r = 1 + o(k-1)\)), \(g\) the gold share of all assignments, \(t\) the mean minutes per label, \(w\) the hourly rate, \(P\) the pool size and \(h\) hours per rater per week. Then
\[ H = \frac{N\,r}{1-g}\cdot\frac{t}{60}, \qquad C = H\,w, \qquad D = 7\,\frac{H}{P\,h}. \]\(H\) is rater-hours, \(C\) labour cost and \(D\) calendar days of full pool capacity. Dividing by \(1-g\) rather than multiplying by \(1+g\) reflects that gold items are a share of all assignments.
The label-noise ceiling. Model each rater as matching a latent "true" preference with probability \(q\), independently of other raters, with no ties. Two raters agree when both are right or both are wrong:
\[ a = q^2 + (1-q)^2 \quad\Rightarrow\quad q = \tfrac{1}{2}\left(1 + \sqrt{2a - 1}\right). \]Here \(a\) is the observed pairwise agreement. A perfect model, one that always predicts the latent preference, agrees with a single human label only with probability \(q\); that is the ceiling for any accuracy measured against single labels. Labelling the evaluation set with \(k\) raters and taking the majority raises the ceiling to \(q_k = \sum_{j > k/2} \binom{k}{j} q^j (1-q)^{k-j}\).
The model's assumptions matter. Correlated errors (raters sharing a misconception) make true accuracy lower than \(q\) suggests; heterogeneous difficulty (most items easy, some coin-flips) means the ceiling differs by slice. Use the number to decide whether to push back, not to predict the final accuracy.
The verifier share. If a share \(m\) of the decision is machine-checkable, routing it to a verifier saves roughly \(m\) of the human time only if raters can skip that part; in practice the saving comes from raters judging a narrower question faster and more consistently. A useful threshold is \(m \ge 0.3\): below it, the integration cost of a verifier usually outweighs the gain.
| Check | Fires when | Default response | Deviate when |
|---|---|---|---|
| Consumer | no model/eval or decision named | block | never; exploratory work is a pilot with its own consumer: the researcher's report |
| Ceiling | target > \(q\) (or \(q_k\)) | multi-label the eval set, or lower the target | agreement estimate comes from a different domain: run a pilot first |
| Capacity | \(D\) > days available | cut \(N\) or overlap; extend | a second pool exists with verified quality |
| Budget | \(C\) > budget | reduce overlap before reducing \(N\) | agreement is the open question: keep overlap |
| Verifier | \(m \ge 0.3\) | verifier for that part | verifier is untrusted for this domain |
What you would actually do: compute all three checks at intake, attach the arithmetic to each push-back, and default to asking for a small pilot whenever the agreement estimate is borrowed from another domain, since the ceiling check is only as good as \(a\).
The scoping checker takes an Intake record (the researcher's answers plus what the platform knows about pools and past agreement) and returns a list of flags, each with a severity (block, push_back or note) and a message that contains the arithmetic. It reuses single_label_accuracy from the pilot statistics module, which inverts \(a = q^2 + (1-q)^2\).
"""scoping.py - turn intake answers into a feasibility report with explicit push-back flags.
Input: Intake (what the researcher asked for + what the platform knows). Output: list[Flag]."""
from dataclasses import dataclass, field
from math import comb
from pilot_stats import single_label_accuracy
@dataclass
class Intake:
consumer: str | None # e.g. "rm-coding"; None = nobody named
decision: str | None # what changes if the data is good
items: int # requested volume
raters_per_item: float # mean labels per item incl. overlap (W1: 24,000 / 20,000 = 1.2)
minutes_per_label: float
gold_fraction: float
rate_usd_per_hour: float
budget_usd: float
pool_size: int
pool_hours_per_week: float
days_available: float
expected_agreement: float | None = None # from a past campaign or a pilot
target_eval_accuracy: float | None = None # requested consumer metric vs single human labels
eval_labels_per_item: int = 1
required_skills: set[str] = field(default_factory=set)
pool_skills: set[str] = field(default_factory=set)
machine_checkable_share: float = 0.0 # share of the judgement a program could make (tests, verifiers)
@dataclass
class Flag:
code: str; severity: str; msg: str # severity: block | push_back | note
def majority_accuracy(q: float, k: int) -> float:
"""Accuracy of a k-rater majority vote (k odd) when each rater is right with prob q independently."""
return sum(comb(k, j) * q**j * (1 - q)**(k - j) for j in range(k // 2 + 1, k + 1))
def assess(x: Intake) -> list[Flag]:
f: list[Flag] = []
if not x.consumer or not x.decision:
f.append(Flag("no_consumer", "block", "Name the model/eval that consumes the data and the decision it informs."))
hours = x.items * x.raters_per_item / (1 - x.gold_fraction) * x.minutes_per_label / 60
cost = hours * x.rate_usd_per_hour
cap_hours = x.pool_size * x.pool_hours_per_week * x.days_available / 7
if cost > x.budget_usd:
f.append(Flag("budget", "push_back", f"${cost:,.0f} planned > ${x.budget_usd:,.0f}: cut volume or overlap, or raise budget."))
if hours > cap_hours:
f.append(Flag("capacity", "push_back", f"{hours:,.0f} h needed > {cap_hours:,.0f} h of pool capacity in {x.days_available:g} days."))
if x.required_skills - x.pool_skills:
f.append(Flag("population", "block", f"pool lacks {sorted(x.required_skills - x.pool_skills)}"))
if x.expected_agreement and x.target_eval_accuracy:
q = single_label_accuracy(x.expected_agreement)
ceiling = majority_accuracy(q, x.eval_labels_per_item) if x.eval_labels_per_item > 1 else q
if x.target_eval_accuracy > ceiling:
f.append(Flag("ceiling", "push_back",
f"target {x.target_eval_accuracy:.0%} > label-noise ceiling {ceiling:.1%} "
f"(agreement {x.expected_agreement:.0%}); label the eval set with 3 raters or lower the target."))
if x.machine_checkable_share >= 0.3:
f.append(Flag("verifiable", "note", f"{x.machine_checkable_share:.0%} of the judgement is machine-checkable: "
"score it with a verifier and ask humans only about the rest."))
return f
The tests encode the W1 scoping conversation: the fully scoped request is clean; removing the consumer blocks; an 85% target against single labels triggers the ceiling flag, which disappears once the evaluation set has three labels per item; tripling the volume trips both capacity and budget.
from scoping import Intake, assess, majority_accuracy
from pilot_stats import single_label_accuracy
def w1(**kw):
base = dict(consumer="rm-coding", decision="Include in next RM retrain if held-out accuracy improves",
items=20_000, raters_per_item=1.2, minutes_per_label=4.5, gold_fraction=0.05,
rate_usd_per_hour=40, budget_usd=80_000, pool_size=150, pool_hours_per_week=20,
days_available=7, expected_agreement=0.72, required_skills={"python"}, pool_skills={"python"})
base.update(kw); return Intake(**base)
def codes(x): return {f.code for f in assess(x)}
def test_scoped_w1_is_clean():
assert codes(w1()) == set()
def test_vague_request_is_blocked():
assert "no_consumer" in codes(w1(consumer=None, decision=None))
def test_ceiling_push_back_and_majority_fix():
q = single_label_accuracy(0.72)
assert abs(majority_accuracy(q, 3) - 0.9246) < 1e-3 # 3-rater eval labels lift the ceiling to ~92%
assert "ceiling" in codes(w1(target_eval_accuracy=0.85))
assert "ceiling" not in codes(w1(target_eval_accuracy=0.85, eval_labels_per_item=3))
def test_capacity_and_budget():
assert {"capacity", "budget"} <= codes(w1(items=60_000, days_available=7)) # 5,684 h > 3,000 h; $227k > $80k
def test_population_and_verifier_notes():
c = codes(w1(required_skills={"python", "rust"}, machine_checkable_share=0.4))
assert {"population", "verifiable"} <= c
assess(w1(target_eval_accuracy=0.85)) returns one flag: ceiling / push_back: target 85% > label-noise ceiling 83.2% (agreement 72%); label the eval set with 3 raters or lower the target. The researcher sees the reason and the alternative in the same message.Debugging tips. If the ceiling flag fires on every request, check that expected_agreement is pairwise agreement on the same task and not Cohen's kappa, which is chance-corrected and much lower. If capacity never fires, check that pool_hours_per_week is hours per rater, not for the whole pool. Agreement below 0.5 raises an error by design: the independent-rater model cannot explain it, and it usually means a data bug such as swapped response positions.
Operating scoping means running an intake queue with an owner, a template and a review. The failure it guards against is silent: a campaign that collects on time and on budget and never moves its consumer. That failure shows up weeks later, in the "data reaching the mix" metric, so scoping needs leading indicators.
| Indicator | Formula | Objective |
|---|---|---|
| Time to scoped intake | first message → all seven questions answered | p80 ≤ 1 working day |
| Push-back rate | requests with ≥ 1 push_back flag / requests | tracked, no target; a rate near 0 means the checks are not run |
| Push-back resolution | flags resolved by an alternative (not withdrawn) | ≥ 70% |
| Rescope after pilot | campaigns whose pilot ended in "rescope" | ≤ 15%; higher means scoping misses separability |
The scoping review runbook, run before any spec is created:
- Consumer and decision named, and the consumer's owner has agreed to the decision rule. If not: stop.
- Agreement estimate attached with its source (prior campaign id, or "none"). If none or from another domain: require a pilot before the volume is fixed.
- Ceiling check passed for the evaluation set as it will actually be labelled.
- Feasibility arithmetic attached (hours, cost, days) and within budget and capacity.
- Verifier share estimated; if ≥ 0.3, the verifier path is in the spec.
- Risk review done for content, personal data and licensing; reviewer recorded.
- Every answer copied into the spec draft; the intake record links to the spec id.
The cost of this review is a few hours per campaign; the measurable return is a lower rescope-after-pilot rate and a higher share of data reaching the mix. If after a quarter the rescope rate has not fallen, the review is being treated as paperwork and the questions should be enforced by the launcher instead.
The Campaign Spec as a Data Model
A campaign spec is a structured document, stored and versioned like code, that states everything the platform needs to run a campaign: the consumer and decision, the task and its guidelines, the prompts and how samples are generated, the population, the overlap (how many items get several raters), the quality checks, the budget and the stopping rule. It is a data model rather than a prose document because every downstream system reads it: the sampler reads the generation section, the router reads the population and overlap, the quality service reads the gold settings, the exporter reads the consumer, and the cost dashboard reads the budget. If those systems each kept their own copy of these decisions, they would drift.
The idea has two predecessors. Annotation tools already treat the interface as configuration: Label Studio describes its labeling interface as an XML configuration of object, control and visual tags (HumanSignal, Label Studio docs), and Argilla's dataset settings bundle fields, questions, guidelines and a task distribution whose min_submitted sets how many responses complete a record (Argilla docs). Those configurations cover what a rater sees and how many times an item is labelled. Documentation frameworks such as Datasheets for Datasets (Gebru et al., 2021) record, after the fact, how a dataset was collected and for what purpose. A campaign spec combines both and moves them forward in time: it states the purpose, population and procedure before collection, and the platform enforces them during collection.
Each section has a job. Consumer names the model or evaluation and the decision. Task fixes the feedback type and its options (for a preference task: whether ties are allowed, the strength scale, whether response positions are randomized). Guidelines point to the rater instructions by a pinned version, never "latest", so every label can be traced to the exact text the rater saw. Prompts and generation say where prompts come from and which model endpoints and checkpoints produce responses. Population names the pool, its size, hours and required qualifications. Overlap sets the share of items labelled by several raters and how many. Quality sets the gold share (items with known answers mixed into the stream), the accuracy floor, the minimum time per label and the expected rejection rate. Budget holds rate, expected minutes per label and a cap. Stopping holds the target and the rules that pause or end collection early.
A validator checks the spec at two levels. Field rules are local: a fraction lies between 0 and 1; an id matches a pattern. Cross-field rules need several fields at once: a pairwise task needs exactly two generation policies; the overlap cannot ask for more raters per item than the pool has; the planned cost must fit the cap; the plan must fit the calendar. Some legal specs are still probably mistakes, so the validator also returns warnings that do not block.
rm-coding with its decision rule; a pairwise task with ties and randomized positions, two pairs per prompt over 10,000 prompts; guidelines pinned at v1.2; a 2,000-pair pre-generated buffer from the current and candidate checkpoints; 150 vendor raters at 20 h/week; 10% overlap with 3 raters; 5% gold with an 80% floor and a 40-second minimum; $40/h, 4.5 min per label, a cap of $80,000; target 20,000 items within 7 days. The validator accepts it and warns that 5% gold gives only 8.4 gold items per rater over the whole campaign.A spec is frozen at launch. Changing a running campaign creates a new spec version, and every label records the version it was collected under. That rule costs some flexibility, and it is what makes the data analyzable later: without it, a change to overlap or guidelines mid-campaign silently mixes two experiments. What you would actually do: start from a template spec per feedback type, keep specs in version control or an append-only store, make the platform refuse to start a campaign from anything but a validated, frozen spec, and add new fields only with defaults so old specs stay valid.
The spec's value is that it makes derived quantities computable and consistent. Define for a preference-style task: target items \(N\); overlap share \(o\) with \(k\) raters per overlapped item; gold share \(g\) of all assignments; mean minutes per label \(t\); rate \(w\); expected QA rejection share \(\rho\); pool size \(P\) at \(h\) hours per week.
\[ L = oN\,k + (1-o)N, \qquad A = \left\lceil \frac{L}{1-g} \right\rceil, \qquad G = A - L, \] \[ H = \frac{A\,t}{60}, \qquad C = H\,w, \qquad U = N(1-\rho), \qquad c_U = \frac{C}{U}, \qquad W = \frac{H}{P\,h}. \]\(L\) is labels on real items, \(A\) total assignments, \(G\) gold assignments, \(H\) rater-hours, \(C\) cost, \(U\) useful items, \(c_U\) cost per useful item and \(W\) weeks of full pool capacity.
For a rubric task such as W3, the unit is a prompt: an expert writes a rubric (\(t_r\) minutes) and graders score \(m\) responses (\(t_s\) minutes each), so \(H = N(t_r + m\,t_s)/60\).
The spec also carries invariants whose violation would make data unusable rather than merely expensive. The table lists the ones the reference validator enforces and why each is an error rather than a warning.
| Rule | Level | Why |
|---|---|---|
Guidelines version pinned (pattern v1.2) | error | labels must be traceable to the exact text a rater saw |
| Unknown keys rejected | error | a typo such as gold_fracton would otherwise silently fall back to a default |
| Pairwise: exactly 2 policies, positions randomized | error | without randomization, position preference is confounded with model preference |
| Raters per overlap item ≤ pool size | error | the router cannot satisfy it; items would wait forever |
| Planned cost ≤ cap; planned days ≤ max days | error | a campaign that cannot finish produces a truncated, biased sample |
| Gold per rater < 20 | warning | too few to judge individual raters (see the pilot section); fix with qualification gold |
| Overlapped items < 300 | warning | agreement estimate wider than ±5 points |
| No minimum time per label | warning | low-effort detection disabled |
Design choice: schema-first or code-first. A schema-first design writes JSON Schema by hand and generates types; a code-first design writes typed models and exports the schema. JSON Schema (draft 2020-12) expresses field constraints well but expresses cross-field arithmetic such as "planned cost within cap" poorly, so the reference design is code-first: pydantic models with validators, exporting the schema for the form (Pydantic docs; JSON Schema specification). Deviate when non-Python services must validate specs independently; then keep the schema authoritative and accept duplicated cross-field logic.
The spec file is YAML because researchers edit it and review it in diffs. The W1 reference spec:
# W1: pairwise preference campaign for a coding reward model (illustrative reference workload)
spec_version: 1
id: w1_coding_pref_v1
owner: rm-coding-team
consumer:
kind: reward_model
name: rm-coding
decision: "Include in next RM retrain if held-out pairwise accuracy improves"
guidelines: {uri: "docs://guidelines/w1-coding-pref", version: v1.2}
task:
type: pairwise_preference
allow_ties: true
randomize_position: true
pairs_per_prompt: 2
prompts: 10000
generation:
mode: buffer
buffer_size: 2000
policies:
- {endpoint: policy-current, checkpoint: ckpt-current}
- {endpoint: policy-candidate, checkpoint: ckpt-candidate}
ttfs_p50_ms: 2000
ttfs_p95_ms: 5000
population: {pool: vendor-coding-raters, size: 150, hours_per_week: 20, qualifications: [python_screen]}
overlap: {fraction: 0.10, raters_per_item: 3}
quality: {gold_fraction: 0.05, gold_accuracy_floor: 0.80, min_seconds_per_label: 40, expected_reject_rate: 0.08}
budget: {rate_usd_per_hour: 40, mean_minutes_per_label: 4.5, cap_usd: 80000}
stopping:
target_items: 20000
max_calendar_days: 7
pause_window_gold: 200
plateau_check_every: 5000
plateau_min_gain: 0.004
The model uses pydantic v2. Every section is a frozen model that forbids unknown keys; the task is a discriminated union on type, so each feedback type carries only its own fields; cross-field rules and the plan live on the top-level model. parse_spec flattens validation errors into path: message lines that a form can place beside the right field.
"""campaign_spec.py - the campaign spec as a typed, validated data model (pydantic v2).
Load: spec = load_spec("w1.yaml") -> CampaignSpec (raises SpecError with every problem listed)
Plan: plan = spec.plan() -> Plan (labels, assignments, hours, cost, weeks of capacity)
Schema: CampaignSpec.model_json_schema() -> JSON Schema (draft 2020-12) for the no-code launcher."""
from __future__ import annotations
from math import ceil
from typing import Annotated, Literal, Union
import yaml
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
Frac = Annotated[float, Field(ge=0, le=1)]
class Strict(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True) # unknown keys are typos, not features
class Consumer(Strict):
kind: Literal["reward_model", "sft", "rubric_reward", "eval"]
name: str
decision: str = Field(min_length=10, description="What changes if the data is good")
class Guidelines(Strict):
uri: str
version: str = Field(pattern=r"^v\d+(\.\d+)*$") # pinned: 'latest' is rejected
class PairwiseTask(Strict):
type: Literal["pairwise_preference"]
allow_ties: bool = True
strength_scale: list[str] = ["negligible", "slight", "better", "significant"]
randomize_position: bool = True
pairs_per_prompt: int = Field(ge=1, le=8)
class RubricTask(Strict):
type: Literal["rubric_author_and_grade"]
items_min: int = Field(ge=1)
items_max: int = Field(le=30)
weights_sum_to_one: bool = True
responses_per_prompt: int = Field(ge=1, le=16)
minutes_per_rubric: float = Field(gt=0)
minutes_per_response: float = Field(gt=0)
ai_agreement_target: Frac = 0.8
@model_validator(mode="after")
def _items(self):
if self.items_min > self.items_max:
raise ValueError("items_min > items_max")
return self
Task = Annotated[Union[PairwiseTask, RubricTask], Field(discriminator="type")]
class Policy(Strict):
endpoint: str
checkpoint: str
class Generation(Strict):
mode: Literal["buffer", "on_demand"]
buffer_size: int = Field(default=0, ge=0)
policies: list[Policy] = Field(min_length=1)
ttfs_p50_ms: int = Field(gt=0)
ttfs_p95_ms: int = Field(gt=0)
class Population(Strict):
pool: str
size: int = Field(ge=1)
hours_per_week: float = Field(gt=0, le=60)
qualifications: list[str] = []
class Overlap(Strict):
fraction: Frac
raters_per_item: int = Field(ge=2, le=9)
class Quality(Strict):
gold_fraction: Annotated[float, Field(ge=0, lt=0.5)]
gold_accuracy_floor: Frac
min_seconds_per_label: int = Field(ge=0)
expected_reject_rate: Frac
class Budget(Strict):
rate_usd_per_hour: float = Field(gt=0)
mean_minutes_per_label: float = Field(gt=0)
cap_usd: float = Field(gt=0)
class Stopping(Strict):
target_items: int = Field(ge=1)
max_calendar_days: int = Field(ge=1)
pause_window_gold: int = Field(ge=20)
plateau_check_every: int = Field(default=0, ge=0)
plateau_min_gain: float = Field(default=0.0, ge=0)
class Plan(Strict):
items: int
labels: int
assignments: int
gold_assignments: int
gold_per_rater: float
rater_hours: float
cost_usd: float
useful_items: float
cost_per_useful_usd: float
capacity_weeks: float
class CampaignSpec(Strict):
spec_version: Literal[1]
id: str = Field(pattern=r"^[a-z0-9_]{3,64}$")
owner: str
consumer: Consumer
guidelines: Guidelines
task: Task
prompts: int = Field(ge=1)
generation: Generation
population: Population
overlap: Overlap
quality: Quality
budget: Budget
stopping: Stopping
# ---------- cross-field rules: things no single field can know ----------
@model_validator(mode="after")
def _cross(self):
errs = []
t = self.task
if isinstance(t, PairwiseTask):
if len(self.generation.policies) != 2:
errs.append("pairwise_preference needs exactly 2 policies")
if not t.randomize_position:
errs.append("randomize_position must be true (position bias)")
if self.stopping.target_items > self.prompts * t.pairs_per_prompt:
errs.append("target_items exceeds prompts x pairs_per_prompt")
if self.overlap.raters_per_item > self.population.size:
errs.append("overlap.raters_per_item exceeds population.size")
if self.generation.mode == "buffer" and self.generation.buffer_size == 0:
errs.append("buffer mode needs buffer_size > 0")
if self.generation.ttfs_p50_ms > self.generation.ttfs_p95_ms:
errs.append("ttfs p50 > p95")
if self.stopping.plateau_check_every and self.consumer.kind != "reward_model":
errs.append("plateau stopping needs a trainable consumer (reward_model)")
if errs:
raise ValueError("; ".join(errs))
p = self.plan()
if p.cost_usd > self.budget.cap_usd:
raise ValueError(f"planned cost ${p.cost_usd:,.0f} exceeds cap ${self.budget.cap_usd:,.0f}")
if p.capacity_weeks * 7 > self.stopping.max_calendar_days:
raise ValueError(f"needs {p.capacity_weeks * 7:.1f} days of pool capacity "
f"> max_calendar_days {self.stopping.max_calendar_days}")
return self
# ---------- derived quantities ----------
def plan(self) -> Plan:
n = self.stopping.target_items
o, q, b = self.overlap, self.quality, self.budget
if isinstance(self.task, RubricTask):
# one unit = one prompt: an expert writes a rubric, then graders score each response
t = self.task
hours = n * (t.minutes_per_rubric + t.responses_per_prompt * t.minutes_per_response) / 60
labels = n * t.responses_per_prompt
assignments = ceil(labels / (1 - q.gold_fraction))
else:
labels = round(n * o.fraction) * o.raters_per_item + (n - round(n * o.fraction))
assignments = ceil(labels / (1 - q.gold_fraction)) # gold is a share of all assignments
hours = assignments * b.mean_minutes_per_label / 60
gold = assignments - labels
cost = hours * b.rate_usd_per_hour
useful = n * (1 - q.expected_reject_rate)
cap = self.population.size * self.population.hours_per_week
return Plan(items=n, labels=labels, assignments=assignments, gold_assignments=gold,
gold_per_rater=gold / self.population.size, rater_hours=hours, cost_usd=cost,
useful_items=useful, cost_per_useful_usd=cost / useful, capacity_weeks=hours / cap)
class SpecError(Exception):
def __init__(self, problems: list[str]):
super().__init__("\n".join(problems)); self.problems = problems
def parse_spec(data: dict) -> CampaignSpec:
try:
return CampaignSpec.model_validate(data)
except ValidationError as e: # flatten into 'path: message' lines a form can show next to fields
raise SpecError([f"{'.'.join(map(str, err['loc'])) or '(spec)'}: {err['msg']}" for err in e.errors()])
def load_spec(path: str) -> CampaignSpec:
with open(path) as f:
return parse_spec(yaml.safe_load(f))
def warnings(spec: CampaignSpec) -> list[str]:
"""Soft checks: legal specs that are probably mistakes. The launcher shows them; it does not block."""
w, p = [], spec.plan()
if p.gold_per_rater < 20:
w.append(f"only {p.gold_per_rater:.1f} gold items per rater: too few to judge a rater; "
"front-load gold in qualification")
if spec.overlap.fraction * spec.stopping.target_items < 300:
w.append("fewer than 300 overlapped items: agreement CI wider than +/-5 points")
if spec.quality.min_seconds_per_label == 0:
w.append("no minimum time per label: low-effort detection disabled")
return w
The tests pin the W1 plan to the workload sheet, check the W3 hours, and exercise each error class by patching a single field of the valid W1 spec.
import copy, json, pytest, yaml
from campaign_spec import load_spec, parse_spec, warnings, CampaignSpec, SpecError
W1 = yaml.safe_load(open("w1.yaml"))
def test_w1_plan_matches_workload_sheet():
p = load_spec("w1.yaml").plan()
assert p.labels == 24_000 # 2,000 x 3 + 18,000 x 1
assert abs(p.assignments - 25_260) < 10 # gold = 5% of assignments
assert abs(p.rater_hours - 1_895) < 1
assert abs(p.cost_usd - 75_780) < 30
assert p.useful_items == 18_400
assert abs(p.cost_per_useful_usd - 4.12) < 0.01
assert abs(p.capacity_weeks - 0.63) < 0.01
def test_w1_warns_about_thin_gold():
w = warnings(load_spec("w1.yaml"))
assert any("8.4 gold items per rater" in x for x in w)
def test_w3_plan_hours():
p = load_spec("w3.yaml").plan()
assert p.rater_hours == 1_250 + 400 # authoring + grading
assert p.labels == 12_000 # 3,000 prompts x 4 graded responses
def bad(**patch):
d = copy.deepcopy(W1)
for path, v in patch.items():
node = d; keys = path.split("__")
for k in keys[:-1]: node = node[k]
node[keys[-1]] = v
with pytest.raises(SpecError) as e:
parse_spec(d)
return "\n".join(e.value.problems)
def test_rejects_unpinned_guidelines():
assert "guidelines.version" in bad(guidelines__version="latest")
def test_rejects_typo_keys():
assert "Extra inputs" in bad(quality__gold_fracton=0.05)
def test_rejects_budget_overrun():
assert "exceeds cap" in bad(budget__cap_usd=60000)
def test_rejects_capacity_overrun():
assert "pool capacity" in bad(population__size=50) # 1,895 h / 1,000 h per week = 13.3 days > 7
def test_rejects_unrandomized_pairs_and_wrong_policy_count():
msg = bad(task__randomize_position=False)
assert "randomize_position" in msg
d = copy.deepcopy(W1); d["generation"]["policies"] = d["generation"]["policies"][:1]
with pytest.raises(SpecError, match="exactly 2 policies"):
parse_spec(d)
def test_rubric_fields_required_for_rubric_task():
msg = bad(task={"type": "rubric_author_and_grade", "items_min": 8})
assert "task.rubric_author_and_grade.items_max" in msg
def test_json_schema_export_for_launcher():
s = CampaignSpec.model_json_schema()
assert "task" in s["properties"] and "discriminator" in json.dumps(s)
assert s["additionalProperties"] is False
The exported JSON Schema is what the launcher's form is generated from. Two excerpts: the guidelines section with its pinned-version pattern, and the task union with its discriminator.
"Guidelines": {"additionalProperties": false,
"properties": {"uri": {"type": "string"},
"version": {"pattern": "^v\\d+(\\.\\d+)*$", "type": "string"}},
"required": ["uri", "version"], "type": "object"}
"task": {"discriminator": {"propertyName": "type", "mapping": {
"pairwise_preference": "#/$defs/PairwiseTask",
"rubric_author_and_grade": "#/$defs/RubricTask"}},
"oneOf": [{"$ref": "#/$defs/PairwiseTask"}, {"$ref": "#/$defs/RubricTask"}]}
rubric_author_and_grade, so the validator requires items_min, items_max, responses_per_prompt and both timing fields, and does not ask about ties or positions. A W3 draft that sets only items_min: 8 fails with task.rubric_author_and_grade.items_max: Field required among other missing fields, which a form shows under the rubric panel.Debugging tips. A cross-field error arrives with the path (spec) because it belongs to no single field; the launcher should show those at the top of the form. When adding a field, give it a default, or every stored spec becomes invalid; when removing one, keep accepting it for one version with a deprecation warning, because extra="forbid" otherwise rejects old specs. Keep plan() free of I/O so the validator can call it on every keystroke-driven request.
In production the spec store is the system of record for what each campaign promised, and the label store must join to it. Three operational rules follow. Every label carries spec_id and spec_version. A running campaign's spec is immutable; changes create a new version through the same validation. And each field is classified by what a change does to the data already collected.
| Field class | Examples | Change while running |
|---|---|---|
| Operational | budget cap, max days, pool size, buffer size | new version, no data split; logged |
| Sampling | overlap share, raters per item, gold share | new version; aggregation and agreement are computed per version |
| Semantic | task options, strength scale, guidelines version, policies | new version; data before and after are different datasets until shown equivalent |
| Identity | id, consumer, task type | not allowed; start a new campaign |
SLOs for the spec service: 100% of labels joinable to a spec version (checked nightly; any orphan pages the owner); server validation p95 ≤ 2 s; zero campaigns started from an unvalidated spec (enforced, so the indicator is the count of rejected start attempts).
Runbook: changing a running campaign.
- Classify the change with the table. Identity change: stop and create a new campaign.
- Create the new version from the current one; run server validation; read the plan diff (hours, cost, days).
- Semantic change: decide before the switch whether old and new data will be pooled. If pooling, schedule an equivalence check (for example, 200 items labelled under both versions) and record the decision in the version note.
- Switch at a clean boundary: drain in-flight assignments under the old version, then route under the new one.
- Confirm that dashboards split by version, and that the export reads per-label versions.
The trade-off is a little friction on every change in exchange for analyzable data. If the team finds itself creating many sampling-class versions per campaign, that is a scoping signal: overlap and gold should have been settled in the pilot.
A No-Code Campaign Launcher
A no-code campaign launcher is the tool through which a researcher turns a scoped request into a running campaign without an engineer editing configuration. It exists because the alternative, filing a ticket and waiting for someone to write the config, adds days to every campaign and puts an engineer on the critical path of every experiment. But a launcher that only removes the engineer also removes the review the engineer was doing. The design problem is therefore to make launching easy while making mistakes hard, by replacing human review with a sequence of automatic gates.
The launcher moves a campaign through six states, and each gate receives one artefact and produces the next.
Form. The researcher starts from a template (the closest previous campaign of the same feedback type) and edits friendly fields: percentages rather than fractions, a budget cap in dollars, a dropdown of pools that actually exist. The form is generated from the spec's JSON Schema, so it cannot offer a field the spec does not have. Config. The form serializes to the spec document. Because it is a document, it can be diffed against the template, which is often the fastest review: "same as last month's campaign, but 30% more items and guidelines v1.3." Validate. Two validators run. The client repeats the cheap rules on every keystroke and shows the derived plan (assignments, hours, cost, days) live; the server runs the authoritative model, including checks that need data the browser does not have, such as whether the named endpoints are serving and whether the pool has enough qualified raters. Preview. The researcher sees a handful of real items rendered in the real rating interface, sampled deterministically so that two reviewers see the same items. Many problems are visible only here: prompts truncated by a length limit, code blocks without syntax highlighting, a guideline link that points to the wrong version. Dry run. A dry run pushes a small number of items, 150 by default, through every production stage: generation from the live endpoints, rendering, assignment, labelling with synthetic answers, aggregation and export. It checks plumbing, not judgment, so it does not need real raters. Its output is a pass/fail per stage with the measurement that decided it. Launch. The spec is frozen and gets a version id; the campaign starts.
The pattern is familiar from infrastructure tools. HashiCorp's terraform plan previews the changes a configuration would make without carrying them out (HashiCorp docs), and the launcher's plan panel plays the same role for money and time. Vendor platforms add a human gate at the same point: Scale's Rapid product requires a small calibration batch, around 20 items in its documentation's suggestion, before production batches unlock (Scale docs). The dry run tests the machine; the calibration round, covered in the next section, tests the guidelines and the people.
Compared with an engineer-run launch, the launcher trades judgment for repeatability: the gates catch the same classes of defect every time, but nothing outside those classes. What you would actually do: build the plan panel and the server validator first (they remove most of the waiting), add preview next, and treat the dry run as mandatory for any campaign that touches a new endpoint, interface or export format. Keep a named reviewer for semantic changes such as a new feedback type, where no gate yet exists.
Each gate is a test with a cost and a catch probability, and the launcher is designed by choosing gate sizes so that expected loss avoided exceeds cost.
How many dry-run items. Suppose a defect affects a fraction \(f\) of items, independently (a renderer that breaks on some code blocks, a generation timeout on long prompts). The probability that a dry run of \(n\) random items contains at least one affected item is
\[ P_\text{detect}(n, f) = 1 - (1 - f)^n. \]Setting \(P_\text{detect} = 0.95\) gives \(n = \ln 0.05 / \ln(1-f) \approx 3/f\), the "rule of three" of Hanley and Lippman-Hand (1983): seeing zero events in \(n\) trials bounds the event rate below about \(3/n\) with 95% confidence.
Systematic defects. Some defects affect every item (positions never randomized, export field missing). These are caught with near certainty by any dry run, provided the dry run executes the same code path as production. A dry run that uses a parallel "test" path tests the wrong thing; that is the most common way dry runs give false confidence.
Testing position randomization. The dry run checks the assignment log: the share \(\hat{s}\) of items with the first policy on the left. Under correct randomization \(\hat{s}\) has standard deviation \(\sqrt{0.25/n}\), which is 0.041 at \(n = 150\). A gate of \(|\hat{s} - 0.5| \le 0.10\) is 2.45 standard deviations wide, so a correct system fails it about 1.4% of the time, while a broken system (\(\hat{s}\) = 0 or 1) always fails. Partial breakage, say 60/40, passes this gate about half the time; production monitoring with a tighter gate on more items catches it (Operate level).
Estimating defect rates from launch history. The intro's gate-value inequality needs \(p_d\), the share of campaigns with a gate-catchable defect. Estimate it from launch records with a confidence interval rather than a point estimate.
| Gate | Latency target | Catches | Misses |
|---|---|---|---|
| Client validation | < 50 ms per keystroke | field and arithmetic errors | anything needing server data |
| Server validation | p95 ≤ 2 s | endpoint health, pool qualification counts, budget, cross-field rules | rendering, content |
| Preview | ≤ 10 s | truncation, rendering, wrong guideline link, unreadable items | rare item types (small \(n\)) |
| Dry run (150) | ≤ 30 min | defects with \(f \ge 2\%\) at 95%; all systematic plumbing defects | judgment problems; defects at \(f < 1\%\) |
What you would actually do: default the dry run to 150 items with synthetic labels on the production code path, raise it to \(3/f\) when a specific rare defect is suspected, and add real raters only when the interface itself is new.
The launcher splits into a pure core (no React, no network) that can be unit-tested, and a thin component that wires the core to an API. The core has five parts: formToConfig maps friendly form fields to the spec document; plan and validate repeat the spec model's arithmetic and the subset of rules that should react instantly; previewItems samples deterministically with a seeded generator; judgeDryRun turns dry-run measurements into a pass/fail per stage; and reducer is the wizard's state machine, in which any edit returns to the form.
// launcher-core.ts - pure logic behind the no-code campaign launcher (no React, no network).
// form -> config -> validate (instant, client side) -> preview -> dry run -> ready to launch.
// The server re-validates with the Python CampaignSpec; this copy exists for instant feedback.
export type TaskType = "pairwise_preference" | "rubric_author_and_grade";
export interface CampaignForm { // what the researcher edits: flat, friendly units
id: string; owner: string; consumerDecision: string;
taskType: TaskType; targetItems: number; prompts: number; pairsPerPrompt: number;
guidelinesUri: string; guidelinesVersion: string;
poolSize: number; hoursPerWeek: number;
overlapPercent: number; ratersPerOverlapItem: number;
goldPercent: number; goldFloorPercent: number; minSecondsPerLabel: number;
ratePerHour: number; minutesPerLabel: number; capUsd: number; maxCalendarDays: number;
expectedRejectPercent: number; policies: string[];
}
export interface Issue { path: string; level: "error" | "warning"; msg: string }
export interface Plan { labels: number; assignments: number; goldPerRater: number;
raterHours: number; costUsd: number; costPerUseful: number; calendarDays: number }
// The config is the spec document the server stores (same keys as the YAML spec).
export function formToConfig(f: CampaignForm) {
return {
spec_version: 1, id: f.id, owner: f.owner,
consumer: { kind: "reward_model", name: "rm", decision: f.consumerDecision },
guidelines: { uri: f.guidelinesUri, version: f.guidelinesVersion },
task: { type: f.taskType, allow_ties: true, randomize_position: true, pairs_per_prompt: f.pairsPerPrompt },
prompts: f.prompts,
population: { pool: "default", size: f.poolSize, hours_per_week: f.hoursPerWeek },
overlap: { fraction: f.overlapPercent / 100, raters_per_item: f.ratersPerOverlapItem },
quality: { gold_fraction: f.goldPercent / 100, gold_accuracy_floor: f.goldFloorPercent / 100,
min_seconds_per_label: f.minSecondsPerLabel, expected_reject_rate: f.expectedRejectPercent / 100 },
budget: { rate_usd_per_hour: f.ratePerHour, mean_minutes_per_label: f.minutesPerLabel, cap_usd: f.capUsd },
stopping: { target_items: f.targetItems, max_calendar_days: f.maxCalendarDays },
};
}
export function plan(f: CampaignForm): Plan {
const n = f.targetItems, over = Math.round(n * f.overlapPercent / 100);
const labels = over * f.ratersPerOverlapItem + (n - over);
const assignments = Math.ceil(labels / (1 - f.goldPercent / 100));
const raterHours = assignments * f.minutesPerLabel / 60;
const costUsd = raterHours * f.ratePerHour;
const useful = n * (1 - f.expectedRejectPercent / 100);
return { labels, assignments, goldPerRater: (assignments - labels) / f.poolSize, raterHours, costUsd,
costPerUseful: costUsd / useful, calendarDays: 7 * raterHours / (f.poolSize * f.hoursPerWeek) };
}
export function validate(f: CampaignForm): { issues: Issue[]; plan: Plan | null } {
const I: Issue[] = [];
const err = (path: string, msg: string) => I.push({ path, level: "error", msg });
const warn = (path: string, msg: string) => I.push({ path, level: "warning", msg });
if (!/^[a-z0-9_]{3,64}$/.test(f.id)) err("id", "lowercase letters, digits, _ (3-64)");
if (f.consumerDecision.trim().length < 10) err("consumerDecision", "say what changes if the data is good");
if (!/^v\d+(\.\d+)*$/.test(f.guidelinesVersion)) err("guidelinesVersion", "pin a version like v1.2");
if (f.taskType === "pairwise_preference" && f.policies.length !== 2) err("policies", "pairwise needs exactly 2");
if (f.targetItems > f.prompts * f.pairsPerPrompt) err("targetItems", "more items than prompts x pairs");
if (f.ratersPerOverlapItem < 2 || f.ratersPerOverlapItem > f.poolSize) err("ratersPerOverlapItem", "2..pool size");
if (f.goldPercent < 0 || f.goldPercent >= 50) err("goldPercent", "0..49");
if (I.some(i => i.level === "error")) return { issues: I, plan: null }; // no plan from a broken form
const p = plan(f);
if (p.costUsd > f.capUsd) err("capUsd", `planned $${Math.round(p.costUsd)} exceeds cap`);
if (p.calendarDays > f.maxCalendarDays) err("maxCalendarDays", `needs ${p.calendarDays.toFixed(1)} days of pool capacity`);
if (p.goldPerRater < 20) warn("goldPercent", `${p.goldPerRater.toFixed(1)} gold items per rater; front-load gold in qualification`);
if (f.targetItems * f.overlapPercent / 100 < 300) warn("overlapPercent", "under 300 overlapped items: agreement CI wider than +/-5 pts");
if (f.minSecondsPerLabel === 0) warn("minSecondsPerLabel", "low-effort detection disabled");
return { issues: I, plan: p };
}
// Preview: a deterministic sample of items, so two people looking at the preview see the same thing.
export function mulberry32(seed: number) {
return () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
export function previewItems<T>(pool: T[], k: number, seed: number): { item: T; leftIsFirstPolicy: boolean }[] {
const r = mulberry32(seed), idx = pool.map((_, i) => i);
for (let i = idx.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [idx[i], idx[j]] = [idx[j], idx[i]]; }
return idx.slice(0, k).map(i => ({ item: pool[i], leftIsFirstPolicy: r() < 0.5 }));
}
// Dry run: k items through every real stage with synthetic labels; each stage must pass.
export type Stage = "generate" | "render" | "assign" | "label" | "aggregate" | "export";
export const STAGES: Stage[] = ["generate", "render", "assign", "label", "aggregate", "export"];
export interface StageResult { stage: Stage; ok: boolean; detail: string }
export interface DryRunGates { maxTtfsP95Ms: number; maxLeftShareDev: number; minExportRows: number }
export function judgeDryRun(r: { ttfsMs: number[]; leftIsFirst: boolean[]; renderErrors: number;
unassigned: number; exportRows: number }, g: DryRunGates): StageResult[] {
const s = [...r.ttfsMs].sort((a, b) => a - b);
const p95 = s[Math.min(s.length - 1, Math.ceil(0.95 * s.length) - 1)];
const left = r.leftIsFirst.filter(Boolean).length / r.leftIsFirst.length;
return [
{ stage: "generate", ok: p95 <= g.maxTtfsP95Ms, detail: `ttfs p95 ${p95} ms` },
{ stage: "render", ok: r.renderErrors === 0, detail: `${r.renderErrors} render errors` },
{ stage: "assign", ok: r.unassigned === 0 && Math.abs(left - 0.5) <= g.maxLeftShareDev,
detail: `left=first-policy share ${left.toFixed(2)}, ${r.unassigned} unassigned` },
{ stage: "label", ok: true, detail: "synthetic labels submitted" },
{ stage: "aggregate", ok: true, detail: "overlap groups formed" },
{ stage: "export", ok: r.exportRows >= g.minExportRows, detail: `${r.exportRows} export rows` },
];
}
// Wizard state machine: a step can only be reached when the one before it passed.
export type Step = "edit" | "validated" | "previewed" | "dryRunPassed" | "launched";
export type Action = { type: "edited" } | { type: "validated"; ok: boolean } | { type: "previewed" }
| { type: "dryRun"; results: StageResult[] } | { type: "launch" };
export function reducer(step: Step, a: Action): Step {
switch (a.type) {
case "edited": return "edit"; // any edit invalidates later steps
case "validated": return a.ok ? "validated" : "edit";
case "previewed": return step === "validated" ? "previewed" : step;
case "dryRun": return step === "previewed" && a.results.every(r => r.ok) ? "dryRunPassed" : step;
case "launch": return step === "dryRunPassed" ? "launched" : step;
}
}
The component sketch below type-checks against React 18's types. It shows the wiring, not styling: local validation on every change, buttons enabled only in the right state, the plan panel, preview in sandboxed iframes, and the dry-run report. The server API is the authority; the component never launches a config the server has not validated in the current state.
// Launcher.tsx - component sketch: one screen, four gated panels. Type-checked, not styled.
import { useEffect, useMemo, useReducer, useState } from "react";
import { CampaignForm, Issue, StageResult, Step, formToConfig, reducer, validate } from "./launcher-core";
type Api = {
validate(cfg: object): Promise<{ issues: Issue[] }>; // server: Python CampaignSpec, the authority
preview(cfg: object, seed: number): Promise<{ html: string[] }>; // real interface, real items
dryRun(cfg: object, k: number): Promise<{ results: StageResult[] }>;
launch(cfg: object): Promise<{ campaignId: string }>;
};
export function Launcher({ api, initial }: { api: Api; initial: CampaignForm }) {
const [form, setForm] = useState<CampaignForm>(initial);
const [step, dispatch] = useReducer(reducer, "edit" as Step);
const [serverIssues, setServerIssues] = useState<Issue[]>([]);
const [preview, setPreview] = useState<string[]>([]);
const [dry, setDry] = useState<StageResult[]>([]);
const local = useMemo(() => validate(form), [form]); // instant, every keystroke
const config = useMemo(() => formToConfig(form), [form]);
useEffect(() => { dispatch({ type: "edited" }); setPreview([]); setDry([]); }, [form]);
const set = <K extends keyof CampaignForm>(k: K) => (v: CampaignForm[K]) => setForm({ ...form, [k]: v });
const errorsFor = (path: string) => [...local.issues, ...serverIssues].filter(i => i.path === path);
const blocking = local.issues.some(i => i.level === "error");
async function runValidate() {
const { issues } = await api.validate(config);
setServerIssues(issues);
dispatch({ type: "validated", ok: !issues.some(i => i.level === "error") });
}
async function runPreview() { setPreview((await api.preview(config, 7)).html); dispatch({ type: "previewed" }); }
async function runDry() { const { results } = await api.dryRun(config, 150); setDry(results); dispatch({ type: "dryRun", results }); }
return (
<div className="launcher">
<section aria-label="Campaign">
<NumberField label="Comparisons" value={form.targetItems} onChange={set("targetItems")} issues={errorsFor("targetItems")} />
<NumberField label="Overlap %" value={form.overlapPercent} onChange={set("overlapPercent")} issues={errorsFor("overlapPercent")} />
<NumberField label="Gold %" value={form.goldPercent} onChange={set("goldPercent")} issues={errorsFor("goldPercent")} />
<NumberField label="Budget cap $" value={form.capUsd} onChange={set("capUsd")} issues={errorsFor("capUsd")} />
</section>
<aside aria-label="Plan">{local.plan && (
<dl>
<dt>Assignments</dt><dd>{local.plan.assignments.toLocaleString()}</dd>
<dt>Rater-hours</dt><dd>{Math.round(local.plan.raterHours).toLocaleString()}</dd>
<dt>Cost</dt><dd>${Math.round(local.plan.costUsd).toLocaleString()}</dd>
<dt>Per useful item</dt><dd>${local.plan.costPerUseful.toFixed(2)}</dd>
<dt>Pool-days</dt><dd>{local.plan.calendarDays.toFixed(1)}</dd>
</dl>)}
</aside>
<footer>
<button disabled={blocking} onClick={runValidate}>1 Validate</button>
<button disabled={step !== "validated"} onClick={runPreview}>2 Preview</button>
<button disabled={step !== "previewed"} onClick={runDry}>3 Dry run (150 items)</button>
<button disabled={step !== "dryRunPassed"} onClick={() => api.launch(config)}>4 Launch</button>
</footer>
{preview.map((h, i) => <iframe key={i} title={`preview ${i}`} srcDoc={h} sandbox="" />)}
<ol>{dry.map(r => <li key={r.stage}>{r.ok ? "pass" : "FAIL"} {r.stage}: {r.detail}</li>)}</ol>
</div>
);
}
function NumberField(p: { label: string; value: number; onChange: (v: number) => void; issues: Issue[] }) {
return (
<label>{p.label}
<input type="number" value={p.value} onChange={e => p.onChange(Number(e.target.value))}
aria-invalid={p.issues.some(i => i.level === "error")} />
{p.issues.map((i, k) => <small key={k} className={i.level}>{i.msg}</small>)}
</label>
);
}
The server side exposes four endpoints with small contracts:
POST /api/campaigns/validate {spec} -> {issues: [{path, level, msg}], plan}
POST /api/campaigns/preview {spec, seed, k} -> {html: [string]} # real renderer, real items
POST /api/campaigns/dry-run {spec, k} -> {run_id}; GET .../dry-run/{run_id} -> {results: [StageResult]}
POST /api/campaigns/launch {spec, dry_run_id}-> {campaign_id, spec_version} # 409 unless dry_run_id ran this exact spec hash
The launch endpoint checks that the dry run was executed on the same spec hash, so a stale dry run cannot authorize a changed spec even if the client state machine is bypassed. The tests run with Node's built-in test runner after compiling with tsc:
import { test } from "node:test";
import assert from "node:assert/strict";
import { CampaignForm, validate, plan, previewItems, judgeDryRun, reducer, STAGES } from "./launcher-core";
const W1: CampaignForm = {
id: "w1_coding_pref_v1", owner: "rm-coding-team", consumerDecision: "Include in next RM retrain if accuracy improves",
taskType: "pairwise_preference", targetItems: 20000, prompts: 10000, pairsPerPrompt: 2,
guidelinesUri: "docs://guidelines/w1-coding-pref", guidelinesVersion: "v1.2",
poolSize: 150, hoursPerWeek: 20, overlapPercent: 10, ratersPerOverlapItem: 3,
goldPercent: 5, goldFloorPercent: 80, minSecondsPerLabel: 40,
ratePerHour: 40, minutesPerLabel: 4.5, capUsd: 80000, maxCalendarDays: 7,
expectedRejectPercent: 8, policies: ["policy-current", "policy-candidate"],
};
test("plan matches the Python spec model on W1", () => {
const p = plan(W1);
assert.equal(p.labels, 24000);
assert.equal(p.assignments, 25264);
assert.ok(Math.abs(p.costUsd - 75792) < 1);
assert.ok(Math.abs(p.costPerUseful - 4.12) < 0.01);
assert.ok(Math.abs(p.calendarDays - 4.42) < 0.01); // 0.63 weeks of pool capacity
});
test("W1 validates with one warning about thin gold", () => {
const { issues } = validate(W1);
assert.deepEqual(issues.map(i => i.level), ["warning"]);
assert.match(issues[0].msg, /8\.4 gold items per rater/);
});
test("errors block the plan and point at the field", () => {
const r = validate({ ...W1, guidelinesVersion: "latest", policies: ["only-one"] });
assert.equal(r.plan, null);
assert.deepEqual(r.issues.map(i => i.path).sort(), ["guidelinesVersion", "policies"]);
const c = validate({ ...W1, capUsd: 60000 });
assert.ok(c.issues.some(i => i.path === "capUsd" && i.level === "error"));
});
test("preview is deterministic and roughly balanced", () => {
const pool = Array.from({ length: 2000 }, (_, i) => i);
const a = previewItems(pool, 150, 7), b = previewItems(pool, 150, 7);
assert.deepEqual(a, b);
const left = a.filter(x => x.leftIsFirstPolicy).length / a.length;
assert.ok(Math.abs(left - 0.5) < 0.12);
});
test("dry run catches a position bug and the wizard refuses to advance", () => {
const ok = judgeDryRun({ ttfsMs: Array(150).fill(1800), leftIsFirst: Array.from({ length: 150 }, (_, i) => i % 2 === 0),
renderErrors: 0, unassigned: 0, exportRows: 150 }, { maxTtfsP95Ms: 5000, maxLeftShareDev: 0.1, minExportRows: 150 });
assert.equal(ok.length, STAGES.length);
assert.ok(ok.every(r => r.ok));
const bug = judgeDryRun({ ttfsMs: Array(150).fill(1800), leftIsFirst: Array(150).fill(true),
renderErrors: 0, unassigned: 0, exportRows: 150 }, { maxTtfsP95Ms: 5000, maxLeftShareDev: 0.1, minExportRows: 150 });
assert.equal(bug.find(r => r.stage === "assign")!.ok, false);
let s = reducer("edit", { type: "validated", ok: true });
s = reducer(s, { type: "previewed" });
assert.equal(reducer(s, { type: "dryRun", results: bug }), "previewed");
assert.equal(reducer(reducer(s, { type: "dryRun", results: ok }), { type: "launch" }), "launched");
assert.equal(reducer("dryRunPassed", { type: "edited" }), "edit");
});
assign stage fails, and the reducer refuses to move from previewed to dryRunPassed.Debugging tips. If the plan panel and the server disagree, run the parity test with the stored spec; the usual cause is a percent/fraction conversion in formToConfig. If previews differ between reviewers, the seed is not being passed through. If dry runs pass and production fails, compare code paths: the dry run must call the production assignment and export services, with only the labelling step replaced.
In production the launcher is a user-facing service whose failures are either friction (slow or flaky gates, which push researchers back to tickets) or false passes (a campaign launches with a defect a gate should have caught). Both need indicators.
| SLI | Objective | Alert |
|---|---|---|
| Server validation latency p95 | ≤ 2 s | > 5 s for 15 min |
| Preview success rate | ≥ 99% | < 95% over 1 h |
| Dry-run completion time p95 | ≤ 30 min | any run > 60 min |
| Dry-run infrastructure failure rate (not spec defects) | ≤ 2% | > 5% over a day |
| False-pass rate: campaigns paused in first 48 h for a gate-catchable defect | ≤ 5% of launches | any occurrence opens a gate review |
| Live position share \(|\hat{s} - 0.5|\) over rolling 500 assignments | ≤ 0.06 | page the campaign owner |
Dashboard for a newly launched campaign, first 48 hours: (1) assignments per hour versus plan; (2) time to first sample p50/p95 from the generation service; (3) live position share with a band of \(\pm 0.06\); (4) render error rate; (5) gold accuracy, rolling 200; (6) median seconds per label with the 40 s floor marked; (7) spend versus plan. Panels 3 and 4 exist because they measure what the dry run measured, on the full stream.
randomize_position; the production assignment service read a stale default for overlap and single items alike. Remedy. (1) Pause the campaign. (2) Fix the service to read the frozen spec. (3) Decide on the 2,000 labels (about \(2{,}000/25{,}264 \times \$75{,}792 \approx \$6{,}000\)): they are not invalid, since each still records which response the rater preferred, but they are confounded with position, so mark them and exclude them from position-sensitive analyses and from the reward-model training set unless a later analysis shows rater position bias is negligible. (4) Make the dry run call the production assignment service with a flag that diverts only labelling. (5) Add live panel 3 with its alert. Validation. After relaunch, the live share should sit within \(0.5 \pm 0.06\) over every 500-assignment window (a correct system breaches this about 0.7% of the time per window); the left-choice rate on randomized items then measures true rater position bias, which is the number to report.Runbook: dry run failed.
- Read the failed stage and its measurement. Infrastructure failure (endpoint down, timeout) rather than a spec defect: retry once; if it fails again, page the owning service, not the researcher.
generatefailed on latency: check the endpoint's own dashboard; if the endpoint is healthy, the prompt length distribution is the usual cause; consider a larger pre-generated buffer.renderfailed: open the failing items in preview; fix the prompt filter or the renderer; re-validate (the edit resets the wizard).assignfailed on position share: check the assignment log, not labels; a share of 0 or 1 is a plumbing defect; a share between 0.4 and 0.6 that failed is likely a 1.4% false alarm: re-run once.exportfailed: diff the exported row against the consumer's data contract; never launch with an export defect, because it surfaces only after collection.
The trade-off to watch is gate friction against false passes. If false passes stay at zero while researchers complain about dry-run time, shorten the dry run for template clones that change only volume; if false passes appear, look first at whether the failing campaign's dry run used the production code path.
Pilots, Calibration Rounds, Guideline Iteration, Sample Sizing and Stopping Rules
A pilot is a small, deliberately instrumented run of a campaign whose purpose is to learn whether the task, guidelines and population produce consistent judgments before money is committed to volume. It is made of calibration rounds: in each, a group of raters labels the same small set of items under a pinned guideline version, the platform measures agreement and accuracy, and reviewers read the disagreements. The outcome of a round is one of three decisions: go to production; revise the guidelines and run another round; or rescope, because the disagreement comes from the task itself rather than from its wording.
This cycle predates RLHF. Annotation research describes it as the MATTER cycle (Model, Annotate, Train, Test, Evaluate, Revise) in Pustejovsky and Stubbs (2012), and Finlayson and Erjavec (2016) describe the inner loop between modelling and pilot annotation in which annotators label a small sample, results are inspected with agreement measures, and the guidelines are rewritten when the scheme is sound but its specification is unclear. RLHF practice made the loop continuous: Stiennon et al. (2020) gave labelers detailed instructions, a shared chat, regular feedback, and later office hours and one-on-one calls about disagreements, and kept labelers only above speed and agreement thresholds. Vendor platforms build the round into the product; Scale's calibration batch, for example, has taskers label a small subset and give feedback on the instructions; the requester goes through each item to complete the batch, and a calibration batch is required before production batches unlock (Scale docs).
Qualification comes first: each rater answers gold items (items with an agreed answer) until a sequential test decides whether their accuracy is acceptable. Then the calibration round runs. Measurement produces four numbers and one reading: agreement on overlapped items, gold accuracy, tie rate, time per label, and a review of disagreements grouped into clusters by reason ("both responses are wrong", "one is shorter but less correct"). A large cluster is a guideline problem: one missing rule explains much of the disagreement, and a rule plus two or three worked examples usually fixes it. Disagreement spread thinly across many reasons is a task problem: careful people simply judge differently, and more guideline text will not change that.
Guideline iteration is the revise branch done carefully: every change gets a new version, a changelog entry naming the cluster it addresses, and new examples; the examples that the round settled become gold items for the future. The round cap matters because guideline revision has diminishing returns, and a third failed round is strong evidence that the problem is the task.
Stopping rules are set during the pilot and enforced during production. A target count ends collection by default. A quality pause stops collection when gold accuracy is confidently below the floor. A plateau stop ends collection early when the consumer, retrained on the data so far, stops improving; Touvron et al. (2023) collected preference data in weekly batches and retrained reward models as data accumulated, and Stiennon et al. (2020) alternated large labelling batches with retraining, which is the structure a plateau rule needs. Budget and calendar limits are the last line.
Compared with launching at full volume and fixing problems as they appear, a pilot costs a few percent of the budget and a day or two, and it buys a campaign whose guidelines have been tested. What you would actually do: always run one calibration round, size it from the agreement precision you need, qualify raters with front-loaded gold rather than relying on the gold mixed into production, cap rounds at three, and write the stopping rules into the spec before the first production label.
Five calculations size a pilot and set its stopping rules.
1. Overlapped items for an agreement estimate. To estimate an agreement proportion near \(p\) with a 95% confidence half-width \(E\), treating the item as the unit (rater pairs within an item are correlated, so counting pairs would overstate precision):
\[ n = \frac{z^2\,p(1-p)}{E^2}, \qquad z = 1.96. \]2. Gold items per rater. Production gold is a share of all assignments, so each rater sees \(G/P\) gold items. For W1, \(1{,}264/150 = 8.4\). How many are needed to judge a rater? Wald's sequential probability ratio test (Wald, 1945) answers with the fewest items on average. Let a rater's gold accuracy be \(p_0\) (unacceptable) or \(p_1\) (acceptable), with error rates \(\alpha\) (passing a bad rater) and \(\beta\) (failing a good one). After each gold item, add to a running log-likelihood ratio \(\Lambda\):
\[ \Lambda \mathrel{+}= \ln\frac{p_1}{p_0}\ \text{if correct}, \qquad \Lambda \mathrel{+}= \ln\frac{1-p_1}{1-p_0}\ \text{if wrong}; \qquad \text{pass if } \Lambda \ge \ln\frac{1-\beta}{\alpha},\ \text{fail if } \Lambda \le \ln\frac{\beta}{1-\alpha}. \]3. Clustered pilots. When many scores share a cluster, such as the 40 item-scores (10 rubric items × 4 responses) of one W3 prompt, they are correlated. The design effect \(\text{deff} = 1 + (m-1)\rho\), with cluster size \(m\) and intra-cluster correlation \(\rho\), multiplies the required sample.
4. The quality pause and the peeking problem. A natural rule pauses collection when the Wilson upper bound of gold accuracy over the last 200 gold answers falls below the 80% floor: 148/200 (74%) gives an upper bound of 0.796 and pauses; 152/200 (76%) gives 0.814 and does not. But the rule is checked repeatedly, and every look is another chance of a false alarm. Johari et al. (2015/2019) show that ordinary p-values and intervals become unreliable when users monitor continuously and stop on the result; sequential methods such as the SPRT are designed for it. A simple mitigation for a rolling-window rule is to require two consecutive breaching windows.
5. The plateau stop. If the consumer is retrained at checkpoints \(n_1, n_2, \ldots\), fit \(\text{acc}(n) = a - b/\sqrt{n}\) to the measured accuracies and stop when the predicted gain from the next batch \(\Delta n\), \(b\,(n^{-1/2} - (n + \Delta n)^{-1/2})\), falls below a threshold. The functional form is an assumption; any monotone saturating curve works, and the rule should be re-fitted rather than trusted far beyond the data.
What you would actually do: size the calibration round for \(\pm 5\) points (about 300 items); qualify raters sequentially; arm the quality pause with two consecutive windows; and enable the plateau stop only when the consumer can be retrained cheaply between batches.
The statistics module holds every calculation used in this section. Each function takes and returns plain numbers so it can run inside the spec validator, the pilot report and the production quality service.
"""pilot_stats.py - sample sizes and stopping rules for pilots and campaigns.
Pure standard library. Every function takes plain numbers and returns plain numbers."""
from math import sqrt, log, ceil
from statistics import NormalDist
Z = NormalDist().inv_cdf
def wilson(k: int, n: int, conf: float = 0.95) -> tuple[float, float]:
"""Wilson score interval for k successes in n trials -> (low, high)."""
if n == 0:
return (0.0, 1.0)
z = Z(1 - (1 - conf) / 2); p = k / n
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
half = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return (centre - half, centre + half)
def n_for_proportion(p: float, half_width: float, conf: float = 0.95, deff: float = 1.0) -> int:
"""Items needed so a proportion near p has a CI of +/- half_width.
deff = design effect for clustered items (1 + (m - 1) * icc)."""
z = Z(1 - (1 - conf) / 2)
return ceil(deff * z * z * p * (1 - p) / half_width ** 2)
def design_effect(m: int, icc: float) -> float:
"""Variance inflation when m correlated scores share one cluster (e.g. one prompt)."""
return 1 + (m - 1) * icc
def p_detect(prevalence: float, n: int) -> float:
"""Probability that n random items contain at least one item with a defect of this prevalence."""
return 1 - (1 - prevalence) ** n
def n_to_detect(prevalence: float, power: float = 0.95) -> int:
"""Smallest n with p_detect >= power (the rule of three is the power=0.95 approximation 3/prevalence)."""
return ceil(log(1 - power) / log(1 - prevalence))
def single_label_accuracy(pair_agreement: float) -> float:
"""If each rater independently matches a latent preference with probability q,
two raters agree with probability q^2 + (1-q)^2. Invert for q (q >= 0.5)."""
disc = 2 * pair_agreement - 1
if disc < 0:
raise ValueError("agreement below 0.5 is not explained by this model")
return (1 + sqrt(disc)) / 2
class SPRT:
"""Wald's sequential probability ratio test for a rater's gold accuracy.
H0: accuracy = p0 (unacceptable), H1: accuracy = p1 (acceptable)."""
def __init__(self, p0: float, p1: float, alpha: float = 0.05, beta: float = 0.05):
assert 0 < p0 < p1 < 1
self.up = log((1 - beta) / alpha) # accept H1 (pass) at or above this
self.down = log(beta / (1 - alpha)) # accept H0 (fail) at or below this
self.inc_ok = log(p1 / p0) # log-likelihood ratio step for a correct gold answer
self.inc_bad = log((1 - p1) / (1 - p0)) # step for a wrong gold answer
self.p0, self.p1, self.alpha, self.beta = p0, p1, alpha, beta
self.llr, self.n = 0.0, 0
def update(self, correct: bool) -> str:
self.n += 1
self.llr += self.inc_ok if correct else self.inc_bad
if self.llr >= self.up:
return "pass"
if self.llr <= self.down:
return "fail"
return "continue"
def expected_n(self, p: float) -> float:
"""Wald's approximation (ignores overshoot) of the average number of gold items when true accuracy is p0 or p1."""
drift = p * self.inc_ok + (1 - p) * self.inc_bad
if p == self.p1:
num = (1 - self.beta) * self.up + self.beta * self.down
elif p == self.p0:
num = self.alpha * self.up + (1 - self.alpha) * self.down
else:
raise ValueError("approximation implemented for p0 and p1 only")
return num / drift
def fixed_n_two_point(p0: float, p1: float, alpha: float = 0.05, beta: float = 0.05) -> int:
"""Fixed-sample size for a one-sided test of p0 versus p1 (normal approximation)."""
za, zb = Z(1 - alpha), Z(1 - beta)
return ceil(((za * sqrt(p0 * (1 - p0)) + zb * sqrt(p1 * (1 - p1))) / (p1 - p0)) ** 2)
def should_pause(gold_correct: int, gold_seen: int, floor: float = 0.80, conf: float = 0.95) -> bool:
"""Quality stop: pause when we are confident the rolling gold accuracy is below the floor."""
return gold_seen > 0 and wilson(gold_correct, gold_seen, conf)[1] < floor
def plateau_stop(acc_by_n: list[tuple[int, float]], next_batch: int, min_gain: float) -> bool:
"""Volume stop: fit acc(n) = a - b / sqrt(n) by least squares on (1/sqrt(n), acc) and stop when
the predicted gain from collecting next_batch more labels is below min_gain."""
xs = [1 / sqrt(n) for n, _ in acc_by_n]; ys = [a for _, a in acc_by_n]
mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs)
b = -slope # acc = a - b * x with x = 1/sqrt(n)
n_now = acc_by_n[-1][0]
gain = b * (1 / sqrt(n_now) - 1 / sqrt(n_now + next_batch))
return gain < min_gain
def simulate_pause_rate(p: float, total: int = 1264, window: int = 200, every: int = 50,
consecutive: int = 1, trials: int = 2000, seed: int = 1) -> float:
"""Monte Carlo: share of campaigns whose rolling-window quality stop fires at least once
when every gold answer is correct with probability p (repeated looks inflate false pauses)."""
import random
rng, fired_n = random.Random(seed), 0
for _ in range(trials):
xs = [rng.random() < p for _ in range(total)]
run = 0
for end in range(window, total + 1, every):
run = run + 1 if should_pause(sum(xs[end - window:end]), window) else 0
if run >= consecutive:
fired_n += 1; break
return fired_n / trials
The tests reproduce each number in the Design & Numbers level, check the sequential test's error rates by simulation (4,000 simulated raters per hypothesis), and confirm the false-pause behaviour of the rolling-window rule.
import random
from math import sqrt
from pilot_stats import (wilson, n_for_proportion, design_effect, p_detect, n_to_detect,
single_label_accuracy, SPRT, fixed_n_two_point, should_pause, plateau_stop)
def test_w1_pilot_overlap_size():
# W1: pairwise agreement about 0.72; +/-5 points needs 310 overlapped items, +/-10 needs 78
assert n_for_proportion(0.72, 0.05) == 310
assert n_for_proportion(0.72, 0.10) == 78
def test_agreement_ceiling():
# 72% pairwise agreement implies each single label matches the latent preference ~83% of the time
q = single_label_accuracy(0.72)
assert abs(q - 0.8317) < 1e-3
assert abs(q * q + (1 - q) ** 2 - 0.72) < 1e-9
def test_defect_detection():
assert abs(p_detect(0.02, 50) - 0.636) < 1e-3
assert n_to_detect(0.02) == 149 # rule of three says 3 / 0.02 = 150
assert n_to_detect(0.05) == 59
def test_sprt_constants_and_asn():
s = SPRT(0.70, 0.88)
assert abs(s.up - 2.944) < 1e-3 and abs(s.down + 2.944) < 1e-3
assert round(s.expected_n(0.88)) == 29 and round(s.expected_n(0.70)) == 23
assert fixed_n_two_point(0.70, 0.88) == 52 # the sequential test needs about half
def test_sprt_error_rates_by_simulation():
rng = random.Random(7)
def run(p):
s = SPRT(0.70, 0.88)
while True:
r = s.update(rng.random() < p)
if r != "continue":
return r, s.n
good = [run(0.88) for _ in range(4000)]
bad = [run(0.70) for _ in range(4000)]
assert sum(r == "fail" for r, _ in good) / 4000 < 0.06 # beta about 0.05 or less
assert sum(r == "pass" for r, _ in bad) / 4000 < 0.06 # alpha about 0.05 or less
assert 22 < sum(n for _, n in good) / 4000 < 40 # Wald's 29 plus overshoot
def test_w3_clustered_pilot():
# 40 item-scores per prompt (10 items x 4 responses), assumed ICC 0.1 -> design effect 4.9
assert design_effect(40, 0.1) == 4.9
assert n_for_proportion(0.80, 0.05) == 246
n = n_for_proportion(0.80, 0.05, deff=design_effect(40, 0.1))
assert n == 1205 and -(-n // 40) == 31 # 31 prompts
def test_quality_pause():
lo, hi = wilson(148, 200)
assert hi < 0.80 and should_pause(148, 200) # 74% on 200 gold: confidently below 80%
assert not should_pause(152, 200) # 76%: not yet conclusive
def test_plateau_stop_on_synthetic_curve():
curve = [(n, 0.74 - 3 / sqrt(n)) for n in (2000, 5000, 10000, 15000)] # synthetic, illustrative only
assert not plateau_stop(curve[:2], next_batch=5000, min_gain=0.003)
assert plateau_stop(curve, next_batch=5000, min_gain=0.004)
def test_repeated_looks_inflate_false_pauses():
from pilot_stats import simulate_pause_rate
# W1: 1,264 gold answers, rolling 200, a look every 50. Pool truly at 82% (above the 80% floor).
one = simulate_pause_rate(0.82, consecutive=1)
two = simulate_pause_rate(0.82, consecutive=2)
assert 0.03 < one < 0.07 and two < 0.02 # ~4.7% -> ~1.2% when two consecutive windows are required
assert simulate_pause_rate(0.74, consecutive=2) > 0.95 # a real drop to 74% is still caught
The round decision turns one calibration round into go, revise or rescope. Agreement and gold accuracy enter as Wilson intervals, so a small round cannot "go" on a lucky point estimate; a concentrated disagreement cluster means revise; diffuse disagreement, or a third round, means rescope.
"""pilot_decide.py - turn one calibration round into go / revise / rescope.
Input: RoundStats measured on the round. Output: (decision, reasons)."""
from dataclasses import dataclass
from pilot_stats import wilson
@dataclass
class RoundStats:
overlap_items: int # items labelled by >= 2 raters in this round
pair_agreement: float # mean over items of the share of rater pairs that chose the same side
gold_seen: int; gold_correct: int
tie_rate: float # share of labels marked tie
top_cluster_share: float # share of disagreements in the largest disagreement cluster (from review)
round_no: int
def decide(r: RoundStats, agree_target: float = 0.70, gold_floor: float = 0.80,
tie_max: float = 0.15, cluster_fixable: float = 0.30, max_rounds: int = 3) -> tuple[str, list[str]]:
why = []
# CI with the item as the unit (pairs inside one item are correlated, so counting pairs would be optimistic)
a_lo, a_hi = wilson(round(r.pair_agreement * r.overlap_items), r.overlap_items)
g_lo, g_hi = wilson(r.gold_correct, r.gold_seen)
if a_lo >= agree_target and g_lo >= gold_floor and r.tie_rate <= tie_max:
return "go", [f"agreement CI low {a_lo:.2f} >= {agree_target}", f"gold CI low {g_lo:.2f} >= {gold_floor}"]
if a_hi < agree_target: why.append(f"agreement CI high {a_hi:.2f} < {agree_target}")
elif a_lo < agree_target: why.append(f"agreement inconclusive ({a_lo:.2f}-{a_hi:.2f})")
if g_hi < gold_floor: why.append(f"gold CI high {g_hi:.2f} < {gold_floor}: raters or gold answers wrong")
if r.tie_rate > tie_max: why.append(f"tie rate {r.tie_rate:.0%} > {tie_max:.0%}: tie definition unclear")
# A concentrated disagreement cluster is a wording problem the guidelines can fix;
# diffuse disagreement after max_rounds is a task problem: rescope.
if r.top_cluster_share >= cluster_fixable and r.round_no < max_rounds:
return "revise", why + [f"top cluster holds {r.top_cluster_share:.0%} of disagreements: add a rule + examples"]
if r.round_no >= max_rounds or r.top_cluster_share < cluster_fixable:
return "rescope", why + ["disagreement is diffuse or rounds exhausted: change the task, population or target"]
return "revise", why
from pilot_decide import RoundStats, decide
def test_w1_round1_revise():
# Round 1 (illustrative): 310 overlapped items, 64% agree, one cluster ("both responses wrong") holds 45%
d, why = decide(RoundStats(310, 0.64, 300, 252, 0.13, 0.45, round_no=1))
assert d == "revise" and any("cluster" in w for w in why)
def test_w1_round2_go():
d, _ = decide(RoundStats(310, 0.76, 300, 258, 0.08, 0.20, round_no=2)) # 76% agree, 86% gold
assert d == "go"
def test_diffuse_disagreement_rescopes():
d, _ = decide(RoundStats(310, 0.58, 300, 255, 0.09, 0.12, round_no=2))
assert d == "rescope"
def test_round_cap():
d, _ = decide(RoundStats(310, 0.645, 300, 250, 0.09, 0.50, round_no=3))
assert d == "rescope"
revise with two reasons: "agreement CI high 0.69 < 0.7" and "top cluster holds 45% of disagreements: add a rule + examples". The 13% tie rate is under the 15% limit, so it is not listed. Round 2 (0.76, gold 258/300, ties 8%) returns go, because the agreement interval's lower bound is 0.71 and gold's is 0.82.A guideline change record, kept next to the guidelines and referenced by version from the spec:
version: v1.2
supersedes: v1.1
round: w1_coding_pref_v1/calibration-1
addresses_cluster: both_responses_fail (45% of round-1 disagreements)
rule: "If both programs fail, prefer the one whose failure is easier to fix. Tie only if neither is closer."
examples: [ex_bf_017, ex_bf_031, ex_bf_044] # become gold items after adjudication
expected_effect: agreement +5 to +10 points; tie rate down
check: round-2 agreement CI lower bound >= 0.70
Debugging tips. If the SPRT never terminates for a rater, their accuracy sits between \(p_0\) and \(p_1\); cap the test (for example at 60 items) and decide by the point estimate. If agreement looks implausibly high, check that overlapped items are assigned to raters independently and that raters cannot see each other's answers. If the plateau rule stops immediately, the fit has too few points; require at least three retrain checkpoints.
In production the pilot's numbers become live quality signals with owners, alerts and decision rules. The dashboard below is the minimum for a preference campaign; each panel is a formula over the label and assignment logs, split by spec version and guideline version.
| Panel | Formula | Threshold / action |
|---|---|---|
| Gold accuracy, pool | correct / gold seen, rolling 200, Wilson band | upper bound < 0.80 in 2 consecutive windows: pause |
| Gold accuracy, per rater | SPRT state per rater (qualification + production) | fail: remove from routing, review last 50 labels |
| Overlap agreement | mean pairwise agreement per overlapped item, by guideline version | drop > 5 points from pilot: open a guideline review |
| Tie rate | ties / labels, by guideline version | > 1.5× pilot rate: check guideline changes |
| Effort | median seconds per label; share under 40 s | rater share under 40 s > 30%: low-effort review |
| Plateau | RM held-out accuracy at each 5,000-item checkpoint; fitted gain of next batch | gain < 0.004: propose stop to the consumer's owner |
| Spend and pace | spend / plan; items / plan | spend > 110% of plan at any point: freeze and re-plan |
Alert rule for the quality pause, in the form most alerting systems accept:
alert: CampaignGoldBelowFloor
expr: wilson_upper(gold_correct_rolling200, gold_seen_rolling200) < spec.quality.gold_accuracy_floor
for: 2 windows # two consecutive 50-answer looks; ~1% false pauses at a true 82% (simulated)
action: pause_routing(campaign_id); page(campaign_owner)
annotations: {runbook: "quality-pause", dashboard: "campaign/{{campaign_id}}/quality"}
Runbook: quality pause fired.
- Confirm the pause is not an artefact: check gold answer keys changed recently (a wrong gold key looks like a quality drop across all raters at once).
- Split gold accuracy by rater. If one to three raters explain the drop, their SPRT state will show it: remove them from routing, resume, and review their recent labels.
- Split by guideline version, item slice and generation checkpoint. A drop confined to new prompts or a new checkpoint is a distribution shift: review whether the guidelines cover it before blaming raters.
- If the drop is pool-wide and not explained above, run a mini calibration round (50 overlapped items) and a disagreement review before resuming.
- Record the decision and, if labels are excluded, the excluded count and spend in the campaign log.
The trade-offs are explicit. Tighter pause rules protect data quality and cost throughput through false pauses; the simulation above gives a defensible setting. The plateau stop can save a quarter of a campaign's labour, as in the W1 illustration, but needs retrains between batches and agreement from the consumer's owner, because stopping early is a decision about the model, not just about the data.
Generating and Routing Samples
A campaign spec says what feedback is wanted. This chapter covers how the platform puts the right model outputs in front of the right person at the right moment. Four decisions run in sequence. The first is which prompts to collect feedback on: the pool they come from, how the topic mix is kept balanced, which difficulty range is useful, whether the outputs come from the policy being trained (on-policy) or from other models (off-policy), and whether the platform should prefer prompts the reward model is unsure about. The second is how responses are generated: which model endpoints and exact checkpoints are called, whether outputs are made ahead of time and buffered or made on demand, how the generator lives within rate limits, and how agentic tasks that run in sandboxes are recorded so a reviewer can replay them. The third is who gets each item: matching skills, giving some items to several raters on purpose, keeping gold items hidden, removing near-duplicates and sharing work fairly. The fourth is how fast the next item appears when a rater asks for one, which depends on queues, buffers, prefetching and warm resources.
These decisions sit between the campaign spec of the previous chapter and the feedback interfaces of the next. They decide whether labels arrive at all, whether they measure the comparison the researcher intended, and how much rater time is wasted waiting. A mistake here, such as an unpinned checkpoint alias or a topic mix that drifts toward whatever the reward model finds confusing, does not show up as an error. It shows up weeks later as a reward model that learned the wrong thing.
W1 is a pairwise preference campaign on coding helpfulness: 20,000 comparisons for a reward model, built from 10,000 coding prompts with two response pairs each. Each pair puts the current checkpoint against a candidate checkpoint, both served from live endpoints. A pre-generated buffer of 2,000 pairs feeds 150 vendor raters, and the time from a rater's request to a rendered pair must be at most 2 s at the median and 5 s at the 95th percentile. 10% of items get three raters, 5% of assignments are gold, so the campaign makes about 25,260 assignments. All W1 numbers in this chapter are illustrative.
This chapter makes the sample path quantitative. Each stage has a small model that a builder can run on a whiteboard. Prompt selection is an allocation problem: how many prompts per topic stratum and difficulty band, and what fraction to pick for informativeness instead of at random. Generation is a throughput problem constrained by rate limits stated in requests, input tokens and output tokens per minute, with a cost per pair. Assignment is a counting and probability problem: label slots from overlap, gold from a target share, the chance that a near-duplicate escapes detection, and how a pull-based queue distributes work among raters who work at different speeds. Latency is a queueing problem in which Little's law, \(L=\lambda W\), links buffer depth, demand and the age of buffered samples, and an outage-coverage argument sets the buffer size.
Recurring W1 quantities (illustrative): 140 raters online at peak, each taking a mean of 4.5 min (270 s) per label, so peak demand is \(140/270 \approx 0.52\) pairs per second, about 1,870 per hour. A coding response is assumed to average 1,200 input and 700 output tokens and to take about 12.5 s at the median; a pair (the slower of two parallel calls) takes about 16 s at the median and 30 s at p95. The buffer holds 2,000 pairs, about 64 minutes of peak demand.
Three results recur. Pre-generation is required whenever generation time exceeds the latency target, and for W1 it exceeds it by about eight times. The buffer is sized by the longest generator disruption it must absorb, not by average demand, and it must be split by the segments the assigner enforces, which raises the safety stock. And in a pull-based queue, work flows to the fastest raters unless the assigner caps it, which interacts badly with low-effort work.
This chapter builds the sample path as four small Python modules, each with tests that were run on the W1 values. w1_select.py deduplicates a prompt pool by normalised prefix, caps prompts per originating account, keeps a difficulty band, fills stratified topic quotas and ranks candidates by reward-model ensemble disagreement under a per-cluster cap. w1_generate.py is an asynchronous generator: two arms pinned to immutable checkpoint digests, token-bucket rate limiting, backoff that honours retry-after under a retry budget, idempotent sample ids and a per-segment buffer with watermarks. w1_assign.py groups near-duplicates with MinHash locality-sensitive hashing, plans overlap slots, and hands out work with skill matching, distinct raters per overlap item, unrepeated gold, a daily fairness cap and expiring leases. w1_ttfs_sim.py is a discrete-event simulation that predicts time to first sample for a given buffer size, generator capacity and outage.
The tests use W1 values throughout: a 10,000-prompt selection with a fixed topic mix, 20,000 items with 2,000 triple-labelled, 5% gold, 150 raters, 140 online at peak, a 2,000-pair buffer and the 2 s / 5 s latency targets. The simulation reproduces Little's law on the buffer to within about 1%.
The modules are plain Python with no external dependencies. The model endpoints are behind one async function so the logic can be tested without a serving stack.
In production the sample path fails in ways that do not raise errors. A checkpoint alias that is repointed overnight silently mixes two candidates in one comparison. An active-selection score drifts the topic mix toward prompts that are confusing for reasons humans cannot resolve either. A pull-based queue gives a quarter of the campaign to a handful of fast, low-effort raters. A shared serving quota turns into a retry storm that empties the buffer for one skill segment while global latency still looks healthy. Each of the four sections below works through one such scenario with numbers, the measurements that separate its causes, the remedy and its cost, and the result that would confirm the fix.
The operating artifacts are an SLO table for time to first sample, segmented by skill; alert rules on buffer coverage (depth divided by current demand), checkpoint digests and 429 share; dashboards for coverage against target mix and per-rater share; and a runbook for generator disruptions. The same panels reappear in the platform-wide operations chapter.
The W1 operating targets used in this chapter (illustrative): time to first sample p50 at most 2 s and p95 at most 5 s, evaluated per 15-minute window and per skill segment; buffer coverage of at least 30 minutes of current demand in every segment; zero pairs from an unpinned checkpoint; no rater above twice the daily fair share. Rater time costs $40 per hour, so an hour with 140 raters blocked costs about $5,600.
Prompt sources and selection: coverage, difficulty, on-policy vs off-policy, active selection
Define. Prompt selection decides which inputs the model will answer for raters to judge. Its input is a prompt pool: records that each carry the prompt text, its source, a topic label, an estimate of difficulty and, for prompts from product traffic, an originating account. Its output is an ordered list of prompts for the campaign, with enough metadata to explain why each was chosen. It acts before generation, and in an iterative campaign it acts again after every batch of labels, because new labels change what is worth asking next.
Motivate. Early preference datasets were collected from whatever prompts were at hand, and the result inherits the skew of the source. Ouyang et al. (2022), describing InstructGPT, drew prompts from API traffic and already had to correct for it: they removed prompts sharing a long common prefix, limited each user ID to 200 prompts, and split training, validation and test sets by user so that no user's prompts leaked across splits. Those three measures (deduplication, per-source caps, leakage-aware splits) are still the starting point. Later work added two more concerns: whether the responses come from the model being trained, and whether some prompts teach the reward model more than others.
Explain end to end. A selector works in five steps.
1. Gather sources. Typical sources are product logs (where consent and policy allow), prompts written by domain experts to cover known gaps, public datasets, synthetic prompts generated by a model from a seed taxonomy, and prompts carried over from red-teaming or failed evaluations. Each source has a known bias: logs over-represent common tasks, expert prompts over-represent what experts find interesting, synthetic prompts repeat their generator's habits.
2. Remove redundancy. Exact and near-duplicate prompts are collapsed, and no single account or template may contribute more than a fixed number. Redundancy wastes labels and, if duplicates straddle a train/evaluation split, inflates evaluation scores.
3. Measure coverage. A taxonomy is a fixed list of topic strata, for coding something like language by task type (write, debug, explain, refactor). A classifier, often a small model, assigns each prompt to a stratum. Coverage means the selected set matches a target share per stratum chosen by the researcher, not the share the pool happens to have. The selector fills a quota per stratum; this is stratified sampling. Its limitation is that the taxonomy only covers what someone thought to list, so a rare but important topic outside it gets no quota.
4. Filter by difficulty. For coding prompts with tests, difficulty can be estimated as one minus the pass rate of the current checkpoint over a few samples. Prompts that every sample passes, or that every sample fails, tend to produce two responses of similar quality, and the comparison carries little information. The same logic appears in RL with verifiable rewards: Yu et al. (2025) over-sample and drop prompts whose sampled responses are all correct or all incorrect, because such groups have zero advantage and contribute no gradient. A difficulty band keeps prompts in between.
5. Choose for informativeness (optional). Active selection prefers prompts whose labels are expected to change the reward model most. The classic form is uncertainty sampling, attributed to Lewis and Gale in the survey by Settles (2009): query the item whose predicted label is closest to a coin flip. A variant called query by committee trains several models and queries where they disagree most. For language models, Muldrew et al. (2024) score prompt and completion pairs by the policy's predictive entropy combined with the certainty of the implicit preference model, and Dwaracherla et al. (2024) represent reward uncertainty with an epistemic neural network and choose comparisons by double Thompson sampling, reporting about a tenfold reduction in queries for the same performance in their experiments. Settles notes the main limitation: the most uncertain item can be an outlier, so pure uncertainty sampling can chase unrepresentative cases.
On-policy versus off-policy. A prompt is only half of a comparison item; the responses matter as much. On-policy data compares outputs of the model currently being trained (or its immediate candidates); off-policy data compares outputs of other models, older checkpoints or humans. A reward model trained on off-policy pairs is scored on a different output distribution than the one it will judge during RL. Touvron et al. (2023) collected Llama 2 preference data in weekly batches with the latest chat models and note that reward model accuracy can degrade quickly without exposure to the new sample distribution; Bai et al. (2022) updated preference models and policies weekly in an "iterated online" mode with fresh human feedback. On the training side, Tajwar et al. (2024) find that preference fine-tuning methods using on-policy sampling or a negative gradient generally beat offline methods. Off-policy data still has uses: it is cheaper, can be prepared in advance, and brings diversity, which is why Llama 3 sampled each pair from two different deployed models.
In the W1 test, a synthetic pool of 50,000 coding prompts loses about 4,000 to prefix deduplication and about 9,000 more to the per-account cap and to the difficulty band (current-checkpoint pass rate between 10% and 90%). Stratified quotas then pick 15,000 candidates that match the target mix exactly (for instance 22% Python writing, 15% systems languages, 10% SQL, although the pool is 35% Python writing). Each candidate gets one cheap probe pair, generated overnight and scored by a five-member reward-model ensemble. The final 10,000 prompts are 30% chosen by ensemble disagreement and 70% at random, and no cluster may exceed 1.5 times its target share. Each selected prompt then gets two pairs from the live current and candidate endpoints. The numbers are illustrative.
Compare and contrast. Random sampling from logs is cheap and unbiased with respect to traffic, but it spends most labels on the commonest tasks. Stratified selection fixes the mix at the cost of a taxonomy that must be maintained. Active selection can save labels, but it makes the dataset a biased sample of the stratum, which matters if the same labels are also used to measure the reward model, and it needs a reward model to exist before the campaign starts.
Connect and decide. A useful mental model is a portfolio: a uniform slice that keeps the data honest, a stratified frame that guarantees coverage, and an active slice that buys information where the current reward model is weakest. The default for a reward-model campaign is: deduplicate and cap per source, fill stratified quotas, apply a difficulty band, take responses from the current policy and its candidates (on-policy), and select at most about a third of items actively, by ensemble disagreement, with a per-cluster cap. Deviate toward more off-policy data when no current policy exists yet or when diversity matters more than distribution match, and toward no active selection when the labels must double as an unbiased evaluation set. The next section takes the selected prompts and turns them into responses.
Prompt selection has three quantitative levers: the allocation across strata, the difficulty band, and the share chosen for informativeness. Each has a back-of-envelope model.
Allocation. Let \(n\) be the number of prompts to select and \(\pi_c\) the target share of stratum \(c\), with \(\sum_c \pi_c = 1\). The quota is \(n_c = \operatorname{round}(n\,\pi_c)\). The target shares come from the researcher, not from the pool: if the pool share \(q_c\) differs from \(\pi_c\), the ratio \(\pi_c/q_c\) is the over- or under-sampling factor for that stratum. If a stratum has fewer than \(n_c\) eligible prompts, the gap must be reported and either filled by commissioning prompts or redistributed; silently filling it from the largest stratum undoes the stratification.
In the W1 test the pool is 35% Python writing but the target is 22%, so Python writing is sampled at \(0.22/0.35 = 0.63\) of its natural rate; SQL is 6% of the pool and 10% of the target, a factor of 1.67. With \(n = 15{,}000\) candidates, the SQL quota is 1,500 and the systems quota (15%) is 2,250. With a 30,000-prompt pool the systems stratum ran short and the quota could not be met; the pool had to grow to 50,000.
Why mid-difficulty and uncertain pairs carry more information. Under the Bradley–Terry model that most reward models use, the probability that response A beats B is \(p = \sigma(\Delta)\), where \(\Delta = r_A - r_B\) is the reward difference and \(\sigma(x) = 1/(1+e^{-x})\) is the logistic function. One binary label \(y\) is a Bernoulli draw with mean \(p\). The Fisher information that one label carries about \(\Delta\) is
\[ I(\Delta) = p\,(1-p), \]which is largest, 0.25, at \(p = 0.5\). At \(p = 0.9\) it is 0.09, so a pair the model already considers lopsided carries about 2.8 times less information per label. This is the formal reason for both the difficulty band and uncertainty sampling. It has one trap. A predicted \(p\) near 0.5 can mean the model does not know (epistemic uncertainty, reducible by labels) or that the two responses are genuinely equally good (aleatoric uncertainty, which labels cannot reduce and which shows up as ties and rater disagreement). A single reward model cannot tell them apart. An ensemble of \(K\) reward heads can: if every head predicts \(p_k \approx 0.5\), the pair is a likely tie; if the heads disagree, for example some at 0.2 and some at 0.8, the disagreement \(\operatorname{sd}(p_1,\dots,p_K)\) measures epistemic uncertainty. The default acquisition score is therefore ensemble disagreement, not closeness to 0.5.
The active share. Let \(w\) be the share of items chosen by acquisition score and \(1-w\) the share chosen uniformly within strata. The uniform slice keeps an unbiased sample for measuring the reward model per stratum and for calibrating rater agreement; the active slice buys information. If the uniform slice must support per-stratum accuracy estimates with standard error \(\le 0.02\) at accuracy near 0.7, each stratum needs about \(0.7 \times 0.3 / 0.02^2 \approx 525\) uniformly chosen comparisons. With seven strata that is about 3,700 comparisons, which sets a floor on \(1-w\).
W1 collects 20,000 comparisons. Seven strata at about 525 uniform comparisons each need about 3,700, or 18%, so \(w\) could in principle go as high as about 0.8. W1 uses \(w = 0.3\) because published gains from active selection were measured in other settings and the uniform slice is also used for rater calibration. The probe pairs cost little: assuming 1,200 input and 700 output tokens per response and illustrative internal prices of $3 and $15 per million tokens, one pair costs about \(2(1{,}200 \times 3 + 700 \times 15)/10^6 \approx \$0.028\); 15,000 probes cost about $420, or about $210 through a batch interface at the 50% discount that OpenAI's Batch API documents for a 24-hour window. At about $4.12 per useful comparison, the probes pay for themselves if active selection raises the value of the 18,400 useful comparisons (about $75,800) by about 0.3% with the batch discount, or about 0.6% at synchronous prices.
On-policy share. Let \(d\) be the number of policy updates between when a pair is generated and when the reward model trained on it is used. Reward-model accuracy on the policy's current outputs tends to fall as \(d\) grows; Touvron et al. (2023) report qualitatively that it "can quickly degrade". There is no general formula for the rate, so the practical model is empirical: hold out a small on-policy test set after each policy update and plot reward-model accuracy against \(d\). The collection cadence is then the largest \(d\) at which accuracy stays within tolerance.
Per-source caps. If a fraction of accounts produce most of the traffic, an uncapped log sample inherits their habits. A cap of \(m\) prompts per account bounds any one account's share at \(m/n\); InstructGPT used \(m = 200\) (Ouyang et al., 2022). For a 10,000-prompt selection that bounds one account at 2%.
| Decision | Default | Deviate when | Cost of the default |
|---|---|---|---|
| Strata | Researcher-set target mix, quota per stratum | The goal is to mirror traffic exactly (then sample proportionally) | A taxonomy and classifier to maintain |
| Difficulty | Band on current pass rate or judged difficulty, e.g. 0.1 to 0.9 | The campaign targets failures specifically (red-teaming, hard-case mining) | A few probe samples per prompt |
| Response source | On-policy: current checkpoint and candidates | No policy yet, or diversity is the goal (mix in other models) | Live endpoints and checkpoint pinning |
| Active share \(w\) | 0.2 to 0.3, ensemble disagreement, per-cluster cap 1.5x | Labels double as an unbiased evaluation set (\(w=0\)) | An ensemble and probe pairs |
| Per-source cap | Fixed cap per account and per template | Single-source expert campaigns | Some popular tasks under-represented |
Table. Prompt-selection defaults for a reward-model preference campaign.
What you would actually do: set the target mix with the researcher, verify every stratum can fill its quota before launch, start with \(w = 0.3\) and an ensemble-disagreement score, and keep the uniform slice large enough for per-stratum accuracy. The next section turns selected prompts into response pairs and puts a price on doing so in advance.
The selector is a pure function from a prompt pool to a selected list plus a report, and a second function that ranks candidates by reward-model ensemble disagreement. Keeping both pure makes them replayable: the same pool, mix and seed always give the same selection, so a dataset can be regenerated and audited.
Data shapes. A Prompt record carries pid, text, source, cluster (from a topic classifier), difficulty in [0, 1] (one minus the current checkpoint's pass rate on hidden tests) and a hashed user. The target mix is a dict from cluster to share. A probe candidate is a tuple (prompt_id, cluster, margins) where margins is a list of \(K\) reward differences \(r_A - r_B\), one per ensemble head, on one cheap probe pair for that prompt.
Steps. select_prompts deduplicates by a hash of the normalised first 120 characters (the "long common prefix" heuristic), enforces the per-user cap, keeps the difficulty band, then fills quotas per cluster and reports any shortfall. rank_by_probe turns each head's margin into \(p_k = \sigma(\Delta_k)\), scores candidates by the standard deviation of the \(p_k\) (ensemble disagreement), takes the top w_active share subject to a per-cluster cap, and fills the rest uniformly at random under the same cap.
"""Prompt selection for W1: dedup, per-user cap, difficulty band, coverage quotas, active ranking."""
from dataclasses import dataclass
from collections import Counter, defaultdict
import hashlib, math, random, re, statistics
@dataclass(frozen=True)
class Prompt:
pid: str
text: str
source: str # 'prod_logs' | 'expert' | 'public' | 'synthetic'
cluster: str # topic label from a classifier, e.g. 'python/debug'
difficulty: float # 0..1: 1 - pass rate of the current checkpoint on hidden tests
user: str # hashed originating account ('' for non-user sources)
def prefix_key(text: str, n: int = 120) -> str:
"""Normalised-prefix key: prompts sharing a long common prefix collapse to one."""
t = re.sub(r"\s+", " ", text.lower()).strip()
return hashlib.sha1(t[:n].encode()).hexdigest()
def select_prompts(pool, n, target_mix, band=(0.10, 0.90), max_per_user=200, seed=0):
"""Return n prompts whose cluster shares follow target_mix (dict cluster->share).
Steps: exact/prefix dedup -> per-user cap -> difficulty band -> stratified quota fill."""
rng = random.Random(seed)
seen, per_user, kept = set(), Counter(), []
for p in pool:
k = prefix_key(p.text)
if k in seen:
continue
seen.add(k)
if p.user and per_user[p.user] >= max_per_user:
continue
if not (band[0] <= p.difficulty <= band[1]):
continue # all-pass or all-fail: little comparative signal
per_user[p.user] += 1
kept.append(p)
by_cluster = defaultdict(list)
for p in kept:
by_cluster[p.cluster].append(p)
quotas = {c: round(n * s) for c, s in target_mix.items()}
out, shortfall = [], 0
for c, q in quotas.items():
cand = by_cluster.get(c, [])
rng.shuffle(cand)
out += cand[:q]
shortfall += max(0, q - len(cand))
if shortfall: # refill from the largest leftover clusters, report it
rest = [p for c, ps in by_cluster.items() for p in ps[quotas.get(c, 0):]]
rng.shuffle(rest)
out += rest[:shortfall]
return out[:n], {"after_dedup": len(seen), "kept": len(kept), "shortfall": shortfall}
def p_a_beats_b(margin: float) -> float:
"""Bradley-Terry: P(A > B) = sigmoid(r_A - r_B)."""
return 1.0 / (1.0 + math.exp(-margin))
def probe_scores(margins):
"""margins: reward differences r_A - r_B from K ensemble members on one probe pair for a prompt.
Returns (aleatoric_like, epistemic): mean-p closeness to 0.5, and ensemble disagreement."""
ps = [p_a_beats_b(m) for m in margins]
pbar = sum(ps) / len(ps)
return 4 * pbar * (1 - pbar), statistics.pstdev(ps)
def rank_by_probe(cands, k, w_active=0.3, cluster_cap=1.5, target_mix=None, seed=0):
"""cands: list of (prompt_id, cluster, margins) where margins come from scoring one cheap
probe pair per prompt with a K-member reward-model ensemble. Pick k prompts: a w_active share
by ensemble disagreement, the rest uniformly at random; no cluster above cluster_cap x target."""
rng = random.Random(seed)
cap = {c: math.ceil(k * s * cluster_cap) for c, s in (target_mix or {}).items()}
used, taken, out = Counter(), set(), []
def ok(c): return c not in cap or used[c] < cap[c]
scored = sorted(cands, key=lambda x: -probe_scores(x[2])[1])
for pid, c, _ in scored:
if len(out) >= round(k * w_active): break
if ok(c): out.append(pid); taken.add(pid); used[c] += 1
rest = [x for x in cands if x[0] not in taken]
rng.shuffle(rest)
for pid, c, _ in rest:
if len(out) >= k: break
if ok(c): out.append(pid); used[c] += 1
return out, used
The test builds a skewed synthetic pool, selects 15,000 candidates against the W1 target mix, then ranks them to 10,000. In the synthetic data the ensemble disagrees most on the other cluster (shell scripts, regular expressions, configuration files), so the active slice pulls toward it; the cap must hold.
import random
from collections import Counter
from w1_select import Prompt, select_prompts, rank_by_probe, probe_scores
MIX = {"python/write": .22, "python/debug": .18, "js-ts/write": .12, "js-ts/debug": .08,
"sql": .10, "systems": .15, "other": .15}
def synth_pool(n=50000, seed=1):
rng = random.Random(seed)
skew = {"python/write": .35, "python/debug": .20, "js-ts/write": .14, "js-ts/debug": .06,
"sql": .06, "systems": .07, "other": .12} # production logs over-represent Python
cs, ws = zip(*skew.items())
pool = []
for i in range(n):
c = rng.choices(cs, ws)[0]
txt = f"[{c}] task {rng.randrange(20000)} variant {rng.randrange(3)}" # forces some prefix dups
user = f"u{rng.randrange(400)}" if rng.random() < .7 else ""
pool.append(Prompt(f"p{i}", txt, "prod_logs" if user else "expert", c, rng.random(), user))
return pool
def test_w1_selection():
sel, stats = select_prompts(synth_pool(), 15000, MIX) # 1.5x candidates for active ranking
assert len(sel) == 15000 and len({p.pid for p in sel}) == 15000
share = Counter(p.cluster for p in sel)
for c, s in MIX.items(): # coverage within 1 point of target
assert abs(share[c] / 15000 - s) < 0.01, (c, share[c])
assert all(0.10 <= p.difficulty <= 0.90 for p in sel)
assert max(Counter(p.user for p in sel if p.user).values()) <= 200
print("selection", stats, dict(share))
def test_active_ranking_respects_caps():
rng = random.Random(2)
sel, _ = select_prompts(synth_pool(), 15000, MIX)
cands = []
for p in sel: # one probe pair per candidate prompt, 5 RM heads
spread = 0.9 if p.cluster == "other" else 0.2 # the ensemble disagrees most on 'other'
base = rng.gauss(0, 1.5)
cands.append((p.pid, p.cluster, [base + rng.gauss(0, spread) for _ in range(5)]))
out, used = rank_by_probe(cands, 10000, w_active=0.3, cluster_cap=1.5, target_mix=MIX)
assert len(out) == 10000 and len(set(out)) == 10000
assert used["other"] <= 10000 * 0.15 * 1.5 + 1 # cap held even though 'other' tops the ranking
a, e = probe_scores([0.0, 0.0, 0.0]); assert abs(a - 1) < 1e-9 and e == 0 # tie-like, no disagreement
print("active", dict(used))
if __name__ == "__main__":
test_w1_selection(); test_active_ranking_respects_caps(); print("OK")
Output of the run:
selection {'after_dedup': 45946, 'kept': 36866, 'shortfall': 0} {'python/write': 3300, 'python/debug': 2700, 'js-ts/write': 1800, 'js-ts/debug': 1200, 'sql': 1500, 'systems': 2250, 'other': 2250}
active {'other': 2128, 'sql': 929, 'js-ts/debug': 749, 'js-ts/write': 1094, 'python/write': 2015, 'python/debug': 1686, 'systems': 1399}
OK
The ranked 10,000 prompts put 21.3% in other against a 15% target: the active slice pulled it up, and the 1.5x cap (22.5%) bounded the pull. SQL fell to 9.3% and JS/TS debugging to 7.5%, below their 10% and 8% targets, because the random slice cannot fully compensate. If exact shares matter, run the cap in both directions (a floor of, say, 0.8x target) or fill the uniform slice by quota instead of at random.
Debugging tips. If the shortfall is non-zero, print eligible counts per cluster after each filter; the difficulty band is usually the culprit for rare clusters. If the selection changes between runs, look for an unseeded random generator or iteration over a set. If deduplication removes far more than expected, the prefix length is too short for templated prompts that share a long instruction header; hash the prompt after stripping the shared template, or switch to the near-duplicate grouping used in the assignment section. Before trusting the acquisition score, plot ensemble disagreement against closeness to 0.5 per cluster: a cluster that is high on closeness but low on disagreement is full of likely ties.
Selection problems in production are slow and silent: nothing fails, but the mix of what raters see drifts away from what the researcher intended, and the cost appears as wasted labels or a reward model that is strong where it was already strong. The controls are a coverage dashboard, alert rules on drift, and a short runbook.
Metrics and dashboard. Four panels cover most failures. (1) Coverage: share of served assignments per cluster over a rolling window of 1,000 assignments, against target, as a bar pair per cluster. (2) Agreement and ties per cluster: pairwise agreement on overlap items and tie rate, which reveal clusters where humans cannot resolve the comparison. (3) Uncertainty decomposition: per cluster, mean ensemble disagreement and mean closeness to 0.5 of the selected items. (4) On-policy freshness: policy updates between generation and label, \(d\), and reward-model accuracy on a fresh on-policy hold-out by \(d\).
# alert rules (Prometheus-style; metric names are this platform's own)
- alert: ClusterShareDrift
expr: max by (campaign, cluster) (served_share_rolling1000 / target_share) > 1.5
or min by (campaign, cluster) (served_share_rolling1000 / target_share) < 0.67
for: 30m
- alert: LowAgreementCluster
expr: overlap_agreement_by_cluster < (campaign_overlap_agreement - 0.10)
for: 2h # needs at least ~100 overlap items in the cluster to be meaningful
- alert: StaleOnPolicy
expr: policy_updates_since_generation_p50 > 1
Symptom. After the pilot, the researcher raises the active share from 0.3 to 0.6 and removes the cluster cap to speed up learning. Over the next 4,000 assignments the coverage panel shows the other cluster at 38% against a 15% target. Overlap agreement in that cluster is 58% against 72% for the campaign, and its tie rate is 19% against the campaign's 8%.
Separating causes. Three explanations fit: the cluster is genuinely hard for the reward model (labels are valuable), raters lack the skill (a routing problem), or the items are near-ties (labels are noise). The uncertainty panel separates them. In this variant the acquisition score had been left at closeness to 0.5 from the pilot configuration, not the default ensemble disagreement. For other, closeness was 0.93 while ensemble disagreement was 0.04, the lowest of any cluster: the heads agree that these pairs are about equal. The raters with the strongest shell and regex skills showed the same low agreement, which rules out a skill gap.
Remedy. Switch the score to ensemble disagreement, restore the 1.5x cap, return \(w\) to 0.3, and keep the already-collected labels but give the other excess a separate tag so the reward-model trainer can down-weight it. Cost: about \(4{,}000 \times (0.38-0.15) \approx 920\) assignments went to the excess, about $2,760 of rater time at about $3.00 per assignment ($75,780 / 25,260); nothing is relabelled.
Validation. On the next 4,000 assignments, the other share should return to 15% to 22.5% and its agreement toward the campaign mean. The decisive test is the reward model's accuracy on the uniform hold-out per cluster after retraining with and without the tagged excess. If accuracy on other improves materially with the excess included, the near-tie hypothesis is weakened and the excess was useful; if it is unchanged, the hypothesis holds and closeness-to-0.5 should be banned as an acquisition score for this campaign type.
Runbook: coverage drift. 1. Confirm the drift on the coverage panel over at least 1,000 assignments. 2. Check whether the target mix or acquisition settings changed (campaign config history). 3. If the drifting cluster has low agreement, compare ensemble disagreement with closeness to 0.5; if disagreement is low, pause the active slice. 4. If a cluster is under target, check its eligible pool after filters; if the pool is exhausted, commission prompts or accept the shortfall explicitly. 5. Tag affected items so downstream training can weight or exclude them. 6. Record the decision in the campaign log.
Cost and trade-offs. A per-cluster cap gives up some of the active-selection gain in exchange for predictable coverage; with a 1.5x cap no cluster can exceed one and a half times its target share, whatever the score does. A large uniform slice costs information but provides the hold-out that makes every other diagnosis possible. On-policy freshness costs live endpoints and the pinning discipline of the next section.
The generation path: live model endpoints, which checkpoints, pre-generation buffers vs on-demand, agentic transcripts and sandboxes
Define. The generation path turns a selected prompt into the model outputs a rater will judge, with a record of exactly how they were produced. It receives a work item (prompt id, sampling seed, the campaign's arm definitions) and produces a sample: the responses, the immutable identity of the checkpoint that produced each one, the sampling parameters, token counts, timing and validation results. For agentic tasks the sample is a transcript: every step the agent took, every tool call and every tool output, plus the identity of the environment it ran in.
Motivate. In early preference datasets, responses were generated once, offline, and stored as files; the dataset was the files. That breaks down for on-policy campaigns, where the policy changes every few days and the comparison must involve the current checkpoint and its candidates. The platform therefore calls live model endpoints: serving deployments that load a checkpoint and answer requests, either a provider's public API or an internal research serving stack built on engines such as vLLM or SGLang. Live endpoints add three problems that files did not have: they can change without the client noticing, they are rate-limited, and they are slow relative to a human's patience.
Explain end to end. One work item goes through six steps.
1. Resolve the arms. An arm is one side of the comparison, for example "current checkpoint at temperature 0.8". Each arm names an endpoint and a checkpoint. The checkpoint must be an immutable identifier, such as a content digest, not an alias like "candidate-latest" that an operator can repoint. This is checkpoint pinning. Without it, a comparison silently becomes a comparison between different models halfway through the campaign.
2. Wait for rate-limit capacity. Endpoints limit how fast a client may call them. Anthropic's API documentation, for example, states limits in requests per minute, input tokens per minute and output tokens per minute, enforced with a token bucket: capacity refills continuously up to a maximum instead of resetting each minute, and an over-limit call gets an HTTP 429 response that may carry a retry-after header (Anthropic rate limits). The generator keeps its own token bucket per endpoint so that it rarely hits the server's limit.
3. Call both arms. The two calls run in parallel, so a pair takes as long as the slower response. A sampling seed and fixed parameters make the request reproducible where the serving stack supports it. When two samples share a long prompt prefix on the same checkpoint, prefix caching in the serving engine can skip recomputing it; SGLang's RadixAttention is one implementation of such KV-cache reuse (Zheng et al., 2023).
4. Retry carefully. A failed call is retried after a wait that grows with each attempt and includes randomness (jitter) so that many clients do not retry in lockstep, and never sooner than retry-after. A retry budget limits retries to a small share of total calls; without one, retries add load exactly when the endpoint is overloaded.
5. Validate. A validator checks each response before it can reach a rater: the checkpoint the endpoint reports serving matches the pin; the response is not empty, truncated at the token limit or an error message; the two responses are not identical; content filters for material raters should not see have run. The validator also randomises which response appears on the left, so position cannot correlate with arm.
6. Store and enqueue. The sample gets an idempotent id, a hash of the prompt id, both checkpoints, the sampling parameters and the seed, so a retried job cannot create a second copy. It then goes to the buffer.
When to generate. There are three modes. Full pre-generation creates every sample before raters start, often through a batch interface that trades latency for price (OpenAI documents a 50% discount with a 24-hour completion window: OpenAI Batch API). A rolling buffer keeps a bounded stock of ready samples and refills it continuously. On-demand generation calls the model when the rater asks, usually streaming tokens to the screen as they arrive. On-demand is unavoidable for live multi-turn sessions, where the rater's own message is the prompt. For judging finished responses, a buffer is usually the right choice because a full response takes seconds to tens of seconds to generate.
Agentic transcripts and sandboxes. An agentic sample is produced by running an agent in a sandbox: an isolated environment (container or microVM) started from a fixed snapshot, with a network policy and resource limits. The SWE-bench harness illustrates the structure: it layers base images (language tooling), environment images (per-repository dependencies) and instance images (per task), and lets operators choose how many layers to cache, trading roughly 100 GB for the default against about 2,000 GB for caching every instance (SWE-bench harness docs). MicroVMs such as Firecracker start in about 100 to 150 ms with a few megabytes of overhead each (Agache et al., 2020, as summarised by Colyer). During the run a recorder stores each tool call and its output. Reviewers then see a replay from the recording, not a re-execution: re-running the agent would produce different timings, network responses and sometimes different actions, and the reviewer would be judging a different run.
Each W1 item is a pair from the current checkpoint (pinned digest 9f1c) and the candidate (pinned digest 4be0), both at temperature 0.8. A coding response is assumed to take about 0.8 s to the first token and then about 700 output tokens at about 60 tokens per second, about 12.5 s in total; the pair takes about 16 s at the median and 30 s at p95. Because that is about eight times the 2 s target, W1 uses a rolling buffer of 2,000 pairs. All numbers are illustrative.
W2 transcripts average 60 steps and about 25,000 tokens. Each was produced in a sandbox started from a pinned image, and every tool output was recorded. Experts mark the first failing step and write a corrected continuation; the interface replays recorded tool outputs at each step, which is what the W2 requirement "state replay of tool outputs" means in practice.
Compare and contrast. Stored files are simple and reproducible but cannot follow the policy. Live endpoints follow the policy but introduce drift, rate limits and latency, which pinning, rate limiting and buffering then have to absorb. For agentic data, re-execution looks attractive because it needs no recorder, but it gives up the one property review depends on: that the reviewer sees the run that was actually scored.
Connect and decide. The mental model is a small factory with a strict bill of materials: every output names the exact machine (checkpoint), settings (sampling parameters) and raw materials (prompt, sandbox image) it came from. The default is pinned digests, a client-side token bucket per endpoint, jittered backoff under a retry budget, a validator that rejects any sample whose served checkpoint differs from the pin, a rolling buffer for judged responses, and record-and-replay for agentic runs. Deviate to full pre-generation when the arms are fixed for the whole campaign and price matters, and to on-demand streaming when the rater writes the prompt. The next section decides who receives each sample.
The generation path is sized by four numbers: time per sample, demand, rate limits, and cost. This level works each one and then compares the three generation modes.
Time per sample. For one response, \(T_{\text{resp}} \approx T_{\text{first}} + n_{\text{out}} / r_{\text{dec}}\), where \(T_{\text{first}}\) is the time to the first token (queueing plus prompt processing), \(n_{\text{out}}\) the number of output tokens and \(r_{\text{dec}}\) the decode speed in tokens per second for one stream. A pair generated in parallel takes \(T_{\text{pair}} = \max(T_A, T_B)\), and the maximum of two noisy times is noticeably worse than either: its median is higher than the median of one, and its tail is heavier.
With \(T_{\text{first}} = 0.8\) s, \(n_{\text{out}} = 700\) and \(r_{\text{dec}} = 60\) tokens/s, \(T_{\text{resp}} \approx 0.8 + 11.7 = 12.5\) s. Modelling each response time as lognormal with median 12.5 s and log-standard-deviation 0.45 (an assumption), a simulation of 100,000 pairs gives \(T_{\text{pair}}\) median 16.0 s, mean 17.3 s and p95 30.2 s. The latency target is 2 s, so on-demand generation misses it by a factor of about eight at the median.
Demand and in-flight work. Let \(N\) be the raters online and \(\bar t\) the mean time per label. The rate at which raters consume items is \(\lambda = N/\bar t\). Little's law, \(L = \lambda W\) (Little, 1961; 2011 retrospective), says that the average number of items in a stable system equals the arrival rate times the average time each spends inside. Applied to the generator, the number of pair generations in flight is \(L_{\text{gen}} = \lambda\, \bar T_{\text{pair}}\). The generator must allow at least that many concurrent jobs, plus headroom to refill after a disruption.
With 140 raters online and \(\bar t = 270\) s, \(\lambda = 0.52\) pairs/s. In-flight generations: \(0.52 \times 17.3 \approx 9\) pairs, that is 9 calls to each endpoint. W1 allows 12 concurrent pairs, a capacity of \(12/17.3 \approx 0.69\) pairs/s, about 1.34 times peak demand. This sizing is conservative: 5% of assignments are gold (stored, never generated) and each overlap pair serves three slots, so only \(20{,}000/25{,}260 \approx 79\%\) of assignments need a fresh pair.
Rate limits. Per endpoint, the generator needs \(\lambda\) requests per second, \(\lambda\,\bar n_{\text{in}}\) input tokens per second and \(\lambda\,\bar n_{\text{out}}\) output tokens per second. Multiply by 60 for per-minute limits. On some APIs cached input tokens do not count toward the input limit; Anthropic's documentation states that only uncached input and cache-creation tokens count toward ITPM.
At generator capacity (0.69 pairs/s) each arm's endpoint needs about 41 requests per minute, \(0.69 \times 1{,}200 \times 60 \approx 49{,}700\) input tokens per minute and \(0.69 \times 700 \times 60 \approx 29{,}000\) output tokens per minute. An internal serving pool shared with other jobs must reserve at least this for the campaign; if another job can consume the same quota, the campaign's real capacity is whatever is left.
Retry amplification. If each attempt fails with probability \(f\) and the client retries immediately up to \(k\) attempts, the expected attempts per work item are \(\sum_{i=0}^{k-1} f^i = (1-f^k)/(1-f)\). At \(f = 0.5\) and \(k = 5\) that is 1.94: the client nearly doubles its request rate exactly when the endpoint is refusing requests, which pushes \(f\) higher. A retry budget caps attempts per item at \(1+\beta\) on average, with \(\beta\) typically 0.1, which breaks this feedback loop.
Cost. Per pair, \(C = 2(\bar n_{\text{in}} p_{\text{in}} + \bar n_{\text{out}} p_{\text{out}})\) with per-token prices \(p\).
At illustrative internal prices of $3 and $15 per million input and output tokens, \(C \approx 2(1{,}200 \times 3 + 700 \times 15)/10^6 \approx \$0.028\). All 20,000 pairs cost about $560, under 1% of the $75,780 labour budget. Flushing a full 2,000-pair buffer costs about $56. Generation cost does not decide the mode; latency, freshness and flexibility do.
Staleness. By Little's law again, the mean age of a buffered sample when served is \(W_{\text{buf}} = B/\lambda\) for a full buffer of size \(B\). Age matters only if the arms change; with pinned arms, an hour-old pair is as valid as a new one. It matters a great deal if the campaign swaps the candidate, because every buffered sample becomes invalid at once.
| Mode | Latency to rater | Freshness | Cost | Waste on change | Use when |
|---|---|---|---|---|---|
| Full pre-generation (batch) | Hit only | Fixed at start | Lowest (batch discount) | All unserved samples | Arms fixed for the whole campaign; off-policy or one-shot datasets |
| Rolling buffer | Hit unless the buffer empties | Mean age \(B/\lambda\) | Synchronous price | At most \(B\) samples | On-policy pairs, candidates may change, active selection between batches |
| On-demand, streamed | Time to first token, then reading speed | Exact | Synchronous price, no waste | None | Live multi-turn sessions; very low volume |
Table. Generation modes compared. \(B\) is buffer size, \(\lambda\) demand.
Agentic transcripts: replay versus re-execution. Suppose each step of an agent run has a small probability \(q\) of producing a different tool output when re-executed (a timestamp, a network response, a test's timing). The probability that a 60-step run reproduces exactly is \((1-q)^{60}\): 0.55 at \(q = 0.01\), 0.05 at \(q = 0.05\). Re-execution is therefore not a viable way to show a reviewer the run that was scored; recording is. Storage is small: a W2 transcript of about 25,000 tokens is on the order of 100 KB of text, so 2,000 transcripts are about 200 MB before tool artifacts.
What you would actually do: pin by digest and reject mismatches, set the client token bucket to the campaign's reserved share of each endpoint, cap retries at 10%, size generator concurrency at \(1.3\) to \(1.5\) times \(\lambda \bar T_{\text{pair}}\), use a rolling buffer for judged on-policy pairs, and record every agentic run. The buffer size itself is derived in the latency section.
The generator has five parts: arm definitions with pinned digests, a token bucket per endpoint, a call wrapper with jittered backoff and a retry budget, a pair builder that randomises position and assigns an idempotent id, and a per-segment buffer with low and high watermarks that a refill loop keeps topped up. A segment is a partition of the buffer by the property the assigner matches on (here, programming-language skill), so that every rater population has its own stock. A watermark is a threshold: when a segment drops below its low watermark, the refiller fills it to the high watermark.
Configuration. The campaign's generation block is declarative and is validated at launch: aliases are rejected, and the client-side limits must not exceed the reservation on each endpoint.
# w1_generation.yaml
campaign: w1-coding-pairs
arms:
- name: current
endpoint: serve-a
checkpoint: ckpt-sha256:9f1c # immutable digest; aliases such as 'latest' fail validation
sampling: {temperature: 0.8, max_tokens: 2048}
- name: candidate
endpoint: serve-b
checkpoint: ckpt-sha256:4be0
sampling: {temperature: 0.8, max_tokens: 2048}
limits: # client side, at or below the campaign's reservation
serve-a: {rpm: 45, itpm: 55000, otpm: 32000}
serve-b: {rpm: 45, itpm: 55000, otpm: 32000}
retry: {max_attempts: 5, budget: 0.10, honour_retry_after: true, jitter: full}
concurrency: 12 # about 1.34x of lambda x mean pair time at peak
buffer:
segments: # watermarks scaled to each segment's share of demand
python: {low: 600, high: 800}
js-ts: {low: 300, high: 400}
sql: {low: 150, high: 200}
systems: {low: 225, high: 300}
other: {low: 225, high: 300}
validate: [checkpoint_digest, non_empty, not_truncated, not_identical, content_filter]
The generator itself, with the endpoint behind one async function call(arm, prompt_text) that returns the text, the checkpoint the server reports and the output token count:
"""Rolling pre-generation buffer for W1 with pinned checkpoints, token-bucket rate limits,
retry-after aware backoff with a retry budget, and idempotent sample ids."""
import asyncio, hashlib, json, random, time
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Arm: # one side of the comparison, pinned to an immutable checkpoint
name: str # 'current' | 'candidate'
endpoint: str
checkpoint: str # immutable digest, never an alias like 'latest'
temperature: float = 0.8
max_tokens: int = 2048
class RateLimited(Exception):
def __init__(self, retry_after: float): self.retry_after = retry_after
class TokenBucket:
"""Capacity refills continuously at rate/sec (same shape as API RPM/OTPM limits)."""
def __init__(self, rate_per_s: float, burst: float):
self.rate, self.cap, self.tokens, self.t = rate_per_s, burst, burst, time.monotonic()
async def take(self, n: float = 1.0):
while True:
now = time.monotonic()
self.tokens = min(self.cap, self.tokens + (now - self.t) * self.rate); self.t = now
if self.tokens >= n: self.tokens -= n; return
await asyncio.sleep((n - self.tokens) / self.rate)
def sample_id(prompt_id: str, a: Arm, b: Arm, seed: int) -> str:
"""Same inputs -> same id, so a retried or duplicated job can never create a second pair."""
key = json.dumps([prompt_id, a.checkpoint, a.temperature, b.checkpoint, b.temperature, seed])
return hashlib.sha256(key.encode()).hexdigest()[:16]
@dataclass
class Generator:
call: callable # async (arm, prompt_text) -> dict(text, checkpoint, out_tokens)
arms: tuple
rpm: dict # endpoint -> TokenBucket
max_attempts: int = 5
retry_budget: float = 0.10 # retries may add at most 10% to request volume
stats: dict = field(default_factory=lambda: {"calls": 0, "retries": 0, "rejected_ckpt": 0})
async def _one(self, arm: Arm, text: str):
for attempt in range(self.max_attempts):
await self.rpm[arm.endpoint].take()
self.stats["calls"] += 1
try:
r = await self.call(arm, text)
if r["checkpoint"] != arm.checkpoint: # endpoint served something else: refuse it
self.stats["rejected_ckpt"] += 1
raise RuntimeError(f"checkpoint drift on {arm.name}: {r['checkpoint']}")
return r
except RateLimited as e:
if self.stats["retries"] >= self.retry_budget * max(self.stats["calls"], 20):
raise # budget spent: fail fast, do not amplify
self.stats["retries"] += 1
backoff = max(e.retry_after, random.uniform(0, 0.01 * 2 ** attempt)) # full jitter
await asyncio.sleep(backoff)
raise TimeoutError("attempts exhausted")
async def make_pair(self, prompt_id: str, text: str, seed: int):
a, b = self.arms
ra, rb = await asyncio.gather(self._one(a, text), self._one(b, text))
flip = random.Random(seed).random() < 0.5 # randomise left/right at generation time
left, right = (rb, ra) if flip else (ra, rb)
return {"sample_id": sample_id(prompt_id, a, b, seed), "prompt_id": prompt_id,
"left": left, "right": right, "left_arm": b.name if flip else a.name,
"created": time.time()}
class Buffer:
"""Per-segment FIFO with low/high watermarks; the refiller keeps every segment between them."""
def __init__(self, low: dict, high: dict):
self.low, self.high, self.q, self.ids = low, high, {s: [] for s in low}, set()
def depth(self, seg): return len(self.q[seg])
def put(self, seg, item):
if item["sample_id"] in self.ids: return False # idempotent insert
self.ids.add(item["sample_id"]); self.q[seg].append(item); return True
def pop(self, seg): return self.q[seg].pop(0) if self.q[seg] else None
def deficits(self):
return {s: self.high[s] - len(q) for s, q in self.q.items() if len(q) < self.low[s]}
async def refill(buf: Buffer, gen: Generator, prompts: dict, concurrency: int = 8, rounds: int = 3):
"""prompts: segment -> iterator of (prompt_id, text, seed). Fill every segment below low to high.
Failed jobs are not retried inline; the next round (or the next refill tick) tries new work."""
sem = asyncio.Semaphore(concurrency) # Little's law: in-flight = rate x latency
async def job(seg, pid, text, seed):
async with sem:
try: buf.put(seg, await gen.make_pair(pid, text, seed))
except (RateLimited, RuntimeError, TimeoutError): pass # counted in stats; prompt re-queued upstream
for _ in range(rounds):
tasks = []
for seg, need in buf.deficits().items():
for _ in range(need):
pid, text, seed = next(prompts[seg])
tasks.append(job(seg, pid, text, seed))
if not tasks: return
await asyncio.gather(*tasks)
The test uses a fake endpoint that sleeps a few milliseconds instead of 12.5 s, returns 429 with a given probability, and can simulate an alias being repointed after a number of calls.
import asyncio, random
from w1_generate import Arm, Generator, Buffer, TokenBucket, RateLimited, refill, sample_id
CUR = Arm("current", "serve-a", "ckpt-sha256:9f1c")
CAND = Arm("candidate", "serve-b", "ckpt-sha256:4be0")
def fake_endpoint(p429=0.15, drift_after=None):
n = {"b": 0}
async def call(arm, text):
await asyncio.sleep(random.uniform(0.001, 0.004)) # stand-in for ~12 s generation
if random.random() < p429: raise RateLimited(retry_after=0.002)
ck = arm.checkpoint
if arm.name == "candidate":
n["b"] += 1
if drift_after and n["b"] > drift_after: ck = "ckpt-sha256:77aa" # alias silently repointed
return {"text": f"{arm.name}:{text}", "checkpoint": ck, "out_tokens": 700}
return call
def prompt_stream(seg):
i = 0
while True:
yield (f"{seg}-p{i}", f"prompt {i}", i); i += 1
def run(drift_after=None, p429=0.15):
random.seed(0)
buf = Buffer(low={"python": 60, "rust": 20}, high={"python": 120, "rust": 40})
gen = Generator(fake_endpoint(p429, drift_after), (CUR, CAND),
{"serve-a": TokenBucket(5000, 50), "serve-b": TokenBucket(5000, 50)})
asyncio.run(refill(buf, gen, {s: prompt_stream(s) for s in ("python", "rust")}))
return buf, gen
def test_fill_and_pin():
buf, gen = run(p429=0.05)
assert buf.depth("python") >= 60 and buf.depth("rust") >= 20 # every segment back above low
items = buf.q["python"] + buf.q["rust"]
assert all({i["left"]["checkpoint"], i["right"]["checkpoint"]} == {CUR.checkpoint, CAND.checkpoint} for i in items)
assert gen.stats["retries"] <= 0.10 * gen.stats["calls"] + 1
left_cand = sum(i["left_arm"] == "candidate" for i in items) / len(items)
assert 0.35 < left_cand < 0.65 # position randomised
print("filled", buf.depth("python"), buf.depth("rust"), gen.stats)
def test_drift_is_rejected():
buf, gen = run(drift_after=30, p429=0.0)
assert gen.stats["rejected_ckpt"] > 0
assert all(i["left"]["checkpoint"] != "ckpt-sha256:77aa" and i["right"]["checkpoint"] != "ckpt-sha256:77aa"
for s in buf.q for i in buf.q[s])
print("drift rejected", gen.stats["rejected_ckpt"])
def test_retry_budget_caps_amplification():
buf, gen = run(p429=0.5) # endpoint rejecting half of calls
assert gen.stats["retries"] <= 0.10 * gen.stats["calls"] + 1 # no retry storm
print("under 50% 429s:", gen.stats, "depths", buf.depth("python"), buf.depth("rust"))
def test_idempotent_ids():
assert sample_id("p1", CUR, CAND, 7) == sample_id("p1", CUR, CAND, 7)
assert sample_id("p1", CUR, CAND, 7) != sample_id("p1", CUR, CAND, 8)
b = Buffer({"s": 1}, {"s": 2}); it = {"sample_id": "x"}
assert b.put("s", it) and not b.put("s", it)
if __name__ == "__main__":
test_fill_and_pin(); test_drift_is_rejected(); test_retry_budget_caps_amplification(); test_idempotent_ids(); print("OK")
filled 120 40 {'calls': 337, 'retries': 17, 'rejected_ckpt': 0}
drift rejected 390
under 50% 429s: {'calls': 656, 'retries': 66, 'rejected_ckpt': 0} depths 67 23
OK
Three behaviours are verified. Under 5% rate limiting every segment refills. When the candidate endpoint starts serving a different digest, every affected response is rejected and none reaches the buffer (the 390 rejections show the refiller kept trying; production code should open a circuit breaker and page after a handful). When half of all calls are refused, retries stay at 10% of calls and the buffer refills only partly: the generator degrades instead of amplifying the overload.
Record and replay for agentic runs. The recorder wraps the real tools during the run; the replayer serves recorded outputs in order and raises on any mismatch.
"""Record tool I/O during an agentic run, then replay it for review without re-executing (W2)."""
import hashlib, json
from dataclasses import dataclass, field
def h(obj) -> str:
return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest()[:12]
@dataclass
class Transcript:
task_id: str
sandbox_image: str # immutable snapshot digest the run started from
policy_checkpoint: str # immutable digest of the agent model
steps: list = field(default_factory=list) # {step, tool, args, args_hash, output, output_hash}
class Recorder:
"""Wraps real tools. Every call is executed once and its output stored with hashes."""
def __init__(self, tr: Transcript, tools: dict): self.tr, self.tools = tr, tools
def call(self, tool: str, **args):
out = self.tools[tool](**args)
self.tr.steps.append({"step": len(self.tr.steps), "tool": tool, "args": args,
"args_hash": h([tool, args]), "output": out, "output_hash": h(out)})
return out
class Divergence(Exception): pass
class Replayer:
"""Serves recorded outputs in order. A request that does not match the recording is a divergence:
the UI shows the recorded run, and a corrected continuation must branch from an explicit step."""
def __init__(self, tr: Transcript): self.tr, self.i = tr, 0
def call(self, tool: str, **args):
if self.i >= len(self.tr.steps): raise Divergence(f"no recorded step {self.i}")
s = self.tr.steps[self.i]
if s["args_hash"] != h([tool, args]):
raise Divergence(f"step {self.i}: expected {s['tool']}({s['args']}), got {tool}({args})")
if h(s["output"]) != s["output_hash"]: raise Divergence(f"step {self.i}: corrupted output")
self.i += 1
return s["output"]
import random
from w2_replay import Transcript, Recorder, Replayer, Divergence
def make_tools(seed):
rng = random.Random(seed) # stands in for clock, network and scheduling noise
files = {"app.py": "def add(a, b):\n return a - b\n"}
return {"read_file": lambda path: files[path],
"run_tests": lambda: {"passed": 3, "failed": 1, "ms": rng.randint(800, 1200)}}
def agent(tools): # a fixed 3-step policy for the test
src = tools.call("read_file", path="app.py")
res = tools.call("run_tests")
return src, res
def test_replay_matches_recording():
tr = Transcript("w2-t0001", "img-sha256:0c3e", "ckpt-sha256:9f1c")
rec_out = agent(Recorder(tr, make_tools(1)))
rep_out = agent(Replayer(tr))
assert rec_out == rep_out and len(tr.steps) == 2
def test_reexecution_is_not_replay():
tr = Transcript("w2-t0002", "img-sha256:0c3e", "ckpt-sha256:9f1c")
first = agent(Recorder(tr, make_tools(1)))
again = agent(Recorder(Transcript("x", "", ""), make_tools(2))) # re-run in a fresh sandbox
assert first[1]["ms"] != again[1]["ms"] # timing output differs
def test_divergence_detected():
tr = Transcript("w2-t0003", "img-sha256:0c3e", "ckpt-sha256:9f1c")
agent(Recorder(tr, make_tools(1)))
r = Replayer(tr)
try:
r.call("read_file", path="other.py"); assert False
except Divergence as e:
assert "step 0" in str(e)
if __name__ == "__main__":
test_replay_matches_recording(); test_reexecution_is_not_replay(); test_divergence_detected(); print("OK")
The test shows the three properties a W2 review interface relies on: replaying a recorded run returns exactly the outputs the agent saw; re-running the same agent in a fresh sandbox does not (here the test-timing field differs); and any request that departs from the recording is reported with its step number, which is where a reviewer's corrected continuation would branch.
Debugging tips. If buffer depth oscillates, the low and high watermarks are too close relative to concurrency; widen the gap to at least a few minutes of demand. If the retry count is zero during known 429s, check that the exception type the client raises is the one being caught. If pairs show the same arm on the left far more than half the time, the flip is seeded from something correlated with the arm (for example the prompt id parity). If identical responses appear, the endpoint may be ignoring temperature or caching full responses; log a hash of each response and alert on duplicates.
The generation path is operated like any production client of a shared service, with two additions: the identity of what was served is part of correctness, not just observability, and agentic runs carry an environment that must also be pinned.
| SLI | Definition | Objective (W1, illustrative) |
|---|---|---|
| Pin conformance | Samples whose served digest equals the arm's pinned digest, over all samples | 100%; any mismatch pages |
| Generation success | Work items that produce a valid pair within 3 attempts | ≥ 99% per hour |
| Validator reject rate | Pairs rejected (empty, truncated, identical, filtered) over pairs generated | Baseline ± 2 points; alert on change |
| Retry ratio | Retries over calls, per endpoint | ≤ 10% (hard cap) |
| Generator headroom | Successful pairs per second over current demand | ≥ 1.2 |
| Replay fidelity (agentic) | Transcripts whose replay reaches the last step without divergence | 100% for transcripts shown to experts |
Table. Generation SLIs and objectives.
Dashboard. One row per arm: served-digest count (should be exactly one), output-length histogram (mean and p95 output tokens), response time p50/p95, 429 share and retry ratio. One row for the buffer: depth per segment and coverage in minutes (depth divided by current demand). One row for agentic runs: sandbox start time, run duration, recorder bytes per transcript and replay divergence count.
Symptom. At 10:30 the researcher notices that the candidate's win rate in the last 1,000 labels is 66%, against 54% over the first 6,000. On the generation dashboard the candidate arm's mean output length has risen from about 700 to about 910 tokens since roughly 02:00.
Separating causes. Three explanations fit: raters changed (a new shift that prefers longer answers), prompts changed (the selector moved to clusters where the candidate is stronger), or the model changed. The coverage panel shows the cluster mix within target and the rater mix unchanged, and the length shift is in the generated data before any rater sees it, which rules out raters. The served-digest panel for the candidate shows two digests since 02:00. The generator in this version addressed the candidate by the alias candidate-latest, which an operator had repointed to a newer candidate overnight; the validator logged the served digest but did not compare it with a pin, because there was no pin.
Impact. 3,100 pairs were generated from the wrong candidate: about 1,950 still in the buffer and 1,150 already labelled. The labelled ones are not usable for the intended comparison, about \(1{,}150 \times \$4.12 \approx \$4{,}700\) of labour (they remain usable as off-policy data with a different arm label). The buffered ones cost about $55 to regenerate.
Remedy. 1. Stop serving from the candidate arm's affected samples: quarantine by served digest, not by time window. 2. Pin both arms by digest in the campaign config and enable the digest check in the validator, so any future mismatch is rejected before buffering. 3. Refill: at 0.69 pairs/s capacity against about 0.52 pairs/s demand, refilling 2,000 pairs takes about \(2{,}000/0.17 \approx 3.3\) hours, so raise generator concurrency temporarily to about 20 pairs, roughly 1.15 pairs/s, which refills in about 50 minutes. That rate needs about 69 requests and 83,000 input tokens per minute per endpoint, above the client limits of 45 and 55,000 in the generation config, so the endpoint reservation and the client limits must be raised for the refill window as well; otherwise the token bucket holds generation near 0.75 pairs/s and the refill takes about 2.4 hours. 4. Re-tag the 1,150 labelled pairs with the served digest and hand the decision about their use to the researcher.
Validation. The served-digest panel shows exactly one digest per arm, and the candidate's output length returns to about 700 tokens. The hypothesis predicts that the candidate's win rate on post-fix labels returns to roughly the earlier 54%. If it stays near 66%, the model change was not the whole story and the rater and prompt hypotheses must be reopened.
Runbook: suspected checkpoint drift. 1. Check the served-digest panel per arm. If more than one digest: 2. Quarantine all samples with the unexpected digest, buffered and labelled. 3. Find the alias or deployment change (serving change log). 4. Confirm the arm config pins a digest and the validator compares it; if not, fix before resuming. 5. Refill the buffer with raised concurrency, raising the endpoint reservation and the client-side limits for the refill window if the higher rate exceeds them. 6. Report the number of affected labels and their cost to the researcher, with the served digest attached.
Agentic environments. The same discipline applies to sandboxes. The image digest is part of the sample's identity; a base image rebuilt with a newer package version changes tool outputs and can change the agent's behaviour. Pre-built, cached images keep sandbox start times low (the SWE-bench harness trades about 100 GB of cache at its default level for about 2,000 GB when every instance image is cached); a warm pool of started sandboxes hides the remaining start latency for interactive sessions. Replay divergence above zero for transcripts shown to experts is treated like pin conformance: the transcript is withdrawn from review until fixed, because experts' first-failing-step labels refer to step numbers in the recording.
Cost and trade-offs. Pinning means a new candidate requires a config change and a buffer flush, which is cheap ($56 for W1) but must be deliberate. Reserved quota on a shared serving pool is capacity other teams cannot use; a reservation of about 1.3 times peak demand is a reasonable starting point, revised from the generator-headroom panel.
Assignment: matching tasks to annotators, overlap/redundancy, skill and population constraints, fairness, deduplication
Define. Assignment decides which rater labels which item, and how many times each item is labelled. Its inputs are the generated items (each with a required skill or population), the campaign's redundancy plan, a pool of gold items with known answers, and the roster of raters with their qualifications and history. Its output is a stream of assignments: one item, one rater, a lease (a reservation that expires if the rater does not submit), and flags the rater cannot see, such as whether the item is gold or overlap. Assignment acts every time a rater asks for work, and again whenever a lease expires.
Motivate. The simplest scheme hands each rater the next item in a list. It fails in five ways. Raters get items outside their skill. Every item is labelled once, so nobody can measure agreement. Raters recognise gold items or never see them. The same rater sees near-identical prompts and labels them by habit. And the fastest raters, who are not always the best, take most of the work. Annotation tools expose part of the fix as settings; Label Studio Enterprise, for instance, has an "annotations per task minimum" for overlap and a task reservation that returns abandoned tasks to the pool (HumanSignal support). A platform for model training needs all five fixes together, plus an audit trail.
Explain end to end. Assignment has a planning stage and a serving stage.
Planning: slots. Each item becomes one or more slots, one per required label. Most items get one slot. A random fraction of items, the overlap set, get \(k\) slots so that \(k\) different raters label them independently; agreement on that set is the campaign's main measure of label reliability (Chapter 6). Gold items, items with an answer fixed by experts, are mixed in at a target share of all assignments and look exactly like other items; accuracy on them is the main per-rater quality signal.
Planning: deduplication. Exact duplicates are found by hashing normalised text. Near-duplicates (the same task reworded, or with a different variable name) are found with MinHash and locality-sensitive hashing (LSH). MinHash turns each text into a set of overlapping word sequences (shingles) and then into a short signature, so that two signatures agree in about the same fraction of positions as the Jaccard similarity of the two sets (the size of their intersection over the size of their union). LSH splits each signature into bands and treats two texts as candidates if any band matches exactly, so similar texts are compared without comparing every pair. Lee et al. (2022) used this approach on web text and found that about 3% of C4 training examples were near-duplicates and about 4.6% of the C4 validation set had a near-duplicate in training. For assignment, near-duplicates are grouped: a group is either reduced to one item or treated as one unit so that the same rater never labels two members of it.
Serving. When a rater asks for work (a pull model), the assigner walks a queue of open slots in the rater's skill segments and returns the first that passes every constraint: the rater is qualified for the item's skill or population; the rater has not labelled this item or any member of its near-duplicate group; for overlap items, the rater is not one of the item's existing raters; for gold, the rater has not seen this gold item before; and the rater is under their fairness cap, a limit on how much of the available work one person may take in a period. The chosen slot is leased. If the lease expires, the slot returns to the queue. In a push model a scheduler assigns batches to raters ahead of time instead; it gives more control over who does what, but it reacts slowly to raters who are idle or away.
Fairness. The word has two meanings here. Fairness to raters means equal access to work and predictable earnings; no qualified rater should be starved because others click faster. Fairness to the data means no small group of raters dominates the labels, because their personal preferences and errors would then dominate the reward model. A pull queue without caps violates both: work flows to whoever asks most often, and the raters who ask most often include those spending the least time per item.
W1 has 20,000 items. 2,000 (10%) get three slots and 18,000 get one, so there are \(18{,}000 + 6{,}000 = 24{,}000\) label slots. Gold is 5% of all assignments, which brings the total to about 25,260. The 150 vendor raters are qualified by language segment (Python, JS/TS, SQL, systems languages, other); about half also take the "other" segment. A fair share is about \(25{,}260/150 \approx 168\) assignments per rater over the campaign. Four percent of raters (6 people) were flagged for low effort with a median time per label under 40 s; at that speed a rater in an uncapped pull queue takes work nearly seven times faster (270/40 = 6.75) than one at 4.5 minutes. All numbers are illustrative.
Compare and contrast. Crowdsourcing marketplaces historically used open pull queues with per-worker qualification tests and post-hoc filtering; managed vendor teams often use push assignment by a team lead. A training-data platform usually takes the pull model for its low latency and natural load balancing, and adds the constraints and caps that a push scheduler would otherwise enforce. The cost is complexity in the assigner and a need to audit every assignment decision.
Connect and decide. The mental model is a dealer at a card table who follows house rules: every hand is dealt to someone qualified, nobody gets the same card twice, the marked cards (gold) are shuffled in invisibly, and no player gets more than a set share of hands. The default is a pull model with per-skill queues, a random 10% overlap at three raters, 5% gold drawn without repeats, near-duplicate groups as the unit of "already seen", leases at about the 99th percentile of label time, and a daily cap of about twice the fair share that rises with demonstrated quality. Deviate to push assignment for small expert campaigns where each item needs a named specialist (W2-style transcript review), and to higher overlap for pilots and new feedback types where agreement is unknown. The next section measures how long a rater waits for each assignment.
Assignment is mostly counting, plus three probability questions: how much gold a rater sees, whether near-duplicates are caught, and how a pull queue divides work.
Slots and assignments. Let \(n\) be the number of items, \(o\) the overlap fraction, \(k\) the raters per overlap item and \(g\) the gold share of all assignments. Label slots are \(S = n(1-o) + n o k\), and total assignments are \(A = S/(1-g)\), because gold is a share of the total, not of the label slots.
\(S = 20{,}000 \times 0.9 + 20{,}000 \times 0.1 \times 3 = 24{,}000\) and \(A = 24{,}000/0.95 \approx 25{,}263\), the "about 25,260" of the campaign spec. Gold assignments: about 1,263. Fair share per rater: \(A/150 \approx 168\).
How a pull queue divides work. If rater \(i\) works \(h_i\) hours and takes \(t_i\) per item, then in an uncapped pull queue with enough items their share is
\[ s_i = \frac{h_i/t_i}{\sum_j h_j/t_j}. \]Speed, not quality, sets the share.
Suppose all 150 raters work equal hours, 144 at a mean of 270 s per label and 6 at 40 s. The fast raters' relative rate is \(270/40 = 6.75\), so their combined share is \(6 \times 6.75/(144 + 6 \times 6.75) = 40.5/184.5 \approx 22\%\): 4% of raters would produce 22% of the labels, about 5,500 of the campaign's assignments. With a cap of twice the fair share per rater, their share is at most \(6 \times 2/150 = 8\%\).
Gold exposure without repeats. A rater who completes \(m\) assignments sees about \(g m\) gold items. To guarantee no repeats, each skill segment's gold pool \(G\) must satisfy \(G \ge g\, m_{\max}\), where \(m_{\max}\) is the most assignments any rater can do. A cap bounds \(m_{\max}\) and so bounds the gold pool needed.
Uncapped, a 40-s rater working four hours a day over about three days could do about 1,100 assignments and see about 55 gold items, close to exhausting a 60-item gold pool per segment. With the cap, \(m_{\max} \approx 336\) and about 17 gold items suffice, so the 60-item pools give a wide margin and allow retiring items that leak.
Near-duplicate detection. With a MinHash signature of \(b \times r\) values split into \(b\) bands of \(r\) rows, two texts with Jaccard similarity \(s\) agree on one band with probability \(s^r\) and become candidates with probability
\[ P(s) = 1 - (1 - s^{r})^{b}. \]The curve is an S whose steep part sits near \(s \approx (1/b)^{1/r}\). Candidates are then verified by computing similarity exactly, so false positives cost compute, not correctness; false negatives let duplicates through.
The Build code uses \(b = 16\), \(r = 4\) (64 hashes). The threshold is about \((1/16)^{1/4} = 0.5\). A rewording with \(s = 0.8\) is caught with probability \(1 - (1 - 0.41)^{16} \approx 0.9998\); a pair at \(s = 0.5\) with 0.64; an unrelated pair at \(s = 0.3\) becomes a candidate with probability 0.12 and is then rejected by the exact check. For comparison, Lee et al. (2022) used 5-grams, 9,000 hashes in 20 bands of 450 and a Jaccard threshold of 0.8 for web-scale text.
Leases. By Little's law, the number of slots held in leases is \(L = \lambda\, \bar h\), where \(\bar h\) is the mean time a lease is held. A lease timeout \(\tau\) should sit near the 99th percentile of label time so that slow but honest raters are not interrupted; abandoned slots then wait up to \(\tau\) before being reissued, which delays overlap completion but not throughput.
At \(\lambda \approx 0.52\) assignments/s and \(\bar h \approx 270\) s, about 140 leases are open at peak, one per online rater, as expected. With the assumed lognormal label times (median 240 s, log-sd 0.485), the 99th percentile is about \(240 \times e^{2.33 \times 0.485} \approx 740\) s, so W1 uses a 15-minute (900 s) lease.
| Decision | Default | Deviate when |
|---|---|---|
| Pull or push | Pull with constraints and caps | Few named experts per item; strict scheduling (push) |
| Overlap | 10% of items, \(k = 3\), chosen at random | Pilots and new feedback types (20 to 30%); mature campaigns with stable agreement (5%) |
| Gold | 5% of assignments, no repeats per rater, hidden | New raters or fast raters: temporarily higher gold rate |
| Deduplication | Exact hash plus MinHash LSH groups, verified | Very short prompts (shingles too few; use edit distance) |
| Fairness cap | 2x daily fair share, raised for proven quality | Expert pools with very uneven availability |
| Lease | About p99 of label time | Long tasks (W2: hours) need save-and-resume, not a short lease |
Table. Assignment defaults.
What you would actually do: compute \(S\) and \(A\) from the spec and check the gold pool against the capped \(m_{\max}\) before launch; set overlap at random so agreement is representative; and never run a pull queue without a per-rater cap.
The assigner has three pieces: near-duplicate grouping, a slot plan, and a stateful Assigner that answers next(rater). Raters are objects with a skill set and a history: items and near-duplicate groups already labelled, gold items already seen, and today's count. The assigner keeps one queue per skill. Overlap slots for an item are re-queued after each lease until all are taken, so the same item's three slots naturally go to three different raters, and the eligibility check makes sure of it.
Gold is injected by a deterministic coin: a hash of the rater id and pull number is compared with the gold share. That makes every assignment decision replayable from the log (the same rater, on the same pull, would get the same decision), which audits need.
# w1_routing.yaml
plan: {overlap_fraction: 0.10, overlap_k: 3, gold_share: 0.05}
dedup: {shingle_words: 3, minhash: {bands: 16, rows: 4}, verify_jaccard: 0.7}
constraints:
skill_match: true
unit_of_seen: near_dup_group # never two members of one group to the same rater
gold_no_repeat: true
daily_cap: {base: 2.0x_fair_share, raise_if_gold_accuracy_at_least: 0.90, max: 3.0x_fair_share}
lease: {timeout_s: 900, on_expiry: reopen_slot}
skills: [python, js-ts, sql, systems, other]
"""Assignment for W1: near-duplicate grouping (MinHash LSH), slot plan (overlap + gold),
pull-based assignment with skills, distinct raters, gold without repeats, fairness caps, leases."""
from collections import defaultdict, deque, Counter
from dataclasses import dataclass, field
import hashlib, math, random
# ---------- near-duplicate grouping ----------
def shingles(text, k=3):
w = text.lower().split()
return {" ".join(w[i:i + k]) for i in range(max(1, len(w) - k + 1))}
def minhash(sh, n=64):
return [min(int(hashlib.blake2b(f"{i}:{s}".encode(), digest_size=8).hexdigest(), 16) for s in sh)
for i in range(n)]
def near_dup_groups(texts: dict, bands=16, rows=4):
"""LSH: two texts become candidates if any band of `rows` hashes matches.
P(candidate | Jaccard s) = 1 - (1 - s**rows)**bands. Union-find merges candidates."""
parent = {k: k for k in texts}
def find(x):
while parent[x] != x: parent[x] = parent[parent[x]]; x = parent[x]
return x
buckets = defaultdict(list)
for k, t in texts.items():
sig = minhash(shingles(t), bands * rows)
for b in range(bands):
buckets[(b, tuple(sig[b * rows:(b + 1) * rows]))].append(k)
for ks in buckets.values():
for k in ks[1:]: parent[find(k)] = find(ks[0])
return {k: find(k) for k in texts}
# ---------- slot plan ----------
@dataclass(frozen=True)
class Item:
item_id: str
group: str # near-duplicate group id
skill: str # e.g. 'python', 'js-ts', 'sql', 'systems'
def plan_slots(items, overlap_frac=0.10, k=3, seed=0):
"""Each item gets 1 slot, or k slots if chosen for overlap. Returns item_id -> n_slots."""
rng = random.Random(seed)
ids = [i.item_id for i in items]
over = set(rng.sample(ids, round(len(ids) * overlap_frac)))
return {i: (k if i in over else 1) for i in ids}
# ---------- assigner ----------
@dataclass
class Rater:
rid: str
skills: frozenset
done_items: set = field(default_factory=set) # item and group ids already labelled
gold_seen: set = field(default_factory=set)
today: int = 0
n_real: int = 0 # non-gold assignments served (drives gold cadence)
class Assigner:
def __init__(self, items, slots, gold_items, gold_frac=0.05, daily_cap=None, lease_s=900):
self.items = {i.item_id: i for i in items}
self.queues = defaultdict(deque) # skill -> deque of item_ids with open slots
self.open = dict(slots)
for i in items:
self.queues[i.skill].extend([i.item_id] * 1)
self.gold = gold_items # list of Item, pre-labelled
self.gold_frac = gold_frac # share of ALL assignments that are gold
self.daily_cap, self.lease_s = daily_cap, lease_s
self.leases = {} # (rater, item) -> expiry
self.log = [] # (rid, item_id, is_gold)
def _eligible(self, r: Rater, iid):
it = self.items[iid]
return iid not in r.done_items and it.group not in r.done_items
def next(self, r: Rater, now=0.0):
if self.daily_cap is not None and r.today >= self.daily_cap:
return None # fairness cap: leave work for others
pull = r.n_real + len(r.gold_seen) # deterministic per (rater, pull) coin: replayable
coin = int(hashlib.blake2b(f"{r.rid}:{pull}".encode(), digest_size=8).hexdigest(), 16) / 2**64
if coin < self.gold_frac:
for g in self.gold: # gold looks like any other item to the rater
if g.skill in r.skills and g.item_id not in r.gold_seen:
r.gold_seen.add(g.item_id); r.today += 1
self.log.append((r.rid, g.item_id, True)); return g.item_id
for skill in sorted(r.skills, key=lambda s: -len(self.queues[s])): # drain the fullest queue
q = self.queues[skill]
for _ in range(min(len(q), 50)): # bounded look-ahead keeps next() O(1)-ish
iid = q.popleft()
if self.open[iid] <= 0: continue
if not self._eligible(r, iid):
q.append(iid); continue # someone else must take this slot
self.open[iid] -= 1
if self.open[iid] > 0: q.append(iid) # remaining overlap slots go back in line
it = self.items[iid]
r.done_items |= {iid, it.group}; r.today += 1; r.n_real += 1
self.leases[(r.rid, iid)] = now + self.lease_s
self.log.append((r.rid, iid, False)); return iid
return None
def expire(self, r: Rater, iid, now):
"""Lease ran out without a submission: reopen the slot for someone else."""
if self.leases.pop((r.rid, iid), now + 1) <= now:
self.open[iid] += 1; self.queues[self.items[iid].skill].append(iid)
r.done_items.discard(iid)
The tests check near-duplicate grouping on a reworded prompt, run the full W1 campaign with 150 simulated raters, and measure the fast-rater share with and without a cap.
import random
from collections import Counter, defaultdict
from w1_assign import Item, Rater, Assigner, plan_slots, near_dup_groups
SKILLS = {"python": .40, "js-ts": .20, "sql": .10, "systems": .15, "other": .15}
def test_near_dup():
base = "write a python function that parses an iso 8601 date string and returns a datetime object with timezone"
texts = {"a": base, "b": base + " please", "c": "explain how a b-tree index speeds up range queries in postgres"}
g = near_dup_groups(texts)
assert g["a"] == g["b"] and g["a"] != g["c"]
def test_w1_campaign():
rng = random.Random(0)
items = [Item(f"i{n}", f"i{n}", rng.choices(list(SKILLS), list(SKILLS.values()))[0]) for n in range(20000)]
slots = plan_slots(items)
assert sum(slots.values()) == 24000 # 18,000 x 1 + 2,000 x 3
gold = [Item(f"g{n}", f"g{n}", s) for n, s in enumerate(list(SKILLS) * 60)] # 300 gold items
a = Assigner(items, slots, gold, gold_frac=0.05)
raters = []
for n in range(150):
main = rng.choices(list(SKILLS), list(SKILLS.values()))[0]
raters.append(Rater(f"r{n}", frozenset({main, "other"} if rng.random() < .5 else {main})))
active = list(raters)
while active: # simulate pulls until no rater gets work
r = rng.choice(active)
if a.next(r) is None: active.remove(r)
log = a.log
real = [x for x in log if not x[2]]; gold_n = sum(x[2] for x in log)
assert len(real) == 24000
assert 0.045 < gold_n / len(log) < 0.055, gold_n / len(log)
by_item = defaultdict(list)
for rid, iid, g in real: by_item[iid].append(rid)
assert all(len(set(v)) == len(v) for v in by_item.values()) # overlap: distinct raters
assert sum(len(v) == 3 for v in by_item.values()) == 2000
per_rater_gold = Counter((rid, iid) for rid, iid, g in log if g)
assert max(per_rater_gold.values()) == 1 # no gold repeats
print("assignments", len(log), "gold", gold_n, f"({gold_n/len(log):.3%})")
def test_fairness_cap():
rng = random.Random(1)
items = [Item(f"i{n}", f"i{n}", "python") for n in range(2000)]
slots = plan_slots(items, overlap_frac=0.0)
def run(cap):
a = Assigner(items, slots, [], gold_frac=0.05, daily_cap=cap)
fast = [Rater(f"f{n}", frozenset({"python"})) for n in range(2)]
slow = [Rater(f"s{n}", frozenset({"python"})) for n in range(48)]
# each fast rater pulls 6x as often as a slow one (40 s vs 4 min per label)
pulls = fast * 6 + slow
while any(a.open[i] for i in a.open):
if a.next(rng.choice(pulls)) is None and all(a.next(r) is None for r in slow): break
c = Counter(rid for rid, _, _ in a.log)
return sum(c[r.rid] for r in fast) / len(a.log)
uncapped, capped = run(None), run(60)
assert uncapped > 0.15 and capped <= 0.061
print(f"fast-rater share uncapped {uncapped:.1%}, capped {capped:.1%}")
if __name__ == "__main__":
test_near_dup(); test_w1_campaign(); test_fairness_cap(); print("OK")
assignments 25203 gold 1203 (4.773%)
fast-rater share uncapped 19.4%, capped 6.0%
OK
The simulated campaign made 24,000 label assignments and 1,203 gold assignments (4.8%, within sampling noise of 5% for a per-pull coin; the expected total is about 25,260). Every overlap item has three distinct raters, exactly 2,000 items have three labels, and no rater saw a gold item twice. In the fairness test, 2 of 50 raters pull six times as often; uncapped they take 19.4% of the work (the formula predicts \(12/60 = 20\%\)), and with a cap of 60 per day they take 6.0%.
Debugging tips. If overlap items stall with one or two labels, the skill segment has too few raters who have not already seen the item's near-duplicate group; log the eligibility failure reason per skipped slot. If gold share drifts below target late in a campaign, the gold pool for some segment is exhausted for heavy raters; the per-rater gold-seen count against the segment pool shows it. If next() slows down, the look-ahead window is scanning many ineligible slots; that usually means one item type has accumulated in front of the queue and should move to its own queue. If two assignments for the same slot appear in the log, the lease and the slot counter were updated in different transactions; in a database-backed version both must change in one transaction with a row lock or compare-and-set on the slot.
Assignment is where data quality and rater welfare meet operations. The monitored quantities are each rater's share of work against fair share, the speed and gold accuracy of the raters who take the most work, overlap completion, gold-pool exhaustion and lease expiries.
Dashboard. (1) Work concentration: share of assignments taken by the top 5% of raters, and a Lorenz curve of assignments per rater; alert above 15%. (2) Speed versus quality: a scatter of each rater's median time per label against gold accuracy, sized by assignment count; large points in the fast, low-accuracy corner are the problem. (3) Overlap progress: overlap items with 1, 2 and 3 labels over time. (4) Gold: gold accuracy per rater with the number of gold items behind it, and the remaining unseen gold per segment for the heaviest rater. (5) Leases: expiries per hour and median reissue delay.
- alert: WorkConcentration
expr: top5pct_rater_share_rolling24h > 0.15
for: 1h
- alert: FastLowAccuracyRater
expr: rater_median_label_s < 40 and rater_gold_n >= 10 and rater_gold_accuracy < 0.80
- alert: GoldPoolNearExhaustion
expr: min by (segment) (gold_pool_size - max_rater_gold_seen) < 10
Symptom. On the first full day of collection (about 8,000 assignments), the concentration panel shows the top 5% of raters (8 people) holding 27% of assignments. Six of them have median label times between 31 and 39 s, against a pool median of 4.0 minutes.
Separating causes. Fast raters can be skilled experts on easy items or low-effort raters. Three measurements separate them. Item mix: the six took the same cluster and difficulty mix as everyone else, so they did not get easier items. Gold: after about 15 gold items each (their roughly 290 assignments at 5% gold), their gold accuracy is 61% against 84% for the rest of the pool and against the 80% campaign threshold. Agreement: on overlap items they share with others, their agreement with the majority is 55% against the campaign's 72%. All three point to low effort, not skill. The cause in the platform was a pull queue with no per-rater cap: the formula \(s_i \propto h_i/t_i\) predicted a share of about 22% for six raters at 40 s; they had reached 1,760 assignments (22%) by the end of the day.
Remedy. 1. Turn on the daily cap at twice the fair share for all raters, raised to three times for raters with gold accuracy of at least 90% on 20 or more gold items. 2. Raise the gold rate to 20% for any rater whose rolling median time falls below 60 s, so that 20 gold items accumulate within about 100 assignments instead of about 400. 3. Hold the six raters' 1,760 labels out of the export pending the quality review of Chapter 6. 4. Re-queue those items for labelling by other raters if the review rejects them.
Cost. Re-collecting 1,760 labels at 4.5 minutes each takes about 132 rater-hours, about $5,280 at $40 per hour; at about 1,870 assignments per peak hour that adds a little under one hour of pool time to collection. The cap also limits honest fast experts; the quality-based raise exists so that they are not penalised.
Validation. The hypothesis predicts that after the cap the top-5% share falls under 15% and campaign agreement on overlap items rises toward the pilot's 72%. If agreement does not rise after the six raters' labels are excluded, low effort was not the main cause of low agreement and the guideline or interface should be examined next.
Runbook: work concentration. 1. Confirm on the concentration panel (top 5% share above 15% for an hour). 2. For each top rater, compare item mix, gold accuracy (with count) and overlap agreement against the pool. 3. If two of three indicate low effort, enable or tighten the cap and raise that rater's gold rate. 4. Hold their labels from export until review. 5. If the cap leaves raters idle because the remaining items need skills few raters have, temporarily lift the cap for qualified raters in that segment only. 6. Record the action, the rater ids (pseudonymous) and the label counts in the campaign log.
Welfare and fairness. Caps and adaptive gold change raters' earnings and how they are evaluated, so the rules belong in the rater-facing guidelines, applied identically to everyone and appealable. Rater-level data is personal data; the dashboards show pseudonymous ids, and only the quality program sees identities. Chapter 10 covers pay structure; the interaction with assignment is direct, because per-item pay rewards speed and amplifies exactly the concentration shown here, while hourly pay with quality gates does not.
Time-to-first-sample engineering: queues, caching, warm pools, streaming
Define. Time to first sample (TTFS) is the time from a rater asking for the next item, by clicking "next" or submitting the previous label, to the item being on screen and usable. For a pairwise comparison, usable means both responses are rendered. TTFS is measured in the rater's browser and reported as percentiles (p50, p95) over many requests.
Motivate. Every second a rater waits is paid time that produces nothing, and waits break concentration on a task that needs it. In early annotation tools items were static files, so TTFS was a page load. Once items come from live model calls, generation time enters the path, and for long responses it is far longer than people tolerate between tasks. The engineering goal is to keep generation out of the path the rater waits on.
Explain end to end. On a request, four things happen in order: the assigner leases a slot; the client fetches the item's payload (the prompt and two responses, a few kilobytes of text for a coding pair); the interface renders it, including syntax highlighting and any diff view; and, only if no ready item exists, the platform waits for a model to generate one. The tools for shortening this path are few and well known.
Queues and buffers. A queue decouples a producer from a consumer that runs at a different pace. Here the producer is the generator and the consumer is the rater pool. A buffer of ready items absorbs the difference, so a rater's request becomes a dequeue (milliseconds) instead of a generation (seconds). Little's law (Little, 1961; 2011 retrospective) ties the three quantities together: the average number of items in the buffer equals the rate at which they are taken times the average time each waits there. A buffer large enough to survive a disruption is therefore also a buffer whose items are, on average, that old.
Prefetching. The client can request the next assignment while the rater is still working on the current one and hold it ready. TTFS then shrinks to rendering time. The cost is one extra lease per rater and a rule for what happens to the prefetched item if the rater stops.
Caching. Payloads are immutable once generated, so they can be cached close to the rater (an edge cache or the browser), and rendering results such as highlighted code can be computed once on the server. On the model side, prefix caching lets a serving engine reuse computation for a shared prompt prefix, which lowers time to the first token for repeated system prompts or multiple samples per prompt (SGLang's RadixAttention is one implementation: Zheng et al., 2023).
Warm pools. Anything that takes long to start (a model replica loading weights, a sandbox container, a microVM) can be started ahead of demand and kept idle in a warm pool, so a request does not pay the cold start. Warm pools cost idle capacity.
Streaming. When generation cannot be avoided, for example in live multi-turn sessions, the interface shows tokens as they arrive, so the rater can start reading after the time to first token instead of after the full response.
Tail tolerance. Dean and Barroso (2013) describe techniques that keep tail latency low without removing every source of variability, by using redundant capacity already deployed for fault tolerance; issuing a duplicate request when the first is slow is the best-known example. In a sample buffer, the analogous move is to keep enough stock that slow generations never reach a rater.
One trap: a closed system hides its own failures. Raters do not send requests at a fixed rate; each sends the next request only after finishing the previous item. When the buffer empties, blocked raters stop sending requests, so a long outage produces only a handful of very slow requests among thousands of fast ones. A daily p95 can look healthy while every rater sat idle for twenty minutes. TTFS must therefore be measured per short window and per segment, and alongside it the share of rater time spent waiting.
On a buffer hit, a W1 request takes about 0.35 s at the median: lease, fetch and render (illustrative values). On a miss, the rater waits for both responses to be generated, about 16 s at the median. With 140 raters online at peak and a mean of 4.5 minutes per label, raters take about 0.52 pairs per second; the 2,000-pair buffer is therefore about 64 minutes of peak demand. In a simulation of an 8-hour shift with a 30-minute outage of the candidate endpoint, a 2,000-pair buffer never empties, while a 200-pair buffer empties after about 6 minutes; the daily p95 for the small buffer is still 0.84 s, but raters lose about 54 hours of time, about $2,150 at $40 per hour.
Compare and contrast. Pure on-demand generation with streaming has no waste and perfect freshness but puts generation in front of every rater. A buffer moves generation off the critical path at the price of stock that ages and must be discarded when the arms change. Prefetching attacks the remaining fetch and render time at the price of extra leases. These combine rather than compete.
Connect and decide. The mental model is a restaurant kitchen during service: dishes that take twenty minutes are prepared ahead (the buffer), the next plate is at the pass before the diner finishes (prefetch), and the ovens are already hot (warm pools). The default for judged responses is a per-segment buffer sized to survive the longest generator disruption the platform is meant to absorb, client prefetch of one item, cached payloads, and streaming only where the rater writes the prompt. SLOs are evaluated per 15-minute window and per segment, with idle rater time as a second metric. Deviate to on-demand with streaming for live sessions, and to warm sandbox pools for interactive agentic tasks. This completes the sample path; Chapter 5 takes over at the moment the item is on screen.
This level derives the buffer size for W1's 2 s p50 and 5 s p95 targets from queueing arguments, and shows which target actually binds.
Decomposition. TTFS on a hit is \(T_{\text{hit}} = T_{\text{lease}} + T_{\text{fetch}} + T_{\text{render}}\); on a miss it is \(T_{\text{miss}} = T_{\text{lease}} + T_{\text{wait}} + T_{\text{render}}\), where \(T_{\text{wait}}\) is the time until a newly generated pair is available. Let \(m\) be the share of requests that miss. Then
\[ P(\text{TTFS} > x) = (1-m)\,P(T_{\text{hit}} > x) + m\,P(T_{\text{miss}} > x). \]With \(T_{\text{hit}}\) lognormal around 0.35 s (assumed) and the pair generation time of about 16 s median, \(P(T_{\text{hit}} > 5\text{ s}) \approx 0\) and \(P(T_{\text{miss}} > 5\text{ s}) \approx 1\). So \(P(\text{TTFS} > 5) \approx m\), and the p95 target requires \(m \le 0.05\). The p50 target only requires \(m < 0.5\). The p95 target binds; the p50 target is met by any working buffer. A design margin of \(m \le 0.01\) per window is used below.
Little's law on the buffer. For the buffer, \(L = \lambda W\): mean depth \(L\) equals service rate \(\lambda\) times mean time in buffer \(W\). With the refill policy keeping the buffer near its high watermark \(B\), \(L \approx B\), so the mean age of a served pair is \(W \approx B/\lambda\).
\(\lambda = 140/270 \approx 0.52\) pairs/s at peak, so \(W \approx 2{,}000/0.52 \approx 3{,}860\) s, about 64 minutes. The Build-level simulation measures a mean depth of 1,991 and \(\lambda W = 1{,}968\) over 48 simulated hours (\(\lambda = 0.517\)/s, \(W = 63.5\) min): Little's law holds to about 1%.
Sizing for a disruption. Misses happen when demand during a generator disruption exceeds the stock. If generation stops for \(T\) seconds at peak, demand during the outage has mean \(\lambda T\); treating arrivals as roughly Poisson, its standard deviation is about \(\sqrt{\lambda T}\). Add a burst \(N\) for the moment a whole shift asks for work at once. The buffer must hold
\[ B \ge \lambda T + z\sqrt{\lambda T} + N, \]where \(z\) sets the probability of running out (\(z = 2.33\) for 1%). This is the standard safety-stock argument from inventory control, applied to samples. Because the assigner only serves items within a rater's skill segment, the buffer is really one buffer per segment, each with demand share \(\pi_i\), and the safety terms add separately:
\[ B_{\text{seg}} = \sum_i \left(\pi_i \lambda T + z\sqrt{\pi_i \lambda T} + \pi_i N\right) \;\ge\; \lambda T + z\sqrt{\lambda T} + N, \]because \(\sum_i \sqrt{\pi_i} \ge 1\). Splitting a buffer always costs safety stock.
For a 30-minute outage, \(\lambda T = 0.52 \times 1{,}800 \approx 933\), the safety term is \(2.33\sqrt{933} \approx 71\) and the shift-start burst is 140: a pooled buffer of about 1,145. Split into the five W1 segments (40/20/10/15/15%), the requirement rises to about 1,230: Python 475, JS/TS 247, SQL 130, systems 189, other 189. After the outage, the generator refills at \(\mu - \lambda\), where \(\mu\) is its capacity: \(0.69 - 0.52 \approx 0.17\) pairs/s, so replacing 933 pairs takes about 89 minutes. A second disruption inside that window finds the buffer half full. W1 therefore holds 2,000, about 64 minutes of peak demand, enough to absorb a 30-minute outage followed by a second one before refill completes. The simulation confirms the two cases: with 2,000 the depth bottoms out at 1,081 and no request misses; with 200 the buffer is empty for about 24 minutes.
Closed-system accounting. Raters are a closed population: a blocked rater stops generating requests. The useful damage measure is idle rater time, about \(N_{\text{seg}} \times T_{\text{empty}}\) for a segment empty for \(T_{\text{empty}}\), not the share of slow requests.
With the 200-pair buffer, the simulated daily p95 is 0.84 s and only 1.2% of requests miss, yet the worst 15-minute window has a p95 of about 1,440 s and raters lose about 54 hours, which matches \(140 \times 24/60 \approx 56\) hours. A full stop of 140 raters costs \(140 \times \$40/60 \approx \$93\) per minute.
Prefetch. With one prefetched item per rater, TTFS on a hit falls to \(T_{\text{render}}\). Leases held rise by \(N\) (Little's law with one extra item per rater), and if the lease timer starts at prefetch, the timeout must grow by one mean label time.
Prefetch adds 140 leases at peak and raises the lease timeout from 900 s to about 1,170 s (900 plus a mean label time of 270 s). Expected TTFS on a hit drops from about 0.35 s to the render time, assumed 0.2 s.
| Technique | Removes | Costs | W1 effect (illustrative) |
|---|---|---|---|
| Per-segment buffer | Generation time from the request path | Stock, staleness \(B/\lambda\), flush on arm change | p50 from about 17.5 s to 0.35 s |
| Client prefetch | Lease and fetch time | \(N\) extra leases, longer timeout | 0.35 s to about 0.2 s |
| Payload and render cache | Repeated fetch and highlighting | Cache invalidation on edits | Overlap and gold items render instantly |
| Warm pools | Cold starts (replicas, sandboxes) | Idle capacity | Not needed for W1; central for interactive agentic tasks |
| Streaming | Waiting for the full response on misses | Rater reads while text arrives | Only for live multi-turn sessions |
Table. Latency techniques and their costs.
What you would actually do: decide which disruption the buffer must absorb (a 30-minute endpoint outage is a reasonable default), size each segment with the safety-stock formula, add margin for refill time, add prefetch, and write the SLO per 15-minute window and per segment with idle rater time beside it.
Two artifacts make the latency design testable: a sizing function and a discrete-event simulation. A discrete-event simulation keeps a priority queue of future events (a rater's request, a generation finishing) ordered by time, repeatedly takes the earliest, updates the state, and schedules the events that follow. It answers questions the formulas cannot, such as how long a buffer stays empty during an outage when blocked raters stop making requests.
Sizing.
"""Buffer sizing per segment: cover T seconds of generator outage at peak demand, plus a
Poisson safety margin at z, plus the shift-start burst (one item per rater in the segment)."""
import math
def size_buffer(lam_total, shares, cover_s, z=2.33, raters=140):
out = {}
for seg, sh in shares.items():
mean = lam_total * sh * cover_s # expected demand while generation is down
out[seg] = math.ceil(mean + z * math.sqrt(mean) + raters * sh)
return out
def refill_minutes(deficit, mu, lam):
"""Time to rebuild `deficit` pairs when capacity mu exceeds demand lam (pairs/s)."""
assert mu > lam, "generator cannot refill while demand exceeds capacity"
return deficit / (mu - lam) / 60
if __name__ == "__main__":
shares = {"python": .40, "js-ts": .20, "sql": .10, "systems": .15, "other": .15}
lam = 140 / 270
seg = size_buffer(lam, shares, 1800)
pooled = size_buffer(lam, {"all": 1.0}, 1800)["all"]
print("per segment", seg, "sum", sum(seg.values()), "pooled", pooled)
print("refill after a 30-min outage: %.0f min" % refill_minutes(lam * 1800, 12 / 17.3, lam))
assert sum(seg.values()) > pooled # segmentation costs safety stock
assert 1150 < sum(seg.values()) < 1300
per segment {'python': 475, 'js-ts': 247, 'sql': 130, 'systems': 189, 'other': 189} sum 1230 pooled 1145
refill after a 30-min outage: 89 min
Simulation. State: the buffer (creation time of each ready pair), the number of generations in flight, and the list of raters waiting on an empty buffer. Events: request (a rater wants an item) and gen_done (a pair finished). Inputs: the number of raters, the label-time and generation-time distributions, generator concurrency, the high watermark and an optional outage window during which generation stalls. Outputs: TTFS percentiles over the day and per 15-minute window, miss rate, idle rater-hours, mean depth and mean age of served pairs, and optionally a per-minute depth trace.
"""Discrete-event simulation of W1 time-to-first-sample: raters pull pairs from a pre-generated
buffer; a concurrency-limited generator refills it; an endpoint outage can stop generation."""
import heapq, math, random
from dataclasses import dataclass
@dataclass
class Cfg:
raters: int = 140 # online at peak
label_median_s: float = 240.0 # 4.0 min median, 4.5 min mean (lognormal, sigma 0.485)
label_sigma: float = 0.485
gen_median_s: float = 12.5 # one response: ~0.8 s first token + ~700 tokens at ~60 tok/s
gen_sigma: float = 0.45
gen_slots: int = 12 # concurrent pair generations (rate-limit headroom ~1.5x demand)
high: int = 2000 # buffer high watermark (refill target)
serve_median_s: float = 0.35 # lease + fetch + render on a buffer hit
serve_sigma: float = 0.5
trace: bool = False # record buffer depth once a minute
outage: tuple = None # (start_s, end_s): candidate endpoint returns nothing
horizon_s: float = 8 * 3600
seed: int = 0
def lognorm(rng, median, sigma): return median * math.exp(rng.gauss(0, sigma))
def simulate(c: Cfg):
rng = random.Random(c.seed)
ev, seq = [], 0
def push(t, kind, data=None):
nonlocal seq; heapq.heappush(ev, (t, seq, kind, data)); seq += 1
buf = [0.0] * c.high # creation times of buffered pairs (start full)
waiting, in_flight = [], 0 # raters blocked on an empty buffer (request times)
ttfs, misses, area, last_t, served_age, rec, tr = [], 0, 0.0, 0.0, [], [], []
def start_gen(t):
nonlocal in_flight
while in_flight < c.gen_slots and len(buf) + in_flight < c.high + len(waiting):
in_flight += 1
d = max(lognorm(rng, c.gen_median_s, c.gen_sigma), lognorm(rng, c.gen_median_s, c.gen_sigma))
if c.outage and c.outage[0] <= t < c.outage[1]:
d = (c.outage[1] - t) + d # stalled until the endpoint is back
push(t + d, "gen_done")
for i in range(c.raters):
push(rng.uniform(0, 60), "request") # shift start: everyone arrives within a minute
start_gen(0.0)
while ev:
t, _, kind, _ = heapq.heappop(ev)
if t > c.horizon_s: break
if c.trace:
while len(tr) * 60 <= t: tr.append(len(buf))
area += len(buf) * (t - last_t); last_t = t
if kind == "request":
if buf:
served_age.append(t - buf.pop(0))
s = lognorm(rng, c.serve_median_s, c.serve_sigma)
ttfs.append(s); rec.append((t, s)); push(t + s + lognorm(rng, c.label_median_s, c.label_sigma), "request")
else:
misses += 1; waiting.append(t)
start_gen(t)
elif kind == "gen_done":
in_flight -= 1
if waiting: # a blocked rater gets the fresh pair directly
t0 = waiting.pop(0)
s = (t - t0) + lognorm(rng, c.serve_median_s, c.serve_sigma)
ttfs.append(s); rec.append((t0, s)); served_age.append(0.0)
push(t0 + s + lognorm(rng, c.label_median_s, c.label_sigma), "request")
else:
buf.append(t)
start_gen(t)
win = {} # p95 per 15-minute window of request time
for t0, s in rec: win.setdefault(int(t0 // 900), []).append(s)
worst = max(sorted(v)[int(len(v) * .95)] for v in win.values() if len(v) >= 20)
ttfs.sort(); n = len(ttfs)
lam = n / last_t # throughput of served pairs (pairs/s)
return {"served": n, "p50": ttfs[n // 2], "p95": ttfs[int(n * .95)], "miss_rate": misses / n,
"throughput_per_h": lam * 3600, "mean_depth": area / last_t,
"mean_age_s": sum(served_age) / len(served_age),
"idle_rater_h": sum(x for x in ttfs if x > 5) / 3600, "worst_15min_p95": worst, "trace": tr}
from w1_ttfs_sim import Cfg, simulate
def show(name, r):
print(f"{name:34s} served {r['served']:6d} p50 {r['p50']:5.2f}s p95 {r['p95']:6.2f}s "
f"miss {r['miss_rate']:6.2%} idle {r['idle_rater_h']:5.1f} rater-h depth {r['mean_depth']:7.1f} "
f"age {r['mean_age_s']/60:5.1f} min worst-15min p95 {r['worst_15min_p95']:7.1f}s")
def test_scenarios():
peak = 3 * 3600
base = simulate(Cfg())
show("B=2000, healthy", base)
assert base["p50"] <= 2 and base["p95"] <= 5
# Little's law on the buffer: mean depth = throughput x mean time in buffer. Over a finite window
# the pairs still sitting in the buffer at the end bias it, so check on a long (48 h) run.
long = simulate(Cfg(horizon_s=48 * 3600))
L, lam, W = long["mean_depth"], long["throughput_per_h"] / 3600, long["mean_age_s"]
print(f"Little: L={L:.0f} lambda*W={lam*W:.0f} (lambda={lam:.3f}/s, W={W/60:.1f} min)")
assert abs(L - lam * W) / L < 0.05, (L, lam * W)
o30 = simulate(Cfg(outage=(peak, peak + 1800)))
show("B=2000, 30-min outage", o30); assert o30["worst_15min_p95"] <= 5 and o30["idle_rater_h"] < 1
small = simulate(Cfg(high=200, outage=(peak, peak + 1800)))
show("B=200, 30-min outage", small)
assert small["p95"] <= 5 and small["worst_15min_p95"] > 5 and small["idle_rater_h"] > 10 # daily p95 hides it
o120 = simulate(Cfg(outage=(peak, peak + 7200)))
show("B=2000, 120-min outage", o120); assert o120["worst_15min_p95"] > 5
nobuf = simulate(Cfg(high=0, gen_slots=200))
show("on-demand only (no buffer)", nobuf); assert nobuf["p50"] > 10
if __name__ == "__main__":
test_scenarios(); print("OK")
B=2000, healthy served 14951 p50 0.35s p95 0.80s miss 0.00% idle 0.0 rater-h depth 1990.3 age 59.5 min worst-15min p95 0.9s
Little: L=1991 lambda*W=1968 (lambda=0.517/s, W=63.5 min)
B=2000, 30-min outage served 14920 p50 0.35s p95 0.80s miss 0.00% idle 0.0 rater-h depth 1880.4 age 56.2 min worst-15min p95 0.9s
B=200, 30-min outage served 14218 p50 0.35s p95 0.84s miss 1.20% idle 53.8 rater-h depth 175.1 age 5.9 min worst-15min p95 1437.0s
B=2000, 120-min outage served 13231 p50 0.36s p95 0.85s miss 1.20% idle 127.3 rater-h depth 1252.5 age 41.8 min worst-15min p95 3302.2s
on-demand only (no buffer) served 14111 p50 17.52s p95 23.11s miss 100.06% idle 69.4 rater-h depth 0.0 age 0.0 min worst-15min p95 24.5s
OK
The five scenarios answer the design questions directly. A healthy 2,000-pair buffer gives p50 0.35 s and p95 0.80 s. It absorbs a 30-minute outage with no misses. A 200-pair buffer meets the daily p95 (0.84 s) yet fails the 15-minute-window SLO badly and costs about 54 rater-hours, about $2,150. Even 2,000 pairs cannot absorb a 120-minute outage (about 127 rater-hours lost, about $5,100), which sets the boundary of what buffering alone can handle. Without a buffer, the p50 is 17.5 s: generation dominates. (The miss rate shows slightly above 100% in that row because requests still waiting at the end of the horizon count as misses but not as served.) The simulation treats every request as needing a fresh pair; in W1 gold items and repeat overlap slots do not, so real demand on the generator is about 79% of this.
Debugging tips. If the simulated p50 is far above the hit latency with no outage, generator capacity is below demand (check \(\mu = \text{slots}/\bar T_{\text{pair}}\) against \(\lambda\)). If Little's law fails by more than a few percent, the horizon is too short relative to \(W\) (items still in the buffer at the end bias the estimate) or time-in-buffer is measured for some items but not others. In the real system, instrument TTFS in the browser from the click to the first paint of both responses, and log the lease id with it, so a slow request can be traced to a hit or a miss and to its segment.
TTFS is the platform's most visible SLO to raters and vendors, and the one whose failures are hardest to see in aggregate. Operating it means segment-level SLOs, coverage-based alerts that fire before the buffer empties, a generator that degrades instead of amplifying overload, and a runbook.
| SLI | Measured | Objective (W1, illustrative) |
|---|---|---|
| TTFS p50 | Browser, click to both responses painted, per segment per 15 min | ≤ 2 s in 99% of windows over 28 days |
| TTFS p95 | Same | ≤ 5 s in 99% of windows over 28 days |
| Idle rater time | Sum of waits over 5 s, over rater time online | ≤ 0.5% per day |
| Buffer coverage | Segment depth over current segment demand, in minutes | ≥ 30 min in every segment |
| Generator headroom | Successful pairs/s over current demand, per segment | ≥ 1.2 |
Table. Latency SLOs. With 15-minute windows, 1% of windows over 28 days is about 27 windows, the error budget.
- alert: SegmentCoverageLow # fires before raters notice
expr: min by (campaign, segment) (buffer_depth / segment_demand_per_min) < 30
for: 5m
- alert: SegmentCoverageFalling
expr: deriv(buffer_depth[10m]) * 60 < -0.5 * segment_demand_per_min # draining at over half of demand
for: 10m
- alert: EndpointThrottled
expr: rate(gen_calls_429[5m]) / rate(gen_calls[5m]) > 0.05
for: 5m
- alert: RetryRatioHigh
expr: rate(gen_retries[5m]) / rate(gen_calls[5m]) > 0.10
Timeline. 13:00, peak: 140 raters online, demand 0.52 pairs/s, buffer at 1,950 pairs. The systems segment (C, C++, Rust, Go; 15% of demand) holds only 200, because its watermarks were left at an earlier, smaller setting. 13:05: an evaluation sweep starts on the same serving pool as the candidate endpoint and shares its quota. The candidate's 429 share jumps from 0.5% to 46%. The generator in this version ignores retry-after and retries immediately up to five times, which raises call volume about 2.4 times (expected attempts per item \((1-0.61^5)/(1-0.61) \approx 2.35\)) and pushes the 429 share to 61%. Successful pairs fall from a capacity of 0.69 to 0.21 per second. The refiller orders work by absolute deficit, so the large Python segment gets almost all of the scarce successful generations and the systems segment gets almost none.
Symptom. At 13:48 the systems segment is empty (200 pairs at about 0.078 pairs/s of systems demand last about 43 minutes). Its 21 raters start waiting; their per-window p95 reaches 38 s. Global p95 is 4.1 s because 85% of requests still hit. The global coverage alert, set at 30 minutes of demand, would fire only at about 14:00, when the global buffer falls below about 930. A vendor lead reports the waits at 13:55.
Separating causes. Three causes can empty a segment: demand rose (more systems raters), generation slowed (endpoint), or generation was misdirected (refill ordering). The demand panel shows systems demand flat. The endpoint panel shows the 429 share at 61% and retries at 57% of calls, so generation slowed. The per-segment generation panel shows Python receiving 92% of successful pairs while holding 51 minutes of coverage and systems receiving under 2% at zero coverage, so generation was also misdirected.
Remedy, in order. 14:20: deploy the generator configuration that honours retry-after with jittered backoff and a 10% retry budget; the 429 share falls to 47% and successful throughput rises to about 0.36 pairs/s. Switch refill priority from absolute deficit to coverage time (depth divided by segment demand), so the emptiest segment by minutes is filled first. 14:35: the evaluation sweep moves to its own quota; the 429 share returns under 1%. Concurrency is raised temporarily so capacity reaches about 1.0 pair/s. 14:40: the systems segment has stock again.
Impact. The systems segment was empty for about 52 minutes (13:48 to 14:40). With 21 raters mostly blocked, the loss is about \(21 \times 52/60 \times 0.8 \approx 15\) rater-hours, about $580, assuming they were blocked 80% of that time. The global buffer bottomed at about 430 at 14:35 and was full again by about 15:27 (\((1{,}950-427)/(1.0-0.52)\) s, about 53 minutes).
Validation. The hypothesis is that retry amplification plus deficit-ordered refill caused the segment outage. It predicts that replaying the 13:05 load in the simulation with the old policy empties the systems segment within about 45 minutes, and with the new policy (honoured retry-after, retry budget, coverage-ordered refill) does not empty any segment during the 90 minutes from the sweep start to the quota split. If the replay with the new policy still empties the systems segment, the watermark for that segment was the dominant cause, and the fix is the per-segment sizing from the Design level (189 for a 30-minute outage, more with refill margin) rather than the refill order.
Runbook: buffer draining. 1. Open the per-segment coverage panel and find the segment with the lowest minutes of coverage. 2. Check segment demand: if it rose, raise that segment's watermark and generation priority. 3. Check endpoint health per arm: 429 share, error rate, latency. If throttled, confirm that retry-after is honoured and retries are under budget; find the competing consumer of the quota (serving pool usage by job) and ask for a reservation or move the other job. 4. Check refill order: generation must go to the lowest coverage first. 5. If a segment will empty before generation recovers, degrade deliberately: show raters in that segment a message with an expected wait, offer qualified raters work in another segment, or pause the segment, instead of leaving them at a spinner. 6. After recovery, compute idle rater-hours and refill time and attach both to the incident.
Scaling scenario. If the pool doubles to 300 raters with 280 online at peak, \(\lambda\) doubles to about 1.04 pairs/s. The pooled 30-minute requirement scales as \(\lambda T + z\sqrt{\lambda T} + N\): about \(1{,}867 + 101 + 280 \approx 2{,}250\), less than double, because the safety term grows with the square root. The per-endpoint quota doubles (about 83 requests, 100,000 input and 58,000 output tokens per minute at a 1.34x capacity margin), and generator concurrency doubles to about 24 pairs. Staleness \(B/\lambda\) halves for the same \(B\), which makes a larger buffer cheaper to hold.
Cost and trade-offs. Buffer stock is cheap in tokens ($56 per 2,000 pairs in W1) and expensive only when the arms change. Reserved quota is the real cost and is shared across teams; the incident shows why a campaign with paid raters attached needs a reservation, not best-effort capacity. Segment-level SLOs multiply the number of alerts, but without them the global p95 hid a 38 s wait for 15% of the pool.
Feedback Interfaces
A feedback interface is the screen on which a person turns a model sample into a structured judgement: a choice between two responses, a score against a rubric, a flagged step in an agent transcript, a rewritten answer. It is the only component of an RL data platform that a human touches, and it is where most of the information in a label is either captured or lost. Everything upstream (campaign spec, prompt selection, generation from live endpoints) decides what is shown; the interface decides how it is shown, what the annotator is able to express, and what the platform records about how the judgement was made.
The interface matters for three reasons. First, the label format fixes the training signal: a pairwise choice becomes a reward-model pair, a step flag becomes a process label, a rewrite becomes a supervised target. Second, layout choices create systematic errors: which response appears on the left, whether an AI suggestion is visible before the annotator has formed a view, how long a session runs. Third, the interface is the cheapest place to measure effort and attention, because every scroll, jump and edit can be logged.
The chapter has four parts. Interface types catalogues the main formats and the record each yields. Reviewing long agentic transcripts designs the hardest current case end to end. Designing for data quality covers biases, effort, fatigue, instrumentation and a TypeScript/React architecture. Experiments on interfaces shows how to measure whether a UI change improved the data. The quality program that consumes these signals is Chapter 6; the conversion into training examples is Chapter 7.
The three reference workloads each need a different interface. W1 (20,000 pairwise comparisons of coding responses, 150 vendor raters, median 4.0 minutes per label) needs a fast side-by-side comparison screen. W2 (2,000 agent transcripts of about 60 steps and 25,000 tokens, reviewed by 40 domain experts in about 35 minutes each) needs a long-document reviewer that marks the first failing step and collects a roughly 400-word corrected continuation. W3 (legal-drafting rubrics, 8 to 12 weighted items per prompt) needs a rubric editor and a rubric-scoring screen.
The interface is a cost and quality lever with unusually high gearing. Annotator time is the dominant cost of human data, and the interface sets how much of that time is spent judging rather than scrolling, waiting or re-reading. It also sets the error structure of the labels: random noise that more overlap can average away, or systematic bias that no amount of overlap removes.
Three quantities organise the design work in this chapter. Active time per label \(t\) (minutes of visible, non-idle interaction) drives cost per label, \(c = w\,t\) for an hourly rate \(w\). Yield \(y\) is the fraction of labels that become usable training examples after ties, validation failures and QA rejections, so the cost per useful label is \(c/y\). Bias is a systematic shift in the label distribution caused by the interface rather than the samples; it is measured against a known expected value (for example, a 50% left-choice share when sides are randomised).
In W1, \(w = \$40/\text{h}\) and the mean active time is 4.5 minutes, so a label costs $3.00; with 25,260 assignments that is about $75,780, and with roughly 18,400 useful comparisons the cost is about $4.12 per useful comparison. In W2, \(w = \$120/\text{h}\) and a transcript takes about 35 minutes, so each transcript costs about $70. One extra minute of interface friction per W2 transcript costs 2,000 minutes, about 33 expert-hours or $4,000 across the campaign.
Each section ends with the design decision and the default this book recommends.
This chapter's Build blocks ship tested artifacts that together form a minimal interface layer: feedback_records.py (typed records for six interface types and their conversion into reward-model pairs, process labels, rubric rewards and correction examples); reviewState.ts and TranscriptReview.tsx (the state model and React component of the W2 transcript reviewer, using TanStack Virtual for virtualised rendering); ui_event.schema.json, uiLogger.ts and active_time.py (the instrumentation contract, a batched browser logger and the derived active-time metric); bias_audit.py (position, length, anchoring and fatigue statistics); and ui_power.py (sample sizes, design effect, CUPED and a cluster bootstrap for interface experiments).
The Python modules have pytest suites (17 tests, including a check of the experiment spec file) and the TypeScript reducer has a node:test suite (6 tests); the React component and logger type-check under tsc --strict against React 18 and @tanstack/react-virtual 3.x. One principle runs through all of them: the label, the validation rules and the state transitions are pure functions of their inputs, so the same code runs in the browser, on the server and in replay from the event log.
In production an interface is a service with users whose time is expensive, so it gets SLOs like any other service. The ones that matter are user-perceived: time to an interactive assignment, interaction latency, draft durability (no lost work), event completeness (so quality metrics are trustworthy) and submit success. The table gives defaults; the Operate blocks below add dashboards, alert rules and worked incidents for each section.
| SLO | Definition | Default target | Why |
|---|---|---|---|
| Time to interactive | assignment request → first judgement possible, p95 | ≤ 2 s (pairwise), ≤ 1.5 s render (W2) | waiting is paid time |
| Interaction latency | Interaction to Next Paint, p75 | ≤ 200 ms | the web.dev "good" threshold |
| Draft durability | submitted drafts lost / drafts started | 0; alert on any | a lost W2 draft costs about $70 |
| Event completeness | sequence gaps / events, per day | ≤ 0.5% | effort and bias metrics depend on it |
| Submit success | accepted submits / submit attempts (excluding rule rejections) | ≥ 99.5% | failed submits cause rework and distrust |
Table. Interface-level SLOs (defaults to adapt). Interaction to Next Paint thresholds are from web.dev (Google): 200 ms or less is good at the 75th percentile.
The common failure pattern across the incidents in this chapter is that a UI change silently changes the data. A larger tie button raises the tie rate; a CSS change pushes one response below the fold; an eagerly rendered tool log slows every review. None of these raise an error. They are caught only by metrics with known expected values, which is why instrumentation is designed before the first campaign, not after the first incident.
Interface types and the data each yields
Definition. An interface type is a fixed combination of what the annotator sees (one response, two, several, a long transcript, a live conversation) and what they produce (a choice, a score, a checklist, a highlighted span with a comment, a rewritten text). The type determines the shape of the record that leaves the browser and therefore which training signal it can become. Six types cover nearly all RL human-data work.
Why there are several. The earliest preference-learning work asked people to compare two short behaviours and pick the better one, because comparing is easier and more consistent than assigning an absolute score. As models improved, three limits appeared. A bare choice says nothing about why one response is better. Some domains need a specific, checkable standard rather than an overall impression. And when both responses are poor, a choice between them teaches little; the annotator needs to be able to write the right answer. Each newer interface type answers one of these limits.
The six types, end to end.
- Pairwise (or multi-way) comparison. The annotator sees a prompt and two responses, usually from different model variants, and picks the better one, often with a strength (for example "slightly" to "significantly" better) and sometimes a tie. The record is (prompt, response ids, choice, strength). It becomes a reward-model training pair whose loss can be weighted by the strength. Touvron et al. (2023) describe this protocol for Llama 2: annotators write a prompt, choose between two sampled responses and rate the degree of preference on a four-level scale, with a separate safety label. A ranking of K responses is the multi-way version: Ouyang et al. (2022) had labelers rank 4 to 9 responses per prompt to speed up comparison collection, and every ranking implies all pairs within it.
- Rating (Likert or multi-attribute). The annotator scores one response on one or more scales. The record is a score per attribute. It becomes a pointwise target (a regression reward model or a filter) and can be converted to pairs by comparing scores of responses to the same prompt. HelpSteer2 (Wang et al. 2024) is a public example: about 10,000 response pairs, each response scored on five attributes (helpfulness, correctness, coherence, complexity, verbosity) on a 0 to 4 scale, typically by three annotators and for a small share of samples by two (dataset card).
- Rubric scoring. Someone first writes a rubric for the prompt (a checklist of weighted criteria); a grader then marks each criterion for each response. The record is a score per rubric item. It becomes a rubric reward (weighted sum) and, later, instructions for an AI grader.
- Critique. The annotator highlights a span of the response and attaches a comment and severity. The record is a list of (span, comment, severity). It becomes training data for critic models and fine-grained error labels. In the CriticGPT work (McAleese et al. 2024), critiques attached comments to quoted sections of code, and contractors also inserted bugs deliberately ("tampering") so that critique quality could be measured against a known bug.
- Rewrite or demonstration. The annotator edits the response, or writes one from scratch. The record is the new text plus the original. It becomes a supervised target and an implicit preference (edited over original).
- Live multi-turn session. The annotator converses with the model; at each model turn they see two candidate replies and pick one, which continues the conversation. The record is a sequence of turn-level choices. Bai et al. (2022) collected Anthropic's helpful and harmless data this way, with about four comparisons per conversation. Because the conversation follows the annotator's choices, later comparisons are on-distribution for the current model.
Process (step-level) labelling is a seventh pattern built from the others: the annotator walks through a multi-step solution and labels steps. In PRM800K (Lightman et al. 2023) labelers marked each step of a maths solution positive, negative or neutral, and in the second collection phase stopped labelling a solution at its first error; the released data has about 800,000 step-level labels. The agentic-transcript version is the subject of the next section.
W1 uses pairwise comparison with a four-level strength and an optional tie: each of the 24,000 labels records which underlying response was on the left, the choice and the strength. With the 8% tie rate, about 22,080 of the 24,000 labels carry an ordering usable for a reward-model pair, before overlap is aggregated and QA rejections are removed. W2 uses step labelling plus rewrite: a first-failing-step flag, a failure type and a corrected continuation of about 400 words. W3 uses two interfaces in sequence: a rubric editor (an expert writes 8 to 12 weighted items in about 25 minutes) and a rubric-scoring screen (a grader scores 4 responses at about 2 minutes each).
Comparison. Comparisons are fast and relatively consistent but carry little information each and say nothing about the reason. Ratings give absolute levels but drift between annotators (one annotator's 4 is another's 3). Rubrics make the standard explicit and transferable to an AI grader, at the cost of expert time to write them. Critiques and rewrites carry the most information per item and the explanation with it, but take longest and are hardest to quality-check.
What changes and what it costs. Moving from comparison to critique or rewrite raises time per item several-fold and moves quality control from agreement statistics to expert review. Moving from comparison to rubric shifts expert effort from labelling to standard-setting, which pays off only if the rubric is reused (by many graders or an AI grader).
What you would actually do. Start from the training signal the researcher needs (Chapter 1) and pick the cheapest interface that produces it without losing the information the signal requires. Default to pairwise with strength and ties for reward-model data; add a short required rationale only for strong preferences; use rewrite when both responses are often bad; use step labelling for multi-step work; and use rubrics when the standard must be applied many times. Store the raw record exactly as captured, including screen position, and convert it to training data in a separate, versioned step.
Choosing an interface type is a trade between three numbers per item: active time \(t\), usable yield \(y\) and information content. Information is hard to measure directly, so a practical proxy is the number of independent training constraints an item produces, discounted for correlation between them.
Pairs from rankings. A ranking of \(K\) responses implies \(\binom{K}{2} = K(K-1)/2\) ordered pairs: 6 for \(K = 4\), 36 for \(K = 9\). These pairs are not independent: they share responses and one annotator's reading. Ouyang et al. (2022) report that shuffling all pairs from rankings into one dataset made the reward model overfit, and they instead trained on all pairs from one prompt as a single batch element. The design implication is that a \(K\)-way ranking is worth more than one pair but far less than \(\binom{K}{2}\) independent pairs.
Strength and ties. If the reward model is trained with a Bradley–Terry loss, the probability that response \(a\) beats \(b\) is modelled as \(\sigma(r_a - r_b)\), where \(r\) is the scalar reward and \(\sigma\) the logistic function. A strength label can enter as a margin \(m\): the loss is \(-\log \sigma(r_a - r_b - m)\), so strong preferences must be separated by more. Llama 2 used such a rating-dependent margin (Touvron et al. 2023). Ties carry no ordering for this loss and are dropped or modelled separately, so the tie rate \(\tau\) directly reduces yield: \(y = (1-\tau)(1-q)\) where \(q\) is the QA rejection rate.
The W1 plan counts 20,000 comparisons less 8% QA rejections, about 18,400 useful comparisons at \(\$75{,}780 / 18{,}400 \approx \$4.12\) each. Ties (8%) stay in that count, but they carry no ordering for a Bradley–Terry loss, so about \(18{,}400 \times 0.92 \approx 16{,}900\) become ordered reward-model pairs, at about $4.48 per ordered pair. If the tie rate rose to 19%, the same spend would buy about \(18{,}400 \times 0.81 \approx 14{,}900\) ordered pairs, roughly $5.08 each: a 12% loss of yield from one interface parameter.
Time budgets. Active time per item scales with how much text must be read and how much must be written. Writing dominates: a corrected continuation of a few hundred words takes far longer than any choice. A rough model is \(t \approx t_{\text{read}} + t_{\text{decide}} + t_{\text{write}}\), and the interface can shrink \(t_{\text{read}}\) (navigation, collapsing irrelevant output) but should not shrink \(t_{\text{decide}}\).
| Type | Record | Typical training use | Main yield loss | Main bias risk |
|---|---|---|---|---|
| Pairwise + strength | choice, strength, side | RM pairs with margin | ties | position, length |
| K-way ranking | order of K | \(\binom{K}{2}\) correlated pairs | partial rankings | primacy in long lists |
| Likert / attributes | score per attribute | pointwise RM, filters | scale drift | annotator leniency |
| Rubric scoring | score per item | rubric reward, AI-grader spec | ambiguous items | rubric author's framing |
| Critique | (span, comment, severity) | critic data, error labels | nitpicks, missed bugs | anchoring on AI critique |
| Rewrite | edited text + original | SFT target, implicit pair | minimal edits | style imposed by editor |
| Live session | choice per turn | on-policy pairs | short conversations | topic self-selection |
| Step labels | label per step or first failure | process reward data | unlabelled suffix | stopping early |
Table. Interface types by record, training use, yield loss and bias risk.
W2 at 35 minutes per transcript and $120/h costs about $70 per item, but each item yields three things: a step-level label sequence (with a first failure at step \(k\), steps \(0..k-1\) are positive, step \(k\) negative and the rest unlabelled), a correction example of about 400 words, and an implicit pair (correction over the original suffix). W3's rubric writing costs 25 minutes per prompt (1,250 expert-hours for 3,000 prompts), while scoring costs 2 minutes per response (400 hours for 12,000 responses); the rubric amortises only because it is applied 4 times by humans and then many times by the AI grader.
What you would actually do. Price each candidate interface as cost per useful training constraint, not cost per item: \(w\,t / (y \cdot n_{\text{eff}})\), where \(n_{\text{eff}}\) is the effective number of independent constraints per item. Use pairwise with strength as the default for reward data, and switch only when a pilot shows the cheaper interface cannot express what the signal needs.
The build artifact for this section is the record layer: one typed record per interface type, stored exactly as captured, and pure functions that convert records into training examples. Keeping capture and conversion separate means a conversion bug can be fixed and rerun without re-collecting data, and the raw records remain the auditable source of truth (Chapter 7 covers schemas and versioning).
Two details matter more than they look. The pairwise record stores which underlying response was shown on the left, not "A" and "B" as the annotator saw them; the converter maps screen positions back to response ids. And the step-label converter leaves steps after the first failure unlabelled, because once an agent has made a mistake the later steps are conditioned on a broken state, the same reason PRM800K's second labelling phase stopped at the first error.
"""What each interface type yields, as typed records, and how each becomes training data.
Raw labels are stored exactly as the interface produced them (including screen position);
conversion to training examples is a separate, versioned step."""
from dataclasses import dataclass
from itertools import combinations
from typing import Literal, Optional
STRENGTH_MARGIN = {0: 0.0, 1: 1/3, 2: 2/3, 3: 1.0} # negligible/slight/better/significant (Llama-2-style scale)
@dataclass(frozen=True)
class PairwiseLabel: # W1: two responses side by side
item_id: str
left_response: str # response id shown on the LEFT for this assignment
right_response: str
choice: Literal['left', 'right', 'tie']
strength: int # 0..3, ignored for ties
rater: str
active_ms: int
@dataclass(frozen=True)
class RMPair:
item_id: str
chosen: str
rejected: str
margin: float
def pairwise_to_rm(l: PairwiseLabel) -> Optional[RMPair]:
"""Map screen positions back to response ids; ties carry no ordering for a BT loss."""
if l.choice == 'tie':
return None
chosen, rejected = ((l.left_response, l.right_response) if l.choice == 'left'
else (l.right_response, l.left_response))
return RMPair(l.item_id, chosen, rejected, STRENGTH_MARGIN[l.strength])
def ranking_to_pairs(item_id: str, ranked: list[str]) -> list[RMPair]:
"""A K-way ranking (best first) implies K*(K-1)/2 ordered pairs (InstructGPT used K = 4..9)."""
return [RMPair(item_id, a, b, 1.0) for a, b in combinations(ranked, 2)]
@dataclass(frozen=True)
class RubricScore: # W3: one grader, one response, one rubric
response_id: str
item_scores: dict[str, float] # rubric item id -> score in [0, 1]
weights: dict[str, float] # rubric item id -> weight
def rubric_reward(r: RubricScore) -> float:
w = sum(r.weights.values())
return sum(r.weights[k] * r.item_scores[k] for k in r.weights) / w
@dataclass(frozen=True)
class StepVerdict: # W2: first failing step on an agent transcript
transcript_id: str
n_steps: int
first_failing_step: Optional[int] # None = transcript judged correct
continuation: Optional[str]
def step_labels(v: StepVerdict) -> list[Optional[int]]:
"""PRM-style labels: 1 before the failure, 0 at it, None (unlabelled) after it.
Steps after the first failure are conditioned on a broken state, so they are not labelled."""
k = v.n_steps if v.first_failing_step is None else v.first_failing_step
return [1] * k + ([0] if k < v.n_steps else []) + [None] * max(0, v.n_steps - k - 1)
def correction_example(v: StepVerdict, prefix_text: str) -> Optional[dict]:
"""SFT/correction example: context = transcript prefix before the failing step,
target = expert continuation. The rejected original suffix can also form a preference pair."""
if v.first_failing_step is None or not v.continuation:
return None
return {'transcript_id': v.transcript_id, 'context': prefix_text, 'target': v.continuation,
'cut_at_step': v.first_failing_step}
The tests pin the W1, W2 and W3 shapes: position mapping, the tie yield, the number of pairs from a ranking, the W2 step labels for a flag at step 23 of 60, and a rubric reward.
from feedback_records import *
def test_position_is_mapped_back():
a = PairwiseLabel('w1_i1', 'resp_cand', 'resp_curr', 'right', 2, 'r7', 210_000)
p = pairwise_to_rm(a)
assert (p.chosen, p.rejected, round(p.margin, 2)) == ('resp_curr', 'resp_cand', 0.67)
assert pairwise_to_rm(PairwiseLabel('w1_i2', 'x', 'y', 'tie', 0, 'r7', 1)) is None
def test_w1_yield():
labels, tie_rate = 24_000, 0.08
assert round(labels * (1 - tie_rate)) == 22_080 # labels that become RM pairs
def test_ranking_pairs():
assert len(ranking_to_pairs('p', list('abcd'))) == 6
assert len(ranking_to_pairs('p', list('abcdefghi'))) == 36
def test_w2_step_labels():
lab = step_labels(StepVerdict('t1', 60, 23, 'fix'))
assert lab.count(1) == 23 and lab[23] == 0 and lab.count(None) == 36 and len(lab) == 60
assert step_labels(StepVerdict('t2', 60, None, None)) == [1] * 60
def test_w3_rubric_reward():
r = RubricScore('resp1', {'cites_statute': 1, 'defines_parties': 0.5, 'no_ambiguity': 0},
{'cites_statute': 3, 'defines_parties': 2, 'no_ambiguity': 1})
assert round(rubric_reward(r), 3) == 0.667
$ python3 -m pytest -q test_feedback_records.py
..... [100%]
5 passed
Debugging tips. If reward-model accuracy on held-out pairs is near 50% after a UI change, check the position mapping first: a converter that reads "left" as "chosen" silently scrambles every label that came from a randomised side. If the step-label dataset is dominated by positives, check how many verdicts are "no failure" and whether reviewers are stopping early (the flag-position histogram in the next section). Keep the strength-to-margin mapping in config, not code, so it can be changed in a reward-model ablation without touching labels.
In production, each interface type is a product with its own health metrics. The common ones are the yield funnel (assignments → submitted → valid → non-tie or non-empty → passed QA), active time per item (median and p90), and one type-specific distribution whose shape is known: tie rate and strength mix for pairwise, score histograms per attribute for ratings, comment counts and severity mix for critique, edit distance for rewrites, flag-position histograms for step labels.
Alert rules. Alert on movement of these distributions after a deploy, not on absolute values, because the right tie rate or score mix depends on the campaign. A practical rule: compare the last 1,000 submissions against the campaign's first 2,000 and alert if the tie rate changes by more than 5 points or the strength mix changes with a chi-square p-value under 0.001.
Symptom. On day 3 of collection, the W1 tie rate rises from 8% to 19% within a few hours of an interface release that restyled the strength buttons and made "About the same" a full-width button under the two responses. Median active time on tie labels is 2.1 minutes against 4.0 minutes overall.
Why it matters. Ties do not become ordered reward-model pairs. At 19% ties, 24,000 labels would yield 19,440 non-tie labels instead of 22,080, and the 18,400 useful comparisons would contain about 2,000 fewer ordered pairs (about $9,100 at $4.48 per ordered pair), plus a shift in which pairs remain (hard, close pairs are exactly the ones tied).
Diagnosis. Split tie rate by UI version: 8.3% on the old build, 18.7% on the new one, on interleaved assignments from the same raters, which rules out a change in prompt difficulty. Tie rate on gold pairs with a clear preferred answer rose too (from 2% to 9%), which shows ties are replacing judgements, not reflecting genuinely close pairs. The short active time on ties points to satisficing (choosing the low-effort option).
Remedy. Roll back the layout; restore ties as the centre option of the five-button scale; require a one-line reason for ties on items whose responses differ by more than a threshold in a cheap automatic similarity score. Re-queue the tied assignments from the affected window for a second rater (about 1,150 assignments, roughly 86 rater-hours or $3,450).
Validation. The fix is supported if the next 2,000 labels show a tie rate between 7% and 10%, tie rate on clear gold pairs back near 2%, and no fall in gold accuracy. It is weakened if ties fall but gold accuracy falls too: that would mean raters are now forced to guess on close pairs, and the tie option needs a better definition rather than a smaller button.
| Panel | Query (per campaign, per UI version) | Alert |
|---|---|---|
| Yield funnel | counts at each stage / assignments | any stage −3 points vs baseline |
| Tie rate | ties / submitted, rolling 1,000 | > ±5 points vs first 2,000 |
| Strength mix | share per strength level | chi-square p < 0.001 |
| Active time | median and p90 minutes, by choice type | median < 50% of plan |
| Gold tie rate | ties on gold items with a clear answer | > 5% |
Table. Interface-type health panels for a pairwise campaign (illustrative thresholds).
Reviewing long agentic transcripts
Definition. An agentic transcript is the full record of an agent working on a task: its messages, each tool call with arguments, each tool result (file contents, test output, web pages, command logs) and its final answer. A transcript review interface lets an expert read such a record, mark the first failing step (the earliest step after which the task can no longer succeed without a correction), label the failure type, and write a corrected continuation: what the agent should have done from that step on.
Why it is hard. Earlier feedback interfaces showed a prompt and one or two responses that fit on a screen. Agent transcripts are long documents with structure. A single transcript can run to "hundreds of thousands of tokens", in the words of Transluce's Docent announcement (Steinhardt 2025), and much of it is machine output that the expert needs only occasionally. Locating the first failure is also intrinsically hard: on the Who&When benchmark of multi-agent failure logs, the best automated method identified the decisive failure step only 14.2% of the time (Zhang et al. 2025). An interface that makes reading slow or navigation clumsy turns an expensive expert into an expensive scroller, and an interface that does not check what was read produces "first failing" flags that are merely the first failure the expert happened to notice.
How the interface works, in order.
- Load. The client fetches the assignment: step metadata (index, kind, token count) and a short preview of every step, but not the full bodies of large tool outputs. Those are fetched when the expert expands them.
- Render. The step list is virtualised: only the rows in and near the viewport are created in the page; the rest are represented by their estimated heights so the scrollbar is still correct. This keeps the first paint fast regardless of transcript length.
- Navigate. A rail shows every step as a small cell coloured by state (read, unread, flagged, current). Clicking a cell, typing a step number or pressing keyboard shortcuts jumps there. Tool outputs over a size threshold are collapsed to a head and tail with a "show full output" control.
- Track reading. A step counts as read once it has been the top visible step for about a second. The interface does not force reading, but it records it.
- Flag. The expert flags a step as the first failure, which dims everything after it and opens the label panel. A failure taxonomy (a fixed list such as wrong tool, bad arguments, misread tool output, unsupported claim, plan error, premature stop, unsafe action) makes failure types countable.
- Inspect state. For agents that change an environment (files, a database, a browser), a state view shows the environment as it was at the flagged step, reconstructed from the recorded tool results (for example, the files changed so far). This is state replay: the expert sees what the agent could have known at that moment without re-running anything.
- Write the continuation. The expert writes what the agent should have done from the flagged step onward. The text is tied to that flag: if the flag moves, the continuation must be re-checked, because it was written for a different prefix.
- Submit. Validation rules run in the browser and again on the server: a verdict exists, every step up to the flag (or every step, for "no failure") was read, a failure type is chosen, and the continuation length is within bounds. Drafts autosave throughout.
A W2 transcript has 60 steps and about 25,000 tokens. The expert reads steps 0 to 22 (seconds for short tool calls, minutes for long outputs), notices that at step 23 the agent claims the tests passed although the tool output at step 22 shows two failures, flags step 23 as misread_tool_output, checks the state view to confirm which files the agent had changed, and writes a 412-word continuation: rerun the failing tests, read the assertion, fix the parser edge case, rerun, then commit. Total: about 35 minutes. Because 10% of transcripts are double-reviewed, this one may be reviewed by a second expert; across the W2 pilot, two experts flag exactly the same step 58% of the time and within two steps 81% of the time.
Comparison with adjacent tools. Evaluation log viewers such as Inspect View from the UK AI Security Institute show an agent's message history, tool calls, scores and metadata, and filter samples by score (Inspect documentation). Docent focuses on analysing many transcripts at once to find environment bugs and unexpected behaviours. Both are built for reading; a review interface for training data adds a structured label, read tracking, validation and a written correction, and must be fast enough to be used for hours a day.
Contrast with step labelling of short solutions. PRM800K labelers rated each step of a maths solution and, in the second collection phase, stopped at the first error (Lightman et al. 2023). The idea carries over, but agent transcripts add tool outputs that are long and noisy, failures that only become visible several steps later, and corrections that need knowledge of the environment state.
What you would actually do. Build the reviewer around navigation and read tracking before adding any assistance: virtualised rendering with collapsed tool outputs, a step rail with jump-to-step, a flag that dims the suffix, a fixed failure taxonomy, a continuation tied to its flag, and validation that the prefix was read. Measure agreement within a tolerance window (±2 steps) alongside exact agreement, because exact agreement on the first failing step is low even among experts. Add AI assistance (a suggested failing step) only behind an experiment, for the anchoring reasons in the next section.
The design problem has three quantitative parts: render time against the 1.5-second target, expert time per transcript, and label agreement. Each has a back-of-envelope model.
Render size. At roughly 4 characters per token (an assumption that holds for English prose and code to within a factor of about 1.5), 25,000 tokens is about 100,000 characters. At about 95 characters per line and 20 px per line, a fully rendered transcript is about 1,050 lines or 21,000 px tall. A 900 px viewport shows about 4% of it. With a mean step height of about 350 px, the viewport holds 3 steps; with an overscan of 4 rows on each side, about 11 rows are mounted. If syntax highlighting produces around 5 elements per line, a full render creates on the order of 5,000 elements for text alone, a virtualised one a few hundred. The virtualised cost is roughly constant in transcript length; the naive cost is linear.
Navigation time. Let \(n\) be the number of steps, \(v\) the number of times the expert needs to revisit an earlier step (to check what a tool returned, or to compare the flag candidate with an earlier claim), and \(s\) the seconds per revisit. Scrolling cost grows with distance; a jump costs a near-constant few seconds. Friction is paid on every transcript, so small per-revisit savings add up.
Suppose a W2 expert makes \(v = 12\) revisits per transcript (an assumption to measure in the pilot from jump and scroll events). If scrolling to a target costs 15 s and a rail jump costs 4 s, jumps save \(12 \times 11 = 132\) s, about 2.2 minutes per transcript. Across 2,000 transcripts that is about 73 expert-hours, roughly $8,800 at $120/h, or 6% of the $140,000 labour budget. The same arithmetic prices the render budget: 2 extra seconds of load per transcript is only about 1.1 hours across the campaign, so render time matters mainly through what it does to flow (experts switching tasks while waiting), not through the seconds themselves.
Agreement. Let \(k_1, k_2\) be the steps two experts flag. Exact agreement is \(P(k_1 = k_2)\); tolerance agreement is \(P(|k_1 - k_2| \le \delta)\). Disagreement has two sources the interface can influence: coverage (one expert flagged a later step because they did not read the earlier one carefully) and definition (the experts disagree about whether an earlier misstep was already fatal). Read tracking addresses coverage; a written definition with examples addresses definition. The tolerance window also matters for training: a process reward model trained on flags that are off by one or two steps learns a blurred signal, so the export should carry both flags for double-reviewed items rather than one arbitrary choice.
With exact agreement 58% and ±2-step agreement 81%, 23% of double-reviewed pairs are near-misses (within 2 steps but not equal) and 19% are far apart. Of the 200 double-reviewed transcripts, about 38 are far apart; those go to adjudication, and their read-coverage events are checked first: if in most of them one expert never had steps before the other's flag on screen for a second, coverage is the main cause and the read-gate is the fix; if both read everything, the failure definition needs work.
| Decision | Options | Default | Deviate when |
|---|---|---|---|
| Long-list rendering | full render; pagination; virtualisation | virtualisation with measured heights | transcripts under ~30 short steps |
| Large tool outputs | inline; collapsed head/tail; separate pane | collapsed above ~2,000 tokens, lazy fetch | the output is the thing being judged |
| Navigation | scroll only; rail + jump + keys | rail, jump box, j/k/f keys | never drop jump for long transcripts |
| Read coverage | none; record; gate submit | record, gate on steps up to the flag | skimming is part of the task design |
| Continuation editor | inline after the flag; side panel | side panel, tied to the flag | continuations are short tool calls |
| State view | none; replay from tool results; live re-run | replay from recorded results | environment is cheap and deterministic |
Table. Design decisions for a long-transcript reviewer.
What you would actually do. Set a render budget and keep it (figure above splits 1.5 s), price navigation friction in expert-hours from pilot event logs, and report both exact and tolerance agreement with the coverage diagnosis attached. Most of the cost lever is in navigation and reading, not in raw render speed.
The build has two layers. reviewState.ts is a pure state model: a reducer over a discriminated union of actions plus a validate function. Keeping it free of React and the DOM means it can be unit-tested, replayed from the event log to reconstruct exactly what the expert saw and did, and imported by the server so the browser and the API enforce the same rules. TranscriptReview.tsx is the React component that renders the state with TanStack Virtual's useVirtualizer hook (TanStack Virtual v3 API), whose options include count, getScrollElement, estimateSize, overscan (default 1) and getItemKey, and whose instance exposes getVirtualItems(), getTotalSize(), measureElement and scrollToIndex(index, {align}).
validate function runs in the browser and on the server, so a label that passes one passes the other.State model. The state holds step metadata, the cursor, a per-step read flag, the verdict (first failing step or explicit "no failure"), the failure type, the continuation and the step it was written against, expanded outputs and autosave bookkeeping. Two rules carry the design: a verdict requires every step up to it to have been read, and a continuation written for one flag is invalid for another.
// reviewState.ts — pure state model for the W2 transcript-review interface.
// No React, no DOM: every transition is a function of (state, action), so it can be
// unit-tested, replayed from the event log, and shared by the server-side validator.
export type StepKind = 'user' | 'assistant' | 'tool_call' | 'tool_result';
export interface StepMeta {
idx: number; // 0-based position in the transcript
kind: StepKind;
tokens: number; // token count of the full step body
preview: string; // first ~200 chars, shipped with the assignment
largeOutput: boolean; // body > 2,000 tokens: fetched lazily on expand
}
export type FailureType =
| 'wrong_tool' | 'bad_arguments' | 'misread_tool_output' | 'unsupported_claim'
| 'plan_error' | 'premature_stop' | 'unsafe_action' | 'other';
export type Status = 'loading' | 'reviewing' | 'submitting' | 'submitted' | 'error';
export interface ReviewState {
assignmentId: string;
status: Status;
steps: StepMeta[];
cursor: number; // step the reviewer is focused on
visited: boolean[]; // step was on screen for >= dwell threshold
firstFailingStep: number | null;
noFailure: boolean; // explicit "transcript is correct" verdict
failureType: FailureType | null;
continuation: string; // corrected continuation from the failing step
continuationForStep: number | null; // flag the continuation was written against
expanded: number[]; // steps whose full tool output is open
dirty: boolean; // unsaved local edits
savedVersion: number; // server draft version (optimistic concurrency)
error: string | null;
}
export type Action =
| { type: 'LOADED'; assignmentId: string; steps: StepMeta[] }
| { type: 'FOCUS'; idx: number; via: 'scroll' | 'jump' | 'key' | 'rail' }
| { type: 'VISITED'; idx: number }
| { type: 'FLAG'; idx: number }
| { type: 'CLEAR_FLAG' }
| { type: 'MARK_NO_FAILURE' }
| { type: 'SET_FAILURE_TYPE'; failureType: FailureType }
| { type: 'EDIT_CONTINUATION'; text: string }
| { type: 'TOGGLE_OUTPUT'; idx: number }
| { type: 'SAVED'; version: number }
| { type: 'SUBMIT' }
| { type: 'SUBMIT_OK' }
| { type: 'SUBMIT_FAIL'; error: string };
export const initialState = (assignmentId = ''): ReviewState => ({
assignmentId, status: 'loading', steps: [], cursor: 0, visited: [],
firstFailingStep: null, noFailure: false, failureType: null,
continuation: '', continuationForStep: null, expanded: [],
dirty: false, savedVersion: 0, error: null,
});
const clamp = (i: number, n: number) => Math.max(0, Math.min(n - 1, i));
export function reducer(s: ReviewState, a: Action): ReviewState {
if (s.status === 'submitted' && a.type !== 'LOADED') return s; // read-only after submit
switch (a.type) {
case 'LOADED':
return { ...initialState(a.assignmentId), status: 'reviewing', steps: a.steps,
visited: a.steps.map(() => false) };
case 'FOCUS':
return { ...s, cursor: clamp(a.idx, s.steps.length) };
case 'VISITED': {
if (s.visited[a.idx]) return s;
const visited = s.visited.slice(); visited[a.idx] = true;
return { ...s, visited };
}
case 'FLAG': {
const idx = clamp(a.idx, s.steps.length);
return { ...s, firstFailingStep: idx, noFailure: false, cursor: idx, dirty: true };
}
case 'CLEAR_FLAG':
return { ...s, firstFailingStep: null, failureType: null, dirty: true };
case 'MARK_NO_FAILURE':
return { ...s, noFailure: true, firstFailingStep: null, failureType: null,
continuation: '', continuationForStep: null, dirty: true };
case 'SET_FAILURE_TYPE':
return { ...s, failureType: a.failureType, dirty: true };
case 'EDIT_CONTINUATION':
// The continuation is written *against* a specific flag: remember which one.
return { ...s, continuation: a.text, continuationForStep: s.firstFailingStep, dirty: true };
case 'TOGGLE_OUTPUT': {
const open = s.expanded.includes(a.idx);
return { ...s, expanded: open ? s.expanded.filter(i => i !== a.idx) : [...s.expanded, a.idx] };
}
case 'SAVED':
return { ...s, dirty: false, savedVersion: a.version };
case 'SUBMIT':
return validate(s).length === 0 ? { ...s, status: 'submitting', error: null }
: { ...s, error: validate(s).join('; ') };
case 'SUBMIT_OK':
return { ...s, status: 'submitted', dirty: false };
case 'SUBMIT_FAIL':
return { ...s, status: 'reviewing', error: a.error };
}
}
export const wordCount = (t: string) => (t.trim() ? t.trim().split(/\s+/).length : 0);
/** Same rules run on the server before the label is accepted. */
export function validate(s: ReviewState, minWords = 150, maxWords = 900): string[] {
const errs: string[] = [];
if (!s.noFailure && s.firstFailingStep === null) errs.push('flag a failing step or mark "no failure"');
// "First failing step" is only meaningful if every earlier step was actually read.
const lastRequired = s.noFailure ? s.steps.length - 1 : (s.firstFailingStep ?? -1);
const unread = s.visited.slice(0, lastRequired + 1)
.map((v, i) => (v ? -1 : i)).filter(i => i >= 0);
if (unread.length) errs.push(`unread steps before verdict: ${unread.slice(0, 5).join(',')}${unread.length > 5 ? '…' : ''}`);
if (s.firstFailingStep !== null) {
if (!s.failureType) errs.push('choose a failure type');
const w = wordCount(s.continuation);
if (w < minWords || w > maxWords) errs.push(`continuation has ${w} words (allowed ${minWords}-${maxWords})`);
if (s.continuationForStep !== s.firstFailingStep) errs.push('flag moved after the continuation was written: re-check it');
}
return errs;
}
/** The record that leaves the browser; the export pipeline turns it into training data. */
export function toLabel(s: ReviewState, prefixHash: string) {
return {
assignment_id: s.assignmentId,
verdict: s.noFailure ? 'no_failure' : 'failure',
first_failing_step: s.firstFailingStep,
failure_type: s.failureType,
continuation: s.noFailure ? null : s.continuation,
prefix_hash: prefixHash, // hash of steps [0, first_failing_step)
steps_visited: s.visited.filter(Boolean).length,
steps_total: s.steps.length,
};
}
Tests build a W2-shaped transcript (60 steps, 25,000 tokens) and check the rules that protect label quality.
// Run: node --experimental-strip-types --test reviewState.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { reducer, initialState, validate, toLabel, type StepMeta, type Action, type ReviewState } from './reviewState.ts';
// A W2-shaped transcript: 60 steps, ~25,000 tokens in total.
const steps: StepMeta[] = Array.from({ length: 60 }, (_, i) => ({
idx: i, kind: (['assistant', 'tool_call', 'tool_result'] as const)[i % 3],
tokens: i % 3 === 2 ? 1000 : 125, preview: `step ${i}`, largeOutput: false,
}));
const words = (n: number) => Array.from({ length: n }, (_, i) => `w${i}`).join(' ');
const run = (acts: Action[], s: ReviewState = initialState()) => acts.reduce(reducer, s);
test('W2 transcript totals 60 steps and 25,000 tokens', () => {
assert.equal(steps.length, 60);
assert.equal(steps.reduce((t, s) => t + s.tokens, 0), 25_000);
});
test('a complete failure verdict validates and exports', () => {
const read = Array.from({ length: 24 }, (_, i): Action => ({ type: 'VISITED', idx: i }));
const s = run([{ type: 'LOADED', assignmentId: 'w2_a_0001', steps }, ...read,
{ type: 'FLAG', idx: 23 }, { type: 'SET_FAILURE_TYPE', failureType: 'misread_tool_output' },
{ type: 'EDIT_CONTINUATION', text: words(400) }, { type: 'SUBMIT' }]);
assert.equal(s.status, 'submitting');
const label = toLabel(s, 'sha256:abc');
assert.equal(label.first_failing_step, 23);
assert.equal(label.steps_visited, 24);
});
test('flagging before reading earlier steps is rejected', () => {
const s = run([{ type: 'LOADED', assignmentId: 'a', steps }, { type: 'VISITED', idx: 0 },
{ type: 'FLAG', idx: 10 }, { type: 'SET_FAILURE_TYPE', failureType: 'plan_error' },
{ type: 'EDIT_CONTINUATION', text: words(300) }, { type: 'SUBMIT' }]);
assert.equal(s.status, 'reviewing');
assert.match(s.error ?? '', /unread steps before verdict: 1,2,3,4,5…/);
});
test('moving the flag after writing the continuation forces a re-check', () => {
const read = Array.from({ length: 60 }, (_, i): Action => ({ type: 'VISITED', idx: i }));
const s = run([{ type: 'LOADED', assignmentId: 'a', steps }, ...read, { type: 'FLAG', idx: 30 },
{ type: 'SET_FAILURE_TYPE', failureType: 'wrong_tool' }, { type: 'EDIT_CONTINUATION', text: words(400) },
{ type: 'FLAG', idx: 28 }]);
assert.deepEqual(validate(s), ['flag moved after the continuation was written: re-check it']);
});
test('"no failure" requires reading every step and clears the continuation', () => {
const s = run([{ type: 'LOADED', assignmentId: 'a', steps }, { type: 'EDIT_CONTINUATION', text: 'x' },
{ type: 'MARK_NO_FAILURE' }]);
assert.equal(s.continuation, '');
assert.match(validate(s)[0], /unread steps/);
});
test('submitted state is read-only', () => {
const read = Array.from({ length: 60 }, (_, i): Action => ({ type: 'VISITED', idx: i }));
let s = run([{ type: 'LOADED', assignmentId: 'a', steps }, ...read, { type: 'MARK_NO_FAILURE' },
{ type: 'SUBMIT' }, { type: 'SUBMIT_OK' }]);
s = reducer(s, { type: 'FLAG', idx: 3 });
assert.equal(s.firstFailingStep, null);
assert.equal(s.status, 'submitted');
});
$ node --experimental-strip-types --test reviewState.test.ts
# tests 6
# pass 6
# fail 0
Component. Rows are absolutely positioned inside a spacer of getTotalSize() pixels and measured after mount through measureElement with a data-index attribute, so the height estimate only needs to be roughly right. The rail and the jump box call scrollToIndex(i, {align: 'start'}). The top visible step is derived from the virtual items and scroll offset; a one-second timer marks it read. Large outputs are fetched on expand and the fetch time is logged. Paste events in the continuation are logged by length only (never content), which feeds low-effort and LLM-assisted-writing detection in Chapter 6.
// TranscriptReview.tsx — W2 review screen: virtualised step list, step rail with
// jump-to-step, failing-step flag, failure type and corrected continuation.
import { useEffect, useReducer, useRef, useState, type KeyboardEvent } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
import { reducer, initialState, validate, type StepMeta, type FailureType } from './reviewState';
export interface StepBody { idx: number; text: string } // full body, fetched on demand
export interface Logger { (type: string, payload: Record<string, unknown>): void }
interface Props {
assignmentId: string;
steps: StepMeta[]; // metadata + previews only
loadBody: (idx: number) => Promise<StepBody>; // lazy full tool output
saveDraft: (draft: unknown, version: number) => Promise<number>; // returns new version
submit: (label: unknown) => Promise<void>;
log: Logger;
}
const DWELL_MS = 1000; // a step counts as read after 1 s as the top visible step
const FAILURES: FailureType[] = ['wrong_tool', 'bad_arguments', 'misread_tool_output',
'unsupported_claim', 'plan_error', 'premature_stop', 'unsafe_action', 'other'];
export function TranscriptReview({ assignmentId, steps, loadBody, saveDraft, submit, log }: Props) {
const [s, dispatch] = useReducer(reducer, initialState(assignmentId));
const [bodies, setBodies] = useState<Record<number, string>>({});
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
dispatch({ type: 'LOADED', assignmentId, steps });
log('assignment_loaded', { steps: steps.length, tokens: steps.reduce((t, x) => t + x.tokens, 0) });
}, [assignmentId, steps, log]);
// Only the rows near the viewport are mounted: ~8-15 of 60, never 25,000 tokens of DOM.
const v = useVirtualizer({
count: steps.length,
getScrollElement: () => scrollRef.current,
estimateSize: i => 56 + Math.min(steps[i].tokens, 600) * 0.5, // px guess, refined by measureElement
overscan: 4,
getItemKey: i => steps[i].idx,
});
// Track the top visible step; mark it read after DWELL_MS without moving.
const top = v.getVirtualItems().find(it => it.end > (v.scrollOffset ?? 0))?.index ?? 0;
useEffect(() => {
dispatch({ type: 'FOCUS', idx: top, via: 'scroll' });
const t = setTimeout(() => { dispatch({ type: 'VISITED', idx: top }); log('step_viewed', { step: top }); }, DWELL_MS);
return () => clearTimeout(t);
}, [top, log]);
// Autosave every 15 s when dirty; the server version guards against two open tabs.
useEffect(() => {
if (!s.dirty) return;
const t = setTimeout(async () => {
const version = await saveDraft({ ...s, visited: undefined }, s.savedVersion);
dispatch({ type: 'SAVED', version });
}, 15_000);
return () => clearTimeout(t);
}, [s, saveDraft]);
const jump = (idx: number, via: 'jump' | 'rail' | 'key') => {
v.scrollToIndex(idx, { align: 'start' });
dispatch({ type: 'FOCUS', idx, via });
log('jump', { from: s.cursor, to: idx, via });
};
const flag = (idx: number) => { dispatch({ type: 'FLAG', idx }); log('flag_set', { step: idx }); };
const expand = async (idx: number) => {
dispatch({ type: 'TOGGLE_OUTPUT', idx });
if (!bodies[idx]) {
const t0 = performance.now();
const b = await loadBody(idx);
setBodies(m => ({ ...m, [idx]: b.text }));
log('output_expanded', { step: idx, fetch_ms: Math.round(performance.now() - t0) });
}
};
const onKey = (e: KeyboardEvent) => { // j/k move, f flags the focused step
if ((e.target as HTMLElement).tagName === 'TEXTAREA') return;
if (e.key === 'j') jump(Math.min(s.cursor + 1, steps.length - 1), 'key');
if (e.key === 'k') jump(Math.max(s.cursor - 1, 0), 'key');
if (e.key === 'f') flag(s.cursor);
};
const errors = validate(s);
return (
<div className="review" onKeyDown={onKey} tabIndex={0}>
<nav className="rail" aria-label="Steps">
{steps.map(st => (
<button key={st.idx} onClick={() => jump(st.idx, 'rail')}
className={[st.kind, s.visited[st.idx] ? 'read' : '', s.firstFailingStep === st.idx ? 'flagged' : '',
s.cursor === st.idx ? 'cursor' : ''].join(' ')}
aria-label={`Step ${st.idx}, ${st.kind}`}>{st.idx}</button>
))}
<input type="number" min={0} max={steps.length - 1} placeholder="Go to step"
onKeyDown={e => { if (e.key === 'Enter') jump(Number((e.target as HTMLInputElement).value), 'jump'); }} />
</nav>
<div ref={scrollRef} className="transcript" style={{ overflow: 'auto', height: '100%' }}>
<div style={{ height: v.getTotalSize(), position: 'relative' }}>
{v.getVirtualItems().map(it => {
const st = steps[it.index];
const open = s.expanded.includes(st.idx);
return (
<div key={it.key} data-index={it.index} ref={v.measureElement}
style={{ position: 'absolute', top: 0, left: 0, width: '100%', transform: `translateY(${it.start}px)` }}
className={s.firstFailingStep !== null && st.idx > s.firstFailingStep ? 'step after-flag' : 'step'}>
<header>#{st.idx} · {st.kind} · {st.tokens} tok
<button onClick={() => flag(st.idx)}>Flag as first failure</button></header>
<pre>{open ? (bodies[st.idx] ?? 'loading…') : st.preview}</pre>
{st.largeOutput && <button onClick={() => expand(st.idx)}>{open ? 'Collapse' : 'Show full output'}</button>}
</div>
);
})}
</div>
</div>
<aside className="label-panel">
<p>First failing step: {s.firstFailingStep ?? (s.noFailure ? 'none (correct)' : 'not set')}</p>
<button onClick={() => dispatch({ type: 'MARK_NO_FAILURE' })}>No failure</button>
<select value={s.failureType ?? ''} disabled={s.firstFailingStep === null}
onChange={e => dispatch({ type: 'SET_FAILURE_TYPE', failureType: e.target.value as FailureType })}>
<option value="" disabled>Failure type…</option>
{FAILURES.map(f => <option key={f} value={f}>{f}</option>)}
</select>
<textarea disabled={s.firstFailingStep === null} value={s.continuation}
placeholder="Corrected continuation from the flagged step (~400 words)"
onChange={e => dispatch({ type: 'EDIT_CONTINUATION', text: e.target.value })}
onPaste={e => log('paste', { chars: e.clipboardData.getData('text').length })} />
{errors.length > 0 && <ul className="errors">{errors.map(x => <li key={x}>{x}</li>)}</ul>}
<button disabled={errors.length > 0 || s.status !== 'reviewing'}
onClick={async () => {
dispatch({ type: 'SUBMIT' });
try { await submit(s); dispatch({ type: 'SUBMIT_OK' }); log('submit', { ok: true }); }
catch (err) { dispatch({ type: 'SUBMIT_FAIL', error: String(err) }); log('submit', { ok: false }); }
}}>Submit</button>
</aside>
</div>
);
}
$ npx tsc -p . # strict, React 18 types, @tanstack/react-virtual 3.x
$ echo $?
0
Debugging tips. If rows jump while scrolling, the item key is unstable (use the step index from the data, not the array position after filtering) or a collapsed output changed height without being re-measured. If the read counter lags, the dwell timer is being reset by scroll events from inside a row; derive the top step from the virtualiser, not from intersection callbacks on every element. If autosave conflicts appear (HTTP 409), two tabs are open on one assignment; the server's draft version is the tie-breaker and the client should show a "newer draft elsewhere" notice instead of overwriting.
Operating a transcript reviewer means watching three things at once: the interface's own performance (render and interaction latency), expert throughput (active minutes per transcript), and label health (agreement and the distribution of flag positions). They are linked: a slow interface lengthens reviews and, when experts start skimming to compensate, shifts flags.
| SLO / metric | Definition | Target | Alert |
|---|---|---|---|
| Render p95 | assignment request → rows painted | ≤ 1.5 s | > 2 s for 30 min |
| Expand p95 | "show full output" → text visible | ≤ 800 ms | > 1.5 s for 30 min |
| Active minutes / transcript | median, daily | plan ± 15% (35 min) | > 40 or < 25 |
| Read-gate blocks | submit attempts blocked for unread steps / attempts | < 10% | > 15% (gate too strict, or skimming) |
| Agreement | exact and ±2 on double reviews, weekly | baseline 58% / 81% | ±2 drops > 8 points |
| Lost drafts | drafts lost / started | 0 | any |
Table. SLOs for the W2 reviewer (illustrative targets derived from the W2 plan).
Symptom. On days 6 and 7, render p95 rises from about 1.2 s to 2.9 s and 3.1 s, and median active minutes per transcript rise from 35 to 41 and 43. No errors are logged.
Why it matters. At 600 expert-hours a week, about 86 hours a day, the pool reviews about 147 transcripts a day at 35 minutes. Over two days, about 294 transcripts took 6 to 8 extra minutes each: roughly 2,060 minutes, 34 expert-hours or about $4,100, and the campaign slips by about half a day.
Diagnosis. Split render p95 by transcript batch: the slow renders all come from a new batch of transcripts generated with a longer test suite, whose tool results include logs of 30,000 to 40,000 tokens. Their step metadata shows largeOutput = false. The ingest job computed the large-output flag from a character count against a threshold written in tokens, so outputs four times over the limit were treated as small and rendered eagerly. The output_expanded event count for that batch is near zero, which confirms nothing was collapsed.
Remedy, step by step. (1) Hot-fix the client to collapse any step whose body size, as reported by the server, exceeds 8,000 characters, regardless of the flag. (2) Fix the ingest job to compute tokens with the same tokenizer as the threshold, and backfill the flag for the affected batch. (3) Add a contract test in ingest: for 100 sampled steps, flag agreement between the character and token rules must be above 99%. (4) Add a per-batch render p95 panel so a single bad batch is visible before it moves the global p95.
Trade-off. The client-side guard duplicates logic that belongs in ingest, but it bounds the damage of any future metadata bug at the cost of one more threshold to keep in sync.
Validation. The fix is supported if render p95 for the affected batch returns under 1.5 s and active minutes return to within 15% of 35 over the next 150 transcripts, while flags on those transcripts do not shift earlier (a shift would mean experts had been compensating by skimming). It is weakened if render recovers but active minutes stay high: then the long outputs themselves, not their rendering, are costing reading time, and the task needs an output summary or a search box inside large outputs.
Runbook: slow reviews. (1) Check render and expand p95 by batch and by browser; if one batch dominates, inspect its step metadata. (2) If rendering is normal, check active minutes by step count and token count; if time scales with tokens, the task has grown, and the plan needs re-pricing rather than an interface fix. (3) Check jump and scroll counts per transcript; a rise in scroll distance with flat jumps suggests a navigation regression (for example, a broken rail after a release). (4) Check flag-position histograms for the same window before concluding that slow reviews did not affect labels.
Designing for data quality: bias, effort, fatigue, instrumentation
Definition. An interface-induced bias is a systematic shift in labels caused by how the item is presented or collected rather than by the item itself. It differs from random noise: noise averages out as more annotators label the same item, bias does not, because every annotator is pushed the same way. Four biases matter most for RL feedback interfaces: position, length, anchoring and fatigue. Two further topics complete the design: effort (whether the annotator actually did the work the label claims) and instrumentation (the event record that lets the platform measure all of the above).
Why the interface is the place to act. Guidelines can tell annotators to ignore length or position, but people cannot reliably ignore cues they can see. The interface can change what they see and in what order, and it can record behaviour that reveals the bias. Each bias below gets the same treatment: what it is, the evidence, the interface mitigation and the statistic that tells whether the mitigation works.
Position. In a side-by-side comparison, an annotator who is unsure, rushed or did not read both responses may favour one slot. A study comparing human and LLM judges found human position preference small (first and second preferred at nearly equal rates), while several LLM judges showed strong positional preferences (Chen et al. 2024). Small on average does not mean absent for every annotator or every layout. The mitigation is to randomise which response appears on which side for every assignment, store the side with the label, and audit the share of non-tie choices that went left: under randomisation its expected value is exactly 50%.
Length and style. Longer, more confident or more richly formatted responses tend to be preferred whether or not they are better. Singhal et al. (2023) found that in several RLHF settings most of the measured reward improvement could be explained by longer outputs, and that optimising for length alone reproduced most of the gains. Hosking et al. (2024) found that assertiveness changes how often annotators notice factual errors, and Chen et al. found human judges susceptible to "rich content" such as formatting and emojis. Length bias in labels is the root of length bias in reward models. The interface cannot hide length, but it can show word counts so length is a conscious factor, ask for a reason on strong preferences, and include probe pairs whose shorter response is known to be better; the share of probes where the longer response wins measures the bias directly.
Anchoring and order. Anything the annotator sees before forming a judgement can pull the judgement towards it: an AI pre-label, a previous annotator's answer, or the items seen earlier in the session. Scholer et al. (2013) showed "threshold priming" in relevance assessment: assessors who first saw low-relevance documents rated later ones more generously. Beck et al. (2024) report that annotation labels shift with the order of items. With AI suggestions, Beck et al. (2025) ran a 2,784-person experiment in which crowdworkers checked AI pre-annotations; errors that required knowing the annotation rules were caught only 31% of the time, and workers with favourable attitudes to AI accepted more wrong suggestions. A 2026 video-labelling pilot found that pre-annotations made annotators agree more with each other without changing agreement with the consensus (Gutiérrez et al. 2026), which is the pattern to watch: assistance can manufacture agreement. Mitigations: judge first, then reveal (the annotator commits a first judgement before seeing any AI suggestion), randomised item order within a session, and planted wrong suggestions whose follow rate measures anchoring. Chapter 9 treats model-assisted annotation in depth.
Fatigue. Quality may fall late in long sessions. The evidence is mixed and should be measured per campaign rather than assumed. Over months, crowd worker quality was "extremely stable" in a study of about nine million annotations, falling only about 1.5% over a worker's lifetime (Hata et al. 2017). Within a working day, effects can appear: a study of more than 35,000 prostate MRI reads found small but significant drift in scores towards the end of radiologists' shifts (reported by Radiology Business on a European Journal of Radiology study). Interface mitigations: a session cap with a break prompt, short items interleaved with long ones, and gold accuracy plotted against position in the session.
Effort. A label can be well-formed but unearned: chosen in seconds, pasted from another tool, or flagged without reading. The interface measures effort through active time (visible, non-idle time), read coverage, scroll and jump events, and paste events. These feed the detection methods in Chapter 6; the interface's job is to log them reliably and without collecting content the annotator types.
Instrumentation. Every interaction worth reasoning about becomes an event with a fixed envelope: unique id, schema version, per-session sequence number, client timestamp, pseudonymous annotator id, assignment, campaign, experiment arm, and a small typed payload. The sequence number makes loss measurable; the arm makes experiments possible; the pseudonym keeps names and emails out of telemetry.
In W1, sides are randomised per assignment and the left share is audited daily; 300 probe pairs (an illustrative number) measure length preference; sessions are capped and gold accuracy is plotted by position in the session; 4% of raters are flagged for low effort because their median active time is under 40 seconds against a campaign median of 4.0 minutes. In W2, the AI-suggested failing step is hidden until the expert has flagged a step, and in the hint experiment 100 of the 500 transcripts in the hint arm (20%) carry a deliberately wrong suggestion, so that anchoring can be measured.
Architecture. In a TypeScript/React front end the mitigations live in a shared shell, not in each screen: one assignment loader, one logger, one experiment-arm provider, one autosave, and a registry of interface types where each entry supplies its component, validation, and label format. Side randomisation, judge-first reveal and session caps are then properties of the shell that every new interface type inherits.
What you would actually do. Randomise sides and item order by default; never show an AI suggestion before the first judgement unless an experiment shows it is safe; plant probes and wrong suggestions at a few percent of items; log events with sequence numbers from the first campaign; and track each bias as a statistic with a known expected value.
Every bias statistic here is a proportion compared with a reference value, so the core arithmetic is the standard error of a proportion, \(\text{SE} = \sqrt{p(1-p)/n}\), for \(n\) labels and proportion \(p\). The design questions are how large \(n\) must be to see the bias and how much the bias costs if it goes unseen.
Position. Let \(L\) be the share of non-tie choices for the left slot. Model a biased annotator as one who, on a fraction \(f\) of items, picks left without judging. Under randomised sides, \(E[L] = (1-f)\cdot 0.5 + f = 0.5 + f/2\), and those \(f\) labels agree with the true preference only half the time: randomisation turns position bias into noise. Without randomisation (for example, the candidate model always on the left), the same \(f\) becomes a systematic shift of \(f/2\) in the candidate's win rate, which no overlap can remove.
W1 produces about 22,080 non-tie labels. At \(L = 0.5\), \(\text{SE} = \sqrt{0.25/22{,}080} \approx 0.0034\), so a campaign-level shift of 0.7 points is detectable at 95%. Each rater contributes about 147 non-tie labels (\(\text{SE} \approx 0.041\)); testing 150 raters with a Bonferroni correction needs \(|z| > 3.59\), so a rater is flagged only if their left share is outside about 35% to 65%. Campaign monitoring catches a layout problem; per-rater monitoring catches only strong habits. If 4% of labels were position-driven and sides were fixed, the candidate's win rate would be inflated by 2 points.
Length. On all pairs, the longer response may genuinely be better more often, so the raw "longer wins" rate is not a bias measure. The clean measure is on probe pairs where the shorter response is known to be better: the longer-wins rate on probes is an error rate attributable to length (and to whatever else the padded response carries).
Illustratively, the longer response wins 61% of all W1 pairs and 39% of 300 probe pairs (117 of 300, 95% Wilson interval 34% to 45%). Against gold accuracy of about 85% on ordinary gold items, the probes show a much higher error rate when the wrong answer is the longer one. The interface response is to show word counts and require a reason on strong preferences for the longer response; the modelling response (length-controlled reward training) belongs to Chapter 8.
Anchoring. Let \(a\) be the rate at which annotators follow a deliberately wrong suggestion, and \(a_0\) the rate at which annotators without the suggestion independently choose the same wrong answer. The anchoring effect is \(a - a_0\). Measuring it costs planted items: with 100 planted items per arm, a 95% interval on a rate near 0.2 is about ±8 points, enough to see a 15-point effect but not a 5-point one.
Illustratively, when the W2 interface shows an AI-suggested failing step before the expert has looked, experts follow 27 of 100 planted wrong suggestions (95% interval 19% to 36%). With judge-first reveal, 12 of 100 (7% to 20%). Without any suggestion, experts flag the same wrong step on about 10% of those transcripts, so hint-first anchoring adds about 17 points and judge-first about 2.
Fatigue. Plot gold accuracy against position in the session. Gold items are a small share of assignments, so curves must be pooled across annotators; per-annotator fatigue curves are too noisy to act on.
W1 has about 1,263 gold assignments (5% of 25,260). Split into five position buckets of 15 items (one hour each at 4 minutes per label), that is about 250 gold labels per bucket. Illustrative accuracies of 86% in the first bucket and 78% after 60 items differ by 8 points with a standard error of about 3.4 points (\(z \approx 2.3\)): detectable over the whole campaign, not in a day. A three-hour session cap would move the late-session items into fresh sessions; whether that is worth the scheduling cost depends on whether the curve reproduces in the next campaign.
Effort. Active time is the sum of gaps between consecutive events that are shorter than an idle threshold \(\theta\) (60 seconds by default) while the page is visible. A floor rule flags labels or annotators whose active time is implausibly short relative to the campaign median.
| Bias | Interface mitigation | Statistic | Expected value | Items needed |
|---|---|---|---|---|
| Position | randomise sides; store side | left share of non-tie | 50% | all labels (free) |
| Length | word counts; reason on strong prefs | longer-wins on probes | low (probe design) | ~1% probe pairs |
| Anchoring | judge first, then reveal | follow rate on planted wrong hints | ≈ no-hint baseline | ~5–10% of assisted items |
| Order | randomise item order | label mean vs item position | flat | all labels (free) |
| Fatigue | session cap, breaks | gold accuracy by session position | flat | gold items (existing) |
| Effort | read gates; visible timers off | active time vs median; read coverage | above floor | all labels (free) |
Table. Bias mitigations and their audit statistics (probe and planted shares are illustrative defaults).
What you would actually do. Budget probe and planted items explicitly in the campaign spec (they are paid labels that do not become training data), and size them from the standard-error arithmetic above so each statistic can detect the effect size you would act on.
The build artifacts are the instrumentation contract (a JSON Schema for the event envelope), a browser logger, the active-time derivation, the bias audit, and the interface-type registry that keeps mitigations in a shared shell.
Event schema. The envelope is strict (additionalProperties: false), versioned, and pseudonymous by pattern: an email in the annotator field fails validation at ingest.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "ui_event.v3",
"type": "object",
"required": ["event_id", "schema_version", "type", "seq", "client_ts", "session_id",
"assignment_id", "campaign_id", "annotator", "ui_variant", "payload"],
"properties": {
"event_id": {"type": "string", "description": "UUID generated on the client; dedup key at ingest"},
"schema_version": {"const": 3},
"type": {"enum": ["assignment_loaded", "item_rendered", "step_viewed", "jump", "output_expanded",
"flag_set", "flag_cleared", "label_changed", "ai_suggestion_shown",
"ai_suggestion_accepted", "text_edit", "paste", "visibility", "idle",
"autosave", "validation_error", "submit"]},
"seq": {"type": "integer", "minimum": 0, "description": "per-session counter; gaps = lost events"},
"client_ts": {"type": "integer", "description": "ms since epoch, client clock"},
"server_ts": {"type": "integer", "description": "set at ingest; used to estimate clock skew"},
"session_id": {"type": "string"},
"assignment_id": {"type": "string"},
"campaign_id": {"type": "string"},
"annotator": {"type": "string", "pattern": "^anon_[0-9a-f]{16}$", "description": "pseudonym, never a name or email"},
"ui_variant": {"type": "string", "description": "experiment arm, e.g. 'w2_rail_v2:B'"},
"payload": {"type": "object", "description": "type-specific; never free text typed by the annotator"}
},
"additionalProperties": false
}
event_id at ingest. Labels live in a separate store and join on assignment_id.Browser logger. Events are buffered and flushed every 5 seconds or 50 events, and flushed with navigator.sendBeacon when the page becomes hidden. MDN describes the transition to hidden as the last event that is reliably observable by the page and recommends it for sending analytics (MDN, visibilitychange).
// uiLogger.ts — batched, loss-aware UI event logger (browser).
export interface Envelope {
event_id: string; schema_version: 3; type: string; seq: number; client_ts: number;
session_id: string; assignment_id: string; campaign_id: string; annotator: string;
ui_variant: string; payload: Record<string, unknown>;
}
type Ctx = Pick<Envelope, 'session_id' | 'assignment_id' | 'campaign_id' | 'annotator' | 'ui_variant'>;
export function createLogger(ctx: Ctx, url = '/v1/ui-events', maxBatch = 50, flushMs = 5000) {
let seq = 0; let buf: Envelope[] = [];
const flush = (beacon = false) => {
if (!buf.length) return;
const body = JSON.stringify(buf); buf = [];
// sendBeacon survives tab close; fetch keepalive is the fallback (both limit body size, so keep batches small).
if (beacon && navigator.sendBeacon(url, body)) return;
void fetch(url, { method: 'POST', body, keepalive: true, headers: { 'content-type': 'application/json' } });
};
const timer = setInterval(() => flush(), flushMs);
document.addEventListener('visibilitychange', () => {
log('visibility', { state: document.visibilityState });
if (document.visibilityState === 'hidden') flush(true); // last reliable moment to send
});
function log(type: string, payload: Record<string, unknown>) {
buf.push({ event_id: crypto.randomUUID(), schema_version: 3, type, seq: seq++,
client_ts: Date.now(), ...ctx, payload });
if (buf.length >= maxBatch) flush();
}
return { log, close: () => { clearInterval(timer); flush(true); } };
}
Active time and loss. Events are ordered by sequence number rather than client timestamp, because client clocks jump. Gaps longer than the idle threshold, or while the page is hidden, do not count.
"""Active time per assignment from UI events. Wall-clock time overstates effort (tabs left open,
breaks); active time counts only gaps <= idle_ms while the page was visible."""
def active_ms(events, idle_ms=60_000):
ev = sorted(events, key=lambda e: e['seq']) # seq, not client_ts: clocks jump
total, visible = 0, True
for prev, cur in zip(ev, ev[1:]):
gap = cur['client_ts'] - prev['client_ts']
if visible and 0 <= gap <= idle_ms:
total += gap
if cur['type'] == 'visibility':
visible = cur['payload']['state'] == 'visible'
return total
def lost_events(events):
"""Sequence gaps reveal dropped beacons; alert when the lost share exceeds ~0.5%."""
seqs = sorted(e['seq'] for e in events)
return (seqs[-1] - seqs[0] + 1) - len(set(seqs)) if seqs else 0
Bias audit. Each function returns a small dictionary that a dashboard panel or alert reads directly.
"""Interface-bias audit over raw labels. Input rows are dicts as stored by the label service:
{'rater','choice' in left/right/tie,'len_left','len_right','session_idx','gold_correct' (or None),
'ai_shown','ai_wrong','followed_ai'}. Output: small dicts that dashboards and alerts read."""
from math import sqrt, log, exp
from statistics import NormalDist
from collections import defaultdict
def wilson(k, n, z=1.96):
if n == 0: return (0.0, 1.0)
p = k / n; d = 1 + z * z / n
c = (p + z * z / (2 * n)) / d; h = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
return (c - h, c + h)
def position_bias(rows, min_n=100, alpha=0.05):
"""Share of non-tie choices that went to the LEFT slot. With randomised sides the truth is 0.5;
a campaign-level deviation is a UI or population problem, a per-rater deviation is a habit."""
nt = [r for r in rows if r['choice'] != 'tie']
k = sum(r['choice'] == 'left' for r in nt); n = len(nt)
z = (k / n - 0.5) / sqrt(0.25 / n)
per = defaultdict(lambda: [0, 0])
for r in nt: per[r['rater']][0] += r['choice'] == 'left'; per[r['rater']][1] += 1
m = sum(1 for v in per.values() if v[1] >= min_n)
zc = NormalDist().inv_cdf(1 - alpha / (2 * max(m, 1))) # Bonferroni across raters
flagged = sorted(a for a, (kk, nn) in per.items()
if nn >= min_n and abs(kk / nn - 0.5) / sqrt(0.25 / nn) > zc)
return {'left_share': k / n, 'n': n, 'z': z, 'ci': wilson(k, n), 'raters_flagged': flagged}
def length_preference(rows, ratio=1.5):
"""Among non-tie pairs where one response is >= ratio x longer, how often the longer one wins.
Compare against the same statistic on gold pairs where the reference answer is known."""
k = n = 0
for r in rows:
if r['choice'] == 'tie': continue
a, b = r['len_left'], r['len_right']
if max(a, b) < ratio * min(a, b): continue
n += 1; k += (r['choice'] == 'left') == (a > b)
return {'longer_wins': k / n if n else None, 'n': n, 'ci': wilson(k, n)}
def anchoring(rows):
"""On items where the AI suggestion was deliberately wrong, how often the label followed it."""
w = [r for r in rows if r.get('ai_shown') and r.get('ai_wrong')]
k = sum(r['followed_ai'] for r in w)
return {'followed_wrong_ai': k / len(w) if w else None, 'n': len(w), 'ci': wilson(k, len(w))}
def fatigue_curve(rows, bucket=10):
"""Gold accuracy by position within a session (items 0-9, 10-19, ...)."""
acc = defaultdict(lambda: [0, 0])
for r in rows:
if r.get('gold_correct') is None: continue
b = r['session_idx'] // bucket; acc[b][0] += r['gold_correct']; acc[b][1] += 1
return {b * bucket: (k / n, n) for b, (k, n) in sorted(acc.items())}
The tests simulate the W1 campaign (150 raters, 160 labels each, 8% ties) to check that a clean campaign raises no position flags, that six habitual raters picking left 80% of the time are found, and that the active-time rule turns a 14-minute wall-clock label with a 10-minute hidden break into 4.0 active minutes.
import random
from bias_audit import *
def simulate_w1(seed=0, left_habit=None):
"""24,000 W1 labels from 150 raters (160 each); 8% ties; sides randomised.
left_habit: {rater: p} -> that rater picks LEFT with prob p when not tying."""
rng = random.Random(seed); rows = []
for r in range(150):
for i in range(160):
ll, lr = rng.randint(80, 900), rng.randint(80, 900)
if rng.random() < 0.08: ch = 'tie'
else:
p_left = (left_habit or {}).get(r, 0.5)
ch = 'left' if rng.random() < p_left else 'right'
rows.append({'rater': r, 'choice': ch, 'len_left': ll, 'len_right': lr,
'session_idx': i % 15, 'gold_correct': (rng.random() < 0.85) if i % 20 == 0 else None})
return rows
def test_clean_campaign_has_no_position_flag():
out = position_bias(simulate_w1())
assert abs(out['z']) < 3 and out['raters_flagged'] == [] and out['n'] > 21_000
def test_six_habitual_raters_are_found():
habit = {r: 0.80 for r in range(6)} # 4% of 150 raters
out = position_bias(simulate_w1(left_habit=habit))
assert set(range(6)) <= set(out['raters_flagged']) and len(out['raters_flagged']) <= 7
def test_length_and_anchoring_shapes():
lp = length_preference(simulate_w1())
assert 0.45 < lp['longer_wins'] < 0.55 # random choices -> no length effect
rows = [{'ai_shown': True, 'ai_wrong': True, 'followed_ai': i < 27} for i in range(100)]
a = anchoring(rows)
assert a['followed_wrong_ai'] == 0.27 and 0.19 < a['ci'][0] < 0.20
import json
from active_time import active_ms, lost_events
def ev(seq, t, typ='label_changed', **p):
return {'seq': seq, 'client_ts': t, 'type': typ, 'payload': p}
def test_w1_label_with_hidden_break():
s = 1_000_000
evs = [ev(0, s, 'item_rendered'), ev(1, s + 50_000), ev(2, s + 100_000),
ev(3, s + 120_000, 'visibility', state='hidden'), # rater switches tab
ev(4, s + 720_000, 'visibility', state='visible'), # 10 minutes later
ev(5, s + 760_000), ev(6, s + 800_000), ev(7, s + 840_000, 'submit')]
assert active_ms(evs) == 240_000 # 4.0 min, not 14 min wall
assert lost_events(evs) == 0 and lost_events(evs[:3] + evs[4:]) == 1
def test_schema_is_valid_json_and_pseudonymous():
sch = json.load(open('ui_event.schema.json'))
assert sch['properties']['annotator']['pattern'].startswith('^anon_')
assert 'paste' in sch['properties']['type']['enum']
def test_event_validates_against_schema():
import jsonschema
sch = json.load(open('ui_event.schema.json'))
e = {'event_id': '0b9f8c1e-1d2a-4c3b-9e8f-2a1b3c4d5e6f', 'schema_version': 3, 'type': 'flag_set',
'seq': 41, 'client_ts': 1762700000000, 'session_id': 's1', 'assignment_id': 'w2_a_0001',
'campaign_id': 'w2', 'annotator': 'anon_0123456789abcdef', 'ui_variant': 'w2_rail_v2:B',
'payload': {'step': 23}}
jsonschema.validate(e, sch)
bad = dict(e, annotator='jane@example.com')
try: jsonschema.validate(bad, sch); assert False
except jsonschema.ValidationError: pass
$ python3 -m pytest -q test_bias_audit.py test_active_time.py
...... [100%]
6 passed
Interface-type registry. The shell owns routing, assignment fetch, the logger, the experiment arm and autosave; each interface type registers a component, an empty draft, a validator shared with the server and a label builder. Side assignment uses a hash of the assignment id, so a reload shows the same layout and the stored side is reproducible.
// registry.ts — one entry per interface type; the shell (routing, assignment fetch, logger,
// experiment arm, autosave) is shared, and adding a feedback type means adding one entry.
import type { ComponentType } from 'react';
export interface InterfaceType<Item, Draft, Label> {
id: string; // 'pairwise_v4', 'transcript_review_v2', 'rubric_score_v1'
schemaVersion: number; // version of Label; bump on any shape change
Component: ComponentType<{ item: Item; draft: Draft; onChange: (d: Draft) => void; log: (t: string, p: Record<string, unknown>) => void }>;
emptyDraft: (item: Item) => Draft;
validate: (item: Item, draft: Draft) => string[]; // shared with the server
toLabel: (item: Item, draft: Draft) => Label; // what is stored; raw, position-aware
}
const registry = new Map<string, InterfaceType<any, any, any>>();
export function register<I, D, L>(t: InterfaceType<I, D, L>) {
if (registry.has(t.id)) throw new Error(`duplicate interface type ${t.id}`);
registry.set(t.id, t);
}
export function lookup(id: string) {
const t = registry.get(id);
if (!t) throw new Error(`unknown interface type ${id}: refuse to render rather than guess`);
return t;
}
// Example entry: pairwise with randomised sides. The side is fixed per assignment by a hash,
// so a reload shows the same layout and the stored label can be mapped back to response ids.
export interface PairItem { assignmentId: string; prompt: string; responses: [string, string]; ids: [string, string] }
export interface PairDraft { choice: 'left' | 'right' | 'tie' | null; strength: 0 | 1 | 2 | 3; reason: string }
export const leftIndex = (assignmentId: string) =>
[...assignmentId].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7) % 2; // 0 or 1
Debugging tips. If active time is near zero for everyone, the logger is not emitting events between load and submit (check that focus and edit events fire inside iframes or rich-text editors). If sequence gaps cluster at session end, the hidden-page flush is failing; check that the beacon payload stays small. If the left share sits at exactly 50.0% every day, check that the audit is reading the stored side rather than recomputing it from the current hash function.
In operation, each bias statistic becomes a dashboard panel with an expected value and an alert threshold set from its standard error. The dashboard below is the W1 version.
| Alert | Rule | Rationale |
|---|---|---|
| Position drift | daily \(|L - 0.5| > 2.4\) points on ≥ 3,000 non-tie labels | 3 SE at n = 3,000 is 2.7 points; 2.4 at W1's ~3,870/day |
| Position by segment | left share by viewport width, browser and UI version differs by > 4 points | layout bugs hit segments, not everyone |
| Length probes | longer-wins on probes above campaign pilot value + 10 points | guideline or rater-mix change |
| Anchoring | follow rate on planted wrong hints > no-hint baseline + 10 points | assistance is being trusted blindly |
| Event loss | sequence gaps > 0.5% of events, daily | all effort metrics become unreliable |
Table. Bias and instrumentation alert rules for W1 (illustrative thresholds).
Symptom. On days 5 and 6 the daily left share is 53.9% and 54.2%, against about 50% on days 1 to 4. The position-drift alert fires on day 5. Gold accuracy is unchanged at campaign level.
Why it matters. Under randomised sides, \(L = 0.5 + f/2\) implies that about \(f = 8\%\) of non-tie choices were made without judging both responses. W1 runs about 4,210 assignments a day, so two days give about 8,420 assignments, 7,750 non-tie labels and about 620 labels that are effectively coin flips. They do not bias the reward model's direction, but they add noise exactly where the campaign has paid $4.12 per useful comparison.
Diagnosis. Split the left share by viewport width: 58% on screens narrower than 1,400 px, 50.2% on wider ones. A day-4 CSS release changed the side-by-side layout to stack the two responses on narrow screens, pushing the right-hand response below the fold. Panel-visibility events show that on narrow screens, for 16% of non-tie labels the second response was never more than half visible. Since roughly half of rater sessions use narrow screens, \(0.5 \times 16\% = 8\%\), matching the estimate from \(L\).
Remedy, step by step. (1) Roll back the CSS. (2) Add a shell-level gate: submit is disabled until each response panel has been at least half visible for 2 seconds, logged as a panel_viewed event. (3) Identify the affected labels from the visibility events (about 620), drop them, and re-queue the assignments: about 47 rater-hours, roughly $1,860. (4) Add viewport width to the position-by-segment panel.
Trade-off. The view gate adds a little friction for raters who legitimately decide quickly; with a median of 4.0 minutes, a 2-second minimum per panel is negligible, but it must not become a visible countdown, which invites waiting rather than reading.
Validation. The fix is supported if, over the next 4,000 non-tie labels, the left share is within 50 ± 1.6 points (two standard errors at that sample size) and the narrow and wide segments differ by less than 2.5 points (about two standard errors for two segments of about 2,000 labels each). It is weakened if narrow-screen left share stays high with the gate in place: that would mean raters are scrolling past the second response, and the layout itself (not visibility) is the problem.
Runbook: a bias statistic moves. (1) Confirm the statistic's denominator (stored side, probe flag, planted flag) is computed from stored fields, not recomputed. (2) Split by UI version, viewport, browser, rater cohort and item batch; a single segment points to a layout or data cause, a uniform shift to a guideline or population cause. (3) Use event data (panel visibility, scroll, active time) to identify the affected labels rather than dropping whole days. (4) Re-queue only the affected assignments and record the incident against the batch in the dataset's provenance (Chapter 7).
Experiments on interfaces: measuring data quality and throughput
Definition. An interface experiment is a randomised comparison of two or more versions of a feedback interface, run on live assignments, that measures how the change affects the labels (quality), the cost of producing them (throughput) and known failure modes (guardrails). It is the same idea as an online A/B test of a product, applied to a population of paid annotators and an output that is training data.
Why it is needed. Interface changes are usually justified by intuition ("a suggestion will save time", "a bigger tie button is clearer"), and the incidents earlier in this chapter show how often the side effect is larger than the intended effect. Throughput gains are easy to see; quality losses are not, because a label that is wrong in a systematic way looks exactly like a correct one. An experiment makes both visible before the change reaches the whole campaign.
How it works, in order.
- Hypothesis and decision rule. Write down what should change, by how much, and what result would mean "ship", "do not ship" or "redesign". Fix it before launch so the result cannot be reinterpreted afterwards.
- Randomisation unit. Choose what gets assigned to an arm. Assigning items within each annotator (each annotator sees both versions) removes differences between annotators from the comparison and needs far fewer items. Assigning whole annotators to an arm is necessary when the change teaches a habit that would carry over to the other version, but annotators differ a lot, so many more items are needed. The assignment is a deterministic hash of the assignment id and experiment id, so a reload keeps the same arm.
- Metrics. A primary metric the decision depends on; quality metrics that need ground truth (gold items, planted items, double review); throughput metrics from events (active minutes per label); and guardrails, metrics that must not get worse (anchoring on planted wrong suggestions, tie rate, read-gate blocks, flag positions).
- Sizing. Compute how many items each arm needs to detect the smallest effect that would change the decision. Quality metrics are expensive because only items with ground truth count.
- Run and check. Check that the arms received the intended share of traffic (a sample ratio mismatch means the randomisation or logging is broken and the result cannot be trusted); watch guardrails; allow for a novelty period in which behaviour is still changing.
- Analyse and decide. Compare arms with confidence intervals that respect the fact that one annotator's items are correlated, apply the decision rule, and record the result with the campaign's provenance.
A proposed W2 change shows an AI-suggested first failing step. The first experiment (no hint versus hint shown first) finds a large time saving but experts follow deliberately wrong suggestions 27% of the time against a 10% baseline. The decision rule rejects it. A second experiment shows the hint only after the expert's own flag (judge-first); it saves less time but anchoring stays near baseline, and it ships. The details are in the Operate block of this section.
Comparison with product A/B testing. The statistics are the same, and so are the classic traps (sample ratio mismatch, peeking, novelty effects). Three things differ. The population is small (tens to hundreds of annotators rather than millions of users), so clustering by annotator dominates the arithmetic. The most important outcome, label correctness, is not observed on most items. And the participants are workers: pay must not depend on the arm, and annotators should know that interface variants and quality checks are part of the job (Chapter 10).
Contrast with a pilot. A pilot (Chapter 3) tests whether a campaign design works at all, usually with one interface; an experiment compares two interfaces under the same campaign. Pilots answer "is this usable?", experiments answer "is this better, and at what cost?".
What you would actually do. Randomise items within annotator by default; size the experiment on the quality metric you would act on and accept that this usually means buying extra gold, planted items or double review for the experiment window; always include an anchoring guardrail for any AI assistance; and pre-register the decision rule in the experiment spec.
Sample size for a proportion. To detect a change from \(p_1\) to \(p_2\) with a two-sided test at significance \(\alpha\) and power \(1-\beta\), each arm needs about
\[ n = \frac{(z_{1-\alpha/2} + z_{1-\beta})^2\,\big(p_1(1-p_1) + p_2(1-p_2)\big)}{(p_2 - p_1)^2}, \]where \(z_q\) is the standard normal quantile (\(z_{0.975} = 1.96\), \(z_{0.80} = 0.84\)). Turned around, the minimum detectable effect with \(n\) per arm near baseline \(p\) is \(\text{MDE} \approx (z_{1-\alpha/2} + z_{1-\beta})\sqrt{2p(1-p)/n}\).
Sample size for a mean. For a continuous metric with standard deviation \(\sigma\) and target difference \(\Delta\): \(n = 2(z_{1-\alpha/2} + z_{1-\beta})^2 \sigma^2 / \Delta^2\) per arm.
Clustering. One annotator's items are correlated (some annotators are fast, some lenient). If whole annotators are randomised and each contributes \(m\) items, the variance is inflated by the design effect \(\text{Deff} = 1 + (m-1)\rho\), where \(\rho\) is the intraclass correlation, the share of variance that sits between annotators (Kish, Survey Sampling, 1965; see summary). The effective sample size is \(n/\text{Deff}\). Randomising items within annotator removes the between-annotator component from the comparison instead.
Variance reduction. CUPED (Deng et al. 2013) adjusts each unit's outcome using a pre-experiment covariate, \(Y' = Y - \theta(X - \bar X)\), with \(\theta = \text{cov}(Y, X)/\text{var}(X)\). The residual variance is \((1-\rho_{XY}^2)\) of the original, where \(\rho_{XY}\) is the correlation between outcome and covariate; the authors report variance reductions of about 50% in their setting. For interface experiments, the annotator's pre-period speed or accuracy is the natural covariate.
Sample ratio mismatch. If arms were meant to be 50/50 and received 1,080 and 920 assignments, a chi-square test gives \(p \approx 0.0003\): randomisation or logging is broken, and the experiment should be stopped and debugged, not analysed.
Quality. Exact agreement on the first failing step is 58%. Detecting a rise to 68% needs 362 double-reviewed pairs per arm, but W2 double-reviews only 200 transcripts (100 per arm), giving an MDE of about 19.6 points. Agreement is therefore descriptive only, unless the experiment buys more double review.
Throughput. Mean time is 35 minutes; assume \(\sigma = 14\) minutes (to be measured in the pilot). Detecting a 10% change (3.5 minutes) needs 252 transcripts per arm. Randomising whole experts with 25 transcripts each and an assumed \(\rho = 0.30\) gives \(\text{Deff} = 1 + 24 \times 0.30 = 8.2\), so about 2,070 per arm: more than the campaign. Randomising transcripts within expert and applying CUPED with an assumed pre-period correlation of 0.6 cuts the requirement to about 161 per arm; with 500 per arm the MDE is about 2.0 minutes.
Mean active time is 4.5 minutes; assume \(\sigma = 3.0\) minutes. A 5% change (0.225 minutes) needs 2,791 assignments per arm, easily available in 25,260. Overlap agreement is 72%; detecting a rise to 76% needs 1,884 overlap items per arm, but the campaign has 2,000 overlap items in total, so with 1,000 per arm the MDE is about 5.6 points. The quality question is the expensive one.
| Metric | Ground truth needed | Units per arm (example) | Cost driver |
|---|---|---|---|
| Active minutes per label | none (events) | W1 2,791; W2 161 with CUPED | free with traffic |
| Gold / planted accuracy | gold or planted items | hundreds of gold items | gold creation and their labels |
| Agreement | double review | W2 362 pairs for +10 points | a second paid label per item |
| Anchoring guardrail | planted wrong suggestions | ~100 for a ±8-point interval | items excluded from export |
| Downstream (RM accuracy) | held-out preference set | full campaign per arm | retraining; rarely affordable |
Table. Interface experiment metrics by the ground truth they need (example sizes from the calculations above; assumptions labelled there).
What you would actually do. Make throughput the primary metric only when quality is protected by guardrails with enough planted or gold items to detect harm; otherwise make quality primary and buy the ground truth. Randomise within annotator unless there is a carry-over reason not to, and use the pre-period as a CUPED covariate.
The build artifacts are a small power-and-analysis module, an experiment spec file, and tests that pin every number used in this section. The analysis uses a cluster bootstrap: resample annotators (with all their items) rather than items, so the confidence interval reflects the correlation within each annotator.
"""Power and analysis helpers for interface experiments (two arms, A = control, B = treatment).
All functions are pure; inputs are plain numbers or lists, so results can be pinned in tests."""
from math import sqrt, ceil
from statistics import NormalDist
from collections import defaultdict
import random
Z = NormalDist().inv_cdf
def n_props(p1, p2, alpha=0.05, power=0.80):
"""Units per arm to detect p1 -> p2 with a two-sided two-proportion z-test."""
k = (Z(1 - alpha / 2) + Z(power)) ** 2
return ceil(k * (p1 * (1 - p1) + p2 * (1 - p2)) / (p2 - p1) ** 2)
def n_means(sd, delta, alpha=0.05, power=0.80):
"""Units per arm to detect a mean difference delta when each unit has std dev sd."""
k = (Z(1 - alpha / 2) + Z(power)) ** 2
return ceil(2 * k * sd ** 2 / delta ** 2)
def mde_props(p, n_per_arm, alpha=0.05, power=0.80):
"""Smallest detectable absolute change around baseline p with n units per arm."""
k = Z(1 - alpha / 2) + Z(power)
return k * sqrt(2 * p * (1 - p) / n_per_arm)
def design_effect(m, icc):
"""Kish: variance inflation when units come in clusters of size m (e.g. one annotator's items)."""
return 1 + (m - 1) * icc
def cuped_factor(rho):
"""CUPED (Deng et al. 2013): residual variance share after regressing on a pre-period covariate."""
return 1 - rho ** 2
def srm_pvalue(n_a, n_b, share_a=0.5):
"""Sample-ratio-mismatch check: chi-square (1 df) p-value for observed vs intended split."""
n = n_a + n_b
ea, eb = n * share_a, n * (1 - share_a)
chi = (n_a - ea) ** 2 / ea + (n_b - eb) ** 2 / eb
return 2 * (1 - NormalDist().cdf(sqrt(chi))) # chi2(1) tail via |z|
def cluster_bootstrap_diff(rows, n_boot=2000, seed=0):
"""rows: (annotator_id, arm, value). Resample annotators, not items, so the CI respects
the fact that one annotator's items are correlated. Returns (diff B-A, 2.5%, 97.5%)."""
by = defaultdict(list)
for a, arm, v in rows: by[a].append((arm, v))
ids = list(by); rng = random.Random(seed)
def diff(sample):
s = {'A': [0.0, 0], 'B': [0.0, 0]}
for a in sample:
for arm, v in by[a]: s[arm][0] += v; s[arm][1] += 1
return s['B'][0] / s['B'][1] - s['A'][0] / s['A'][1]
point = diff(ids)
boots = sorted(diff([rng.choice(ids) for _ in ids]) for _ in range(n_boot))
return point, boots[int(0.025 * n_boot)], boots[int(0.975 * n_boot)]
from ui_power import *
import random
def test_w2_agreement_needs_more_double_reviews_than_budget():
assert n_props(0.58, 0.68) == 362 # pairs per arm for +10 points exact agreement
assert round(mde_props(0.58, 100), 3) == 0.196 # 200 double reviews -> 100 pairs/arm
def test_w2_time_per_transcript():
assert n_means(sd=14, delta=3.5) == 252 # 10% of the 35-min mean, SD 14 min (assumed)
assert round(design_effect(25, 0.30), 1) == 8.2
assert n_means(14, 3.5) * design_effect(25, 0.30) > 1000 # infeasible if randomised by expert
def test_w1_time_and_agreement():
assert n_means(sd=3.0, delta=0.225) == 2791 # 5% of the 4.5-min mean, SD 3.0 min (assumed)
assert n_props(0.72, 0.76) == 1884
assert round(mde_props(0.72, 1000), 3) == 0.056
def test_cuped_and_srm():
assert round(cuped_factor(0.7), 2) == 0.51
assert srm_pvalue(1000, 1000) == 1.0
assert srm_pvalue(1080, 920) < 0.001
def test_cluster_bootstrap_recovers_effect():
rng = random.Random(1); rows = []
for a in range(40): # 40 experts, each with a personal speed
base = rng.gauss(35, 8)
for _ in range(25):
arm = rng.choice('AB')
rows.append((a, arm, base + rng.gauss(0, 10) - (3.5 if arm == 'B' else 0)))
d, lo, hi = cluster_bootstrap_diff(rows, n_boot=500)
assert lo < -3.5 < hi and hi < 0
Experiment spec. The spec is a reviewed file that the assignment service reads to route traffic and the analysis job reads to compute results. Planted items are marked so the export pipeline excludes them from training data.
# w2_hint_exp.yaml — interface experiment spec, reviewed before launch like code
id: w2_hint_exp_2
campaign: w2
hypothesis: >
Showing an AI-suggested first failing step AFTER the expert's own flag (judge-first)
reduces active minutes per transcript without increasing agreement with wrong suggestions.
arms:
A: {ui_variant: "w2_review_v2:A", share: 0.5, hint: none}
C: {ui_variant: "w2_review_v2:C", share: 0.5, hint: judge_first}
randomisation:
unit: transcript # within expert; stratified so each expert sees both arms
stratify_by: [expert]
hash: sha256(assignment_id + experiment_id)
sample:
transcripts: 1000 # 500 per arm
planted_wrong_hints: {arm: C, share: 0.20} # 100 items; excluded from training export
planted_targets_unshown: {arm: A, share: 0.20} # same targets, no hint: baseline a0
metrics:
primary: active_minutes_per_transcript # CUPED on expert's pre-period mean
quality: [agreement_exact, agreement_pm2] # double-reviewed subset; descriptive only
guardrails:
followed_wrong_hint_minus_baseline: {max: 0.05}
read_gate_block_rate: {max: 0.15}
flag_position_median_shift_steps: {max: 2}
decision:
ship_if: "primary CI excludes 0 in favour of C AND all guardrails pass"
stop_early_if: "guardrail breach with 95% CI excluding the threshold"
analysis: {alpha: 0.05, power: 0.80, ci: cluster_bootstrap_by_expert, srm_check: true}
ethics: {pay: hourly_unchanged_by_arm, notice: "interface variants and quality checks disclosed in guidelines"}
import yaml
from ui_power import n_means, cuped_factor
def test_spec_is_consistent_and_powered():
s = yaml.safe_load(open('w2_hint_exp.yaml'))
assert abs(sum(a['share'] for a in s['arms'].values()) - 1) < 1e-9
per_arm = s['sample']['transcripts'] * s['arms']['C']['share']
planted = per_arm * s['sample']['planted_wrong_hints']['share']
assert planted == 100 # matches the anchoring sample in the text
assert per_arm >= n_means(14, 3.5) * cuped_factor(0.6) # 500 >= ~161 needed for a 10% effect
$ python3 -m pytest -q test_ui_power.py test_exp_spec.py
...... [100%]
6 passed
Analysis recipe. (1) Run the SRM check on assignment counts per arm; stop if \(p < 0.001\). (2) Join labels to events on assignment_id and compute active minutes. (3) Compute each expert's pre-period mean as the CUPED covariate and adjust. (4) Compute the arm difference with the cluster bootstrap by expert. (5) Compute guardrails with Wilson intervals. (6) Apply the decision rule from the spec verbatim and store the result next to the spec.
Debugging tips. An SRM usually comes from arm-specific failures (one variant crashes on some browsers, so its assignments are abandoned and re-issued) or from bots and retries in the event stream; compare assignment issue counts with submit counts per arm. If the bootstrap interval is much wider than the textbook formula predicts, the between-annotator variance is larger than assumed; check that randomisation really was within annotator. If the treatment effect shrinks day by day, it may be a novelty effect; report the last days separately.
In operation, interface experiments need the same discipline as product experiments plus two additions: planted items must never reach training data, and the experiment must not change annotator pay or workload unfairly. The guardrail table below is evaluated daily for every running experiment.
| Check | Rule | Action |
|---|---|---|
| Sample ratio | chi-square p < 0.001 on assignment counts | pause, debug routing and logging |
| Anchoring | follow rate on planted wrong hints − baseline > 5 points (CI excludes threshold) | stop arm |
| Flag position | median flag step shifts > 2 steps vs control | investigate early stopping |
| Read-gate blocks | > 15% of submit attempts | investigate skimming or gate bug |
| Export exclusion | planted items found in an export | block export, page owner |
Table. Daily guardrails for interface experiments (illustrative thresholds).
Experiment 1 (hint shown first). 1,000 transcripts, randomised within expert, 500 per arm; 100 planted wrong hints in arm B, and the same 100 target steps recorded but not shown in arm A. Result (illustrative): CUPED-adjusted active minutes fall from 35.1 to 29.4 (−16%, cluster-bootstrap 95% interval −7.9 to −3.6 minutes). Experts follow 27 of 100 planted wrong hints against a 10% baseline: +17 points, far over the 5-point guardrail. The median flag position moves 3 steps later in arm B when the hint points later, consistent with experts stopping their own search at the hint.
Why not ship anyway. The time saving is worth about 5.7 minutes × 2,000 transcripts = 190 expert-hours, about $22,800. If the AI suggestion is wrong on 30% of real transcripts (an assumption to be measured), the extra 17-point follow rate produces about \(2{,}000 \times 0.30 \times 0.17 \approx 102\) wrong flags, about 5% of the dataset, roughly $7,100 at $70 each. The dollar comparison favours shipping, but the cost is misleading: those 102 errors are concentrated exactly where the AI is wrong, so the human labels inherit the model's blind spots, which is the signal human review exists to provide (Chapter 9). The decision rule rejects the arm.
Experiment 2 (judge-first). Same design, hint revealed after the expert's own flag, with a one-click "move my flag to the suggestion" that requires a reason. Result (illustrative): active minutes 35.0 to 32.6 (−7%, interval −4.1 to −0.7); follow rate on planted wrong hints 12% against the 10% baseline (+2 points, within the guardrail); flag-position median unchanged. Ship. Expected saving: 2.4 minutes × 2,000 = 80 expert-hours, about $9,600 per campaign of this size.
Validation after ship. Keep 5% planted wrong hints for two more campaigns; the decision is supported if the follow rate stays within 5 points of baseline as experts get used to the hint, and weakened if it creeps up (habituation turns judge-first into rubber-stamping, and the reveal needs a delay or a required comparison step).
Runbook: launching an interface experiment. (1) Spec reviewed: hypothesis, unit, arms, metrics, guardrails, decision rule, sample size computed by ui_power.py. (2) Planted items registered with the export pipeline's exclusion list; dry-run an export to prove exclusion. (3) Annotator notice and pay check: pay hourly and identical across arms. (4) Launch at a small share for one day; run the SRM check and look at guardrails. (5) Ramp to the planned share; evaluate guardrails daily; do not evaluate the primary metric before the planned sample is reached. (6) Analyse with the recipe in the Build block, record the decision with the spec, and remove the losing variant's code path.
Data Quality and Annotator Integrity
Human feedback is the most expensive input in post-training and one of the noisiest. Two raters who read the same pair of coding answers will disagree a large part of the time, and sometimes neither is wrong. Some raters work carefully, some drift as the week goes on, some click through, and since 2023 some ask a language model to answer for them. A reward model trained on such labels learns whatever the labels contain, including position habits, length preferences and the preferences of whichever model a rater consulted. Data quality, in this chapter, means how well collected labels reflect the careful judgement the campaign asked for. Annotator integrity means the work was done by the person paid to do it, with the effort the guidelines require, without substituting a model's judgement for their own where that is not allowed.
The chapter follows the loop in the figure. First, measurement: how to establish what quality a campaign actually has, using hidden items with known answers (gold items), items labelled by several raters (overlap) and chance-corrected agreement statistics, and checks of whether raters know when they are unsure (calibration). Second, aggregation: how to turn many noisy labels into training targets, from majority vote to models that learn each rater's reliability (Dawid–Skene) and models that turn pairwise preferences into scores (Bradley–Terry). Third, detection: how to find low-effort, model-assisted and adversarial work from behaviour, agreement patterns and peer-prediction scores. Fourth, the quality program: the review tiers, feedback, enforcement ladder and audits that act on all of the above.
W1 collects 20,000 pairwise comparisons of coding answers for a reward model: 2,000 items labelled by 3 raters, 18,000 by one, 5% of assignments are gold items, for about 25,260 assignments across 150 vendor raters. Raters on overlap agree 72% of the time; the gold threshold is 80%; QA rejects 8%, leaving about 18,400 useful comparisons at about $4.12 each; 4% of raters are flagged for low effort. W2 (expert review of 2,000 agentic transcripts) supplies the expert-review numbers: 10% double-reviewed, 58% exact agreement on the first failing step. All numbers are illustrative.
A theme runs through all four sections: agreement is not correctness, and disagreement is not always error. Raters who copy the same model agree with each other; experts who see a genuinely ambiguous case disagree. The design decision this chapter prepares for is how much of the labelling budget to spend on measuring and policing quality versus collecting more labels, and the recommended default is to spend roughly a quarter of labelling labour on quality (gold, extra overlap labels, review) and to make every enforcement step reversible.
Quality work is a budget allocation problem. Every assignment spent on a gold item, a second or third rater, or a reviewer is an assignment not spent on a new comparison. The quantities that decide the allocation are few: the share of assignments that are gold (\(g\)), the share of items with overlap and the overlap depth (\(o\), \(m\)), the review sampling rates per tier, the rater accuracy \(p\) these measure, and the error rate \(\varepsilon\) of what is finally exported. This chapter makes each of them quantitative.
Four calculations recur. Precision of a per-rater estimate: with \(n\) gold items, the 95% half-width on accuracy is about \(1.96\sqrt{p(1-p)/n}\), which is wide for small \(n\). Chance correction: agreement statistics subtract what random labelling with the same label shares would produce, \(\kappa = (p_o - p_e)/(1-p_e)\). Value of redundancy: majority of three raters each correct with probability \(p\) is correct with probability \(p^3 + 3p^2(1-p)\), at three times the cost. Base rates in detection: a detector with recall \(r\) and false-positive rate \(f\) applied to a population with prevalence \(\pi\) has precision \(r\pi/(r\pi + f(1-\pi))\).
The W1 quality budget: gold is 5% of 25,260 assignments = 1,263; overlap adds 2 extra labels on 2,000 items = 4,000 labels; T1 peer review samples 5% (about 1,263 reviews) and T2 expert audit 1% (about 253). Gold plus overlap alone is \((1{,}263 + 4{,}000)/25{,}260 \approx 21\%\) of assignments, which is why the chapter later argues for single-labelling most items and spending overlap where it buys measurement. Per rater, 25,260/150 ≈ 168 assignments, of which about 8.4 are gold and about 40 are overlap labels.
The design decisions, each settled in a later section: how many gold items and overlap labels per rater are enough to act on (measurement), whether redundancy or more unique items gives a better reward model per dollar (aggregation), how many independent signals to require before acting against a rater (detection), and how to size audits so the exported error rate is known to ±2 points (the quality program). Default: 5% gold, 10% overlap at depth 3, two-signal rule, an audit of about 700 items per campaign.
The build for this chapter is a small, tested quality library that sits between the annotation store and the training export. It has four modules, one per section, each pure Python over plain arrays so it can run in a nightly batch job or a notebook: quality_metrics.py (Cohen's and Fleiss' kappa, Krippendorff's alpha, gold posteriors, calibration tables), aggregate.py (majority vote, Dawid–Skene EM with gold clamping, soft reward-model targets, Bradley–Terry and online Elo), detect.py (event-log features, transparent rater rules, and a peer-prediction score conditioned on LLM labels) and policy.py with w1_quality_policy.yaml (deterministic review sampling, audit sizing, the enforcement ladder and quarantine).
The shared data contract is a label table: one row per judgement with assignment_id, item_id, rater_id, label, is_gold, guideline_version, ts, plus an event log per assignment (open, blur, focus, key, paste, choose, submit, with millisecond timestamps). Every function in the chapter consumes one of these two shapes.
All tests in this chapter run on W1-shaped synthetic data: 150 raters, 2,000 triple-labelled items, 18,000 single-labelled items and 1,263 gold assignments (25,263 rows in total, matching the ≈25,260 of the reference workload), labels A, B or tie. The full suite (15 tests) runs in under two seconds with NumPy, SciPy and PyYAML: python3 -m pytest -q.
Debugging rule for the whole chapter: when a quality number is surprising, recompute it from the raw label table with the simplest possible method (raw agreement, raw gold accuracy) before trusting a model-based one. Most production surprises are join errors (gold flag lost, rater id remapped by a vendor) rather than statistics.
In production the quality system is judged by two things: whether bad labels are kept out of the training export before the export is consumed, and whether honest raters are treated fairly while that happens. Both are measurable. The first is a latency and recall problem: how many hours after a rater starts producing bad labels do those labels stop flowing, and what fraction of them are caught. The second is a precision and process problem: how many raters were paused or removed who should not have been, and how quickly that was reversed.
The chapter's Operate blocks build one SLO set: gold and agreement measured daily per rater and per campaign; detection alerts evaluated on daily (not weekly) windows; review queues with 24-hour (T1) and 72-hour (T2) service levels; quarantine applied within 4 hours of a pause; an audit-estimated exported error rate with a confidence interval attached to every dataset version. Each block ends with a worked incident: a guideline-version skew in W2 expert review, a cold-start problem in Dawid–Skene weights, a false-positive storm from a tab-switching rule on coding tasks, and an LLM-assisted cohort in W1 that gold items did not catch.
The W1 request-to-mix baseline is 21 days, of which QA takes 3 as a batch phase after collection. The target is 7 days. That target is unreachable while QA is a phase: the Operate design in this chapter runs every check continuously during collection so that QA at the end is a sign-off on numbers already on the dashboard, not a three-day job.
Measuring Quality: Gold, Agreement, Calibration
Measuring quality means producing numbers that say how close collected labels are to the careful judgement a campaign asked for, per rater, per item and per campaign. Before crowdsourcing, labels came from a few trained annotators whose work could be read in full; at the scale of RLHF campaigns (tens of thousands of comparisons from hundreds of people) nobody can read everything, so quality must be estimated from samples. Three instruments do the estimating, and each answers a different question.
Gold items (also called honeypots or test questions) are items whose correct answer is known in advance and which are mixed, unmarked, into a rater's normal queue. They are written or adjudicated by the campaign's experts, chosen to have one defensible answer (for a coding comparison: one answer fails its tests, or contains a security bug the guidelines say to penalise). The platform scores each response to a gold item and keeps a running accuracy per rater. Gold items answer "does this person get clear cases right?" Their limitations: they only exist for items with a defensible answer, which in preference work are the easier items; raters can learn to recognise them if they look different or repeat; and a rater who consults a strong model passes them easily.
Overlap means giving the same item to two or more raters. It requires no known answer, so it works on the subjective items gold cannot cover. The raw agreement rate (how often two raters pick the same option) is easy to read but misleading on its own, because two raters choosing at random between "A better" and "B better" still agree half the time. Chance-corrected agreement statistics fix this by asking how much of the observed agreement exceeds what random labelling with the same label shares would produce: Cohen's kappa for two raters (Cohen 1960), Fleiss' kappa for a fixed number of raters per item (Fleiss 1971), and Krippendorff's alpha, which handles any number of raters, missing labels and ordered or numeric scales (Krippendorff 2011). A value of 1 means perfect agreement, 0 means no better than chance. Overlap answers "do raters apply the guidelines the same way?" Its limitation: raters who share an error, or share a model, agree perfectly and wrongly.
Calibration has two meanings in annotation work, and a program needs both. Statistical calibration asks whether a rater's stated confidence matches how often they are right: when the interface offers "A is clearly better" and "A is slightly better", clear judgements should agree with gold or adjudicated labels much more often than slight ones. Operational calibration is a calibration session: raters label the same small set, compare answers with an expert key, and discuss the cases they split on until the guideline is applied the same way. The first measures self-knowledge; the second produces shared understanding and is usually how a campaign starts and how a drifting pool is pulled back.
Published RLHF work gives reference points. InstructGPT reports that its trained labelers agreed with each other 72.6% of the time on preference comparisons and held-out labelers 77.3% (Ouyang et al. 2022); Anthropic's helpful–harmless work reports about 63% average agreement between its researchers and crowdworkers (Bai et al. 2022). Raw pairwise preference agreement in the 60s and 70s is therefore normal, not a sign of failure.
Disagreement as signal. On many items there is no single correct label: two reasonable experts can prefer different coding styles. Plank argues that such human label variation should be treated as information about the item rather than noise to remove (Plank 2022). In practice the platform keeps every individual label and a per-item disagreement profile (unanimous, 2–1 split, three-way split), so later stages can decide whether a split item is ambiguous (keep it, perhaps as a soft target) or a guideline gap (fix the guideline).
W1 raters agree 72% of the time on the 2,000 triple-labelled items, which with three raters and no three-way splits means about 58% of items are unanimous and 42% split 2–1. Each rater sees only about 8 gold items over the whole campaign (5% of their ≈168 assignments), so a single rater's gold score can flag someone near chance but cannot distinguish a 75% rater from an 85% rater. In W2, two experts name the same first failing step in 58% of double-reviewed transcripts and land within two steps of each other in 81%: much of the disagreement is about where a failure starts, not whether there is one.
Compare and contrast. Gold measures correctness but only on easy, defensible items; agreement covers every item but only measures consistency; calibration measures whether confidence carries information. Classic crowdsourcing leaned on gold because tasks had right answers; preference work leans on agreement and disagreement profiles because many items do not. The cost of all three is assignments not spent on new data.
What you would actually do. Default: 5% gold drawn from expert-adjudicated items and rotated, 10% overlap at depth three, a two-level confidence option in the interface, a calibration session at launch and whenever agreement drops. Deviate toward more gold when the domain has verifiable answers (code with tests), and toward more overlap when it does not (style, safety judgement).
Measurement numbers are estimates from small samples, so the design question is always "how many observations before this number can drive a decision?" Three estimates matter: a rater's gold accuracy, a campaign's chance-corrected agreement and a rater's calibration.
Gold accuracy and its uncertainty. Let a rater answer \(n\) gold items and get \(c\) right. The point estimate is \(\hat p = c/n\). Treating each answer as an independent trial with true accuracy \(p\), the standard error is \(\sqrt{p(1-p)/n}\) and the 95% half-width is approximately
\[ h = 1.96\sqrt{\frac{p(1-p)}{n}}, \qquad n_{\text{needed}} = \frac{1.96^2\,p(1-p)}{h^2}. \]At \(p = 0.8\), a half-width of 0.05 needs 246 gold items, and 0.10 needs 62. Because these counts are far above what one campaign gives a rater, the decision rule should use a prior: model accuracy as a Beta distribution with a pool-level prior \(\text{Beta}(a_0, b_0)\) and update it to \(\text{Beta}(a_0 + c,\, b_0 + n - c)\). Act only when the posterior probability that accuracy is below the threshold, \(P(p < 0.8 \mid c, n)\), exceeds 0.95.
W1 gives each rater about 1,263/150 ≈ 8.4 gold items, a half-width of about ±0.27. With prior Beta(8, 2) (mean 0.8, worth 10 items), a rater with 6 of 8 correct has posterior mean 0.78 and \(P(p<0.8) \approx 0.55\): no action. A rater with 25 of 40 correct (pooled across campaigns) has \(P(p<0.8) \approx 0.99\): act. The practical consequence is that per-rater gold decisions need gold pooled across campaigns and weeks, keyed by rater, not reset each campaign.
Chance-corrected agreement. For two raters labelling the same items, let \(p_o\) be the observed share of items where they agree and \(p_e = \sum_c q_{1c} q_{2c}\) the agreement expected if each labelled independently with their own category shares \(q_{1c}, q_{2c}\). Cohen's kappa is
\[ \kappa = \frac{p_o - p_e}{1 - p_e}. \]Fleiss' kappa generalises to \(n\) raters per item using pooled category shares \(q_c\): per item, \(P_i\) is the fraction of rater pairs that agree, \(\bar P\) its mean, \(P_e = \sum_c q_c^2\), and \(\kappa_F = (\bar P - P_e)/(1 - P_e)\). Krippendorff's alpha writes the same idea as one minus a ratio of disagreements, \(\alpha = 1 - D_o/D_e\), where \(D_o\) is observed disagreement among values paired within items and \(D_e\) the disagreement expected among all pairable values; a distance function \(\delta^2(c,k)\) (0/1 for nominal labels, \((c-k)^2\) for interval data) makes it usable for ordered scales, and items with a single value simply drop out (Krippendorff 2011). For large samples with complete data, alpha and Fleiss' kappa are nearly identical.
Position randomisation makes A and B about equally common; with category shares 0.46 (A), 0.46 (B), 0.08 (tie), \(p_e = 0.46^2 + 0.46^2 + 0.08^2 = 0.430\). With \(p_o = 0.72\): \(\kappa = (0.72 - 0.430)/(1 - 0.430) \approx 0.51\). The W1-shaped simulation in the Build block gives Fleiss' kappa and alpha of 0.50. Pairwise agreement of 0.72 with three raters and no three-way splits implies \(u + (1-u)/3 = 0.72\), so the unanimous share is \(u = 0.58\). Sampling error on \(p_o\) from 2,000 items is about \(\pm 2\) points at 95%, so a week-over-week drop of 5 points is real.
Interpreting the number. Conventional bands (Landis and Koch's "moderate" for 0.41–0.60, "substantial" for 0.61–0.80) are widely quoted but were offered without supporting evidence (see the discussion of kappa interpretation), and Krippendorff's commonly cited cutoffs (rely on \(\alpha \ge 0.800\), tentative conclusions for \(0.667 \le \alpha < 0.800\)) come from content analysis (Krippendorff 2004, as summarised). Preference data routinely sits below them, as the InstructGPT and HH numbers show. Use kappa as a trend and a comparison across raters and guideline versions, not as a pass/fail grade. Kappa also depends on prevalence: if ties become rarer, \(p_e\) rises and kappa falls even with identical raw agreement.
Ordered labels. W2's "first failing step" is an integer. Exact agreement throws away the fact that steps 31 and 32 are close; interval alpha with \(\delta^2 = (c-k)^2\), or tolerance agreement (within \(\pm 2\) steps), keeps it.
200 transcripts (10% of 2,000) are double-reviewed. Exact agreement on the first failing step is 58% and within-two-steps agreement 81%: 23 points of the disagreement are near-misses. The campaign reports both, plus interval alpha, and treats a fall in within-two-steps agreement as more serious than a fall in exact agreement, because it means experts disagree about which part of the transcript failed.
Calibration. Bucket judgements by stated confidence \(b\) and compute accuracy against gold or adjudicated labels per bucket, \(\text{acc}(b)\). A calibrated rater has \(\text{acc}(\text{clear}) \gg \text{acc}(\text{slight})\); a rater whose buckets have equal accuracy is giving no confidence information. Each bucket needs tens of judgements to estimate, so calibration is a pooled, monthly metric per rater and a weekly metric per campaign.
| Instrument | Measures | Needs per rater | Fails when | Default |
|---|---|---|---|---|
| Gold items | accuracy on clear cases | ~60 for ±0.10 | items look different; raters use a model | 5% of assignments, pooled across campaigns |
| Overlap + kappa/alpha | consistency | ~40 overlap labels | raters share errors or a model | 10% of items at depth 3 |
| Calibration buckets | value of stated confidence | ~50 per bucket | interface hides confidence | two-level confidence, reviewed monthly |
| Disagreement profile | item ambiguity | per item, not per rater | only one label per item | stored for every overlap item |
Table. Measurement instruments and how much data each needs (approximate sample sizes from the formulas above).
What you would actually do. Report raw agreement, kappa and the unanimous share together; decide on raters with Beta posteriors over pooled gold; use interval alpha or tolerance agreement for ordered labels. Deviate from pooled-gold decisions only for new raters, who should get a denser gold rate (for example 20% of their first 50 items) so they reach a decision quickly.
The measurement module takes the label table (one row per judgement) and returns agreement statistics, per-rater gold posteriors and calibration tables. Everything is vectorised over NumPy arrays; the only dependency beyond NumPy is scipy.stats.beta for the posterior. Shapes: a two-rater comparison takes two aligned arrays of length N; Fleiss takes an (N items × K categories) count matrix with the same number of raters per item; Krippendorff takes a list of per-item value lists, so missing raters and varying overlap depth need no padding.
"""quality_metrics.py: agreement and gold-item statistics for a feedback campaign.
Inputs are plain label arrays; categories for W1 are "A", "B", "tie"."""
import numpy as np
from scipy.stats import beta
def cohen_kappa(a, b, cats):
"""Two raters, same items. a, b: (N,) labels. Returns kappa = (p_o - p_e) / (1 - p_e)."""
a, b = np.asarray(a), np.asarray(b)
p_o = np.mean(a == b) # observed agreement
p_e = sum(np.mean(a == c) * np.mean(b == c) for c in cats) # chance, from each rater's marginals
return (p_o - p_e) / (1 - p_e)
def fleiss_kappa(counts):
"""counts: (N items, K categories); row i = how many of the n raters chose each category."""
counts = np.asarray(counts, float)
N, K = counts.shape
n = counts[0].sum()
assert np.allclose(counts.sum(1), n), "Fleiss needs the same number of raters per item"
P_i = (np.sum(counts ** 2, axis=1) - n) / (n * (n - 1)) # agreeing rater pairs per item
p_j = counts.sum(0) / (N * n) # pooled category shares
P_bar, P_e = P_i.mean(), np.sum(p_j ** 2)
return (P_bar - P_e) / (1 - P_e)
def krippendorff_alpha(units, metric="nominal"):
"""units: list of per-item value lists (any number of raters, missing values simply absent).
Coincidence-matrix method (Krippendorff 2011). metric: 'nominal' or 'interval'."""
values = sorted({v for u in units for v in u})
ix = {v: i for i, v in enumerate(values)}
o = np.zeros((len(values), len(values)))
for u in units:
m = len(u)
if m < 2:
continue # unpairable value: contributes nothing
for i, a in enumerate(u):
for j, b in enumerate(u):
if i != j:
o[ix[a], ix[b]] += 1.0 / (m - 1)
n_c = o.sum(1); n = n_c.sum()
if metric == "nominal":
d2 = 1.0 - np.eye(len(values))
else:
v = np.asarray(values, float); d2 = (v[:, None] - v[None, :]) ** 2
D_o = (o * d2).sum() / n
D_e = (np.outer(n_c, n_c) * d2).sum() / (n * (n - 1))
return 1.0 - D_o / D_e
def gold_posterior(correct, total, threshold=0.80, prior=(8.0, 2.0)):
"""Beta-binomial check of one rater's gold accuracy.
prior (a0, b0): pool-level prior, here mean 0.8 worth 10 pseudo-items.
Returns (posterior mean, P(true accuracy < threshold))."""
a, b = prior[0] + correct, prior[1] + (total - correct)
return a / (a + b), beta.cdf(threshold, a, b)
def gold_items_needed(p=0.80, half_width=0.05, z=1.96):
"""Gold items one rater must answer for a +/- half_width normal-approximation CI on accuracy p."""
return int(np.ceil(z ** 2 * p * (1 - p) / half_width ** 2))
def calibration_table(confidence, correct):
"""confidence: (N,) stated bucket per judgement, e.g. 'slight'/'clear';
correct: (N,) bool agreement with gold or adjudicated label. Returns {bucket: (n, accuracy)}."""
confidence, correct = np.asarray(confidence), np.asarray(correct, bool)
return {c: (int((confidence == c).sum()), float(correct[confidence == c].mean()))
for c in np.unique(confidence)}
The tests build a W1-shaped overlap set with a known structure (58% unanimous items, 42% split 2–1, about 8% ties), so the expected pairwise agreement is exactly 0.72, and check that the three statistics agree with each other and with the closed-form numbers from the design discussion.
import numpy as np
from quality_metrics import *
def w1_overlap(seed=0):
"""Synthetic W1 overlap set: 2,000 items x 3 raters, labels A/B/tie (~8% ties).
58% of items unanimous, 42% split 2-1 -> pairwise agreement 0.58 + 0.42/3 = 0.72."""
rng = np.random.default_rng(seed)
items = []
for i in range(2000):
maj = rng.choice(["A", "B", "tie"], p=[0.47, 0.47, 0.06])
if i < 1160:
items.append([maj] * 3)
else:
if maj == "tie":
other = rng.choice(["A", "B"])
else: # dissent is usually the opposite side
other = rng.choice([{"A": "B", "B": "A"}[maj], "tie"], p=[0.85, 0.15])
row = [maj, maj, other]; rng.shuffle(row); items.append(row)
return items
def test_pairwise_agreement_is_72pct():
items = w1_overlap()
pa = np.mean([np.mean([u[i] == u[j] for i, j in [(0, 1), (0, 2), (1, 2)]]) for u in items])
assert abs(pa - 0.72) < 1e-9
def test_kappa_family_agree_on_w1():
items = w1_overlap()
cats = ["A", "B", "tie"]
counts = np.array([[u.count(c) for c in cats] for u in items])
fk = fleiss_kappa(counts)
ka = krippendorff_alpha(items)
ck = cohen_kappa([u[0] for u in items], [u[1] for u in items], cats)
print(f"Fleiss {fk:.3f} alpha {ka:.3f} Cohen(r0,r1) {ck:.3f}")
assert 0.45 < fk < 0.60 and abs(fk - ka) < 0.005 # alpha ~ Fleiss for large N
assert abs(ck - fk) < 0.05
def test_alpha_textbook_cases():
assert krippendorff_alpha([[1, 1], [2, 2], [3, 3]]) == 1.0
assert krippendorff_alpha([[1, 1], [2, 2], [3]]) == 1.0 # lone value dropped
# interval metric: near-misses on a step index are penalised less than far misses
near = krippendorff_alpha([[10, 11], [30, 31], [50, 50], [20, 21]], "interval")
far = krippendorff_alpha([[10, 30], [30, 10], [50, 50], [20, 21]], "interval")
assert near > 0.99 and far < near
def test_gold_math():
assert gold_items_needed() == 246
mean, p_below = gold_posterior(6, 8) # 6/8 = 75% on 8 gold items
assert 0.77 < mean < 0.79 and 0.3 < p_below < 0.6 # cannot conclude anything
mean, p_below = gold_posterior(25, 40) # 62.5% on 40 items
assert p_below > 0.95 # strong evidence below 80%
def test_calibration_table():
t = calibration_table(["clear"] * 10 + ["slight"] * 10, [1] * 9 + [0] + [1] * 6 + [0] * 4)
assert t["clear"] == (10, 0.9) and t["slight"] == (10, 0.6)
Running python3 -m pytest -q -s test_quality_metrics.py prints Fleiss 0.499 alpha 0.499 Cohen(r0,r1) 0.490 and passes 5 tests. The gold checks confirm the two decisions from the design discussion: 6 of 8 correct leaves \(P(p<0.8) \approx 0.55\) (no action), 25 of 40 gives about 0.99 (act). gold_items_needed() returns 246 for ±0.05 at 0.8.
Wiring it to the store. Run nightly: group the label table by campaign and guideline version, compute raw agreement, Fleiss' kappa and alpha on overlap items, and write them to a quality_daily table keyed by (campaign, guideline_version, date). Per rater, accumulate gold correct/total across all campaigns that share a gold bank, then call gold_posterior.
Debugging tips. (1) If kappa is negative or near zero while raw agreement is 70%, check the category mapping: a vendor export that swaps A/B for half the raters produces exactly this. (2) If alpha and Fleiss differ by more than a few thousandths on complete data, an item has a different number of raters than expected (duplicates from retries are common). (3) If gold accuracy is suspiciously high pool-wide, check whether gold items are distinguishable (shorter prompts, fixed positions, repeated text) and whether answers have leaked. (4) Compute agreement separately per guideline version; mixing versions understates both.
In production, measurement becomes a set of service-level objectives and a dashboard that someone reads every day of a campaign. The objectives protect two consumers: researchers, who need to know the quality of what they are about to train on, and the quality program, which needs per-rater evidence fresh enough to act on before a bad week of labels is exported.
| SLO | Target (W1 defaults) | Why |
|---|---|---|
| Freshness of per-rater gold and agreement | ≤ 24 h behind the label stream | action before the export is cut |
| Campaign kappa reported with CI and by guideline version | daily, ±0.03 at 95% | separates drift from noise |
| Gold exposure | no gold item seen by more than 30 raters | limits memorisation and leakage |
| Gold distinguishability | a classifier on surface features separates gold from normal items with AUC ≤ 0.6 | gold must look like work |
| Version pinning | 100% of labels carry the guideline version the rater actually saw | agreement is only comparable within a version |
Table. Measurement SLOs. Targets are illustrative defaults for a W1-sized campaign.
Dashboard. Panel 1: raw agreement, kappa and unanimous share per day, split by guideline version (formula: Fleiss over overlap items with date = d). Panel 2: distribution of per-rater posterior \(P(p<0.8)\), with the count above 0.95 highlighted. Panel 3: calibration, accuracy by confidence bucket per week. Panel 4: gold health, exposures per gold item and gold-vs-normal classifier AUC. Panel 5 (ordered labels): exact and tolerance agreement and interval alpha.
Symptom. In the second week of W2, exact agreement on the first failing step among double-reviewed transcripts falls from 58% to 41% and within-two-steps agreement from 81% to 74%, on about 100 double-reviewed transcripts that week (interval of roughly ±10 points, so the drop is outside noise).
Separating causes. Three hypotheses: harder transcripts this week, expert fatigue, or a guideline problem. Agreement by transcript difficulty bucket (agent task length) is flat, which weakens the first. Agreement by time of day and by expert hours worked is flat, which weakens the second. Agreement split by the guideline version recorded on each review shows the cause: pairs where both experts saw version 2 agree exactly 57%; mixed pairs agree 30%. Version 2 had changed the definition of the failing step from "first wrong action" to "first wrong reasoning that leads to a wrong action", which moves the label earlier by a few steps. 18 of the 40 experts were still served version 1 by a cached guideline page.
Remedy. (1) Pin the guideline version in each assignment and render it from the assignment, not from a cache. (2) Hold a 30-minute calibration session for all 40 experts on 10 transcripts that sit on the boundary between the two definitions. (3) Re-review only the first-failing-step field for transcripts labelled under version 1 in week 2: about 18/40 of that week's ≈1,000 transcripts ≈ 450, at about 10 minutes each ≈ 75 expert-hours ≈ $9,000 at $120/h, versus about $31,500 to redo those transcripts fully at 35 minutes each.
Validation. The following week, exact agreement on same-version pairs returns to 56–60% and no mixed-version pairs exist. If agreement had stayed low with all pairs on version 2, the definition itself would be ambiguous and the next step would be a guideline revision, not more calibration.
Runbook: agreement drop. 1. Confirm the drop exceeds the CI (\(\pm 1.96\sqrt{p(1-p)/n}\) on the overlap count). 2. Split by guideline version, rater cohort, item source and difficulty; the split that concentrates the drop is the lead. 3. If one version or cohort: fix serving or run a calibration session. 4. If items: check prompt-source changes upstream (Chapter 4). 5. If uniform: inspect 20 split items with an expert; if they are genuinely ambiguous, record that as disagreement signal rather than forcing agreement. 6. Record the decision and the before/after kappa in the campaign log.
Cost and trade-off. Higher overlap narrows these intervals but every extra overlap label costs a full assignment. Pooling across weeks gives precision at the cost of slower detection. The default is daily campaign-level metrics (enough data) and weekly per-rater metrics (pooled), with new raters on a denser gold rate.
Aggregating Labels: Majority, Dawid–Skene, Bradley–Terry
Aggregation turns the individual labels collected for an item (or a set of comparisons) into the target a training job consumes. It exists because individual labels are noisy and raters differ in reliability; a simple average treats a careful rater and a click-through rater the same. The question aggregation answers is "given everything we know about these raters, what is our best estimate of the right label, and how sure are we?"
Majority vote is the predecessor and the baseline: for each item, take the label most raters chose. It needs no model, is easy to explain and is often good enough when every rater is better than chance and errors are independent. Its weaknesses are that it gives every rater one vote regardless of skill, says nothing about items with a single label, and produces a hard label that discards how split the vote was.
Dawid–Skene is the classic model that learns rater reliability from the labels themselves (Dawid and Skene 1979, originally for clinicians whose diagnoses disagreed). It assumes each item has one hidden true label, and each rater has a confusion matrix: for every true label, the probabilities of the rater answering each possible label. A careful rater's matrix is concentrated on the diagonal; a rater who always picks "A" has a matrix with one heavy column. The model is fitted by expectation–maximisation (EM), an alternating loop shown in the figure. Starting from the majority vote, the E-step computes, for every item, a probability over its true label given the current confusion matrices; the M-step re-estimates each rater's confusion matrix from those probabilities. Repeat until nothing changes. Outputs: a posterior (a probability for each label) per item, and a reliability per rater. Gold items can be clamped to their known answers, which anchors the estimates. Later models such as MACE add an explicit "spammer" behaviour (Hovy et al. 2013), and libraries such as Crowd-Kit implement Dawid–Skene, MACE, GLAD and others behind one interface (Ustalov et al. 2021).
Bradley–Terry addresses a different aggregation problem: turning many pairwise preferences into a score per item or per model. It assumes each object has a hidden strength, and the probability that one object beats another depends only on the difference of their strengths (Bradley and Terry 1952). Fitting the strengths to observed wins by maximum likelihood gives a ranking with uncertainty. This model matters twice in RLHF: a reward model trained on preference pairs is a Bradley–Terry model whose strengths are produced by a neural network from the response text, and checkpoint comparisons (is the candidate better than the current model?) are Bradley–Terry fits over a handful of policies. Elo is the online, game-by-game approximation from chess; Chatbot Arena moved from online Elo to a Bradley–Terry fit because online Elo depends on the order of games and on a tuning constant (LMSYS 2023; Chiang et al. 2024).
Of W1's 20,000 comparisons, only 2,000 have three labels; 18,000 have one. Majority vote can only help on the 2,000. Dawid–Skene matters more for the other 18,000: it estimates each rater's reliability from overlap and gold, and turns a single label from a reliable rater into a confident soft target and a single label from an unreliable rater into a hedged one. In the W1-shaped simulation, the six low-effort raters (who pick A 70% of the time) receive estimated accuracies of 0.44–0.49, below every honest rater. If the candidate checkpoint wins 55% of comparisons against the current one, Bradley–Terry expresses that as a gap of about 35 Elo points.
Compare and contrast. Majority vote is model-free but blind to reliability; Dawid–Skene learns reliability but assumes raters err independently given the truth, which fails when raters copy each other or the same model; Bradley–Terry ranks objects from comparisons but assumes a single quality scale, which fails when preferences are intransitive or depend on the rater. All three lose information if their output is collapsed to a hard label, so modern pipelines export soft targets (probabilities) with a confidence weight.
What you would actually do. Fit Dawid–Skene with gold clamped on every campaign, export the posterior as a soft preference target plus a weight, keep raw labels alongside, and use Bradley–Terry (not online Elo) for any checkpoint comparison. Deviate to plain majority vote when there are too few overlap labels per rater to estimate a confusion matrix (fewer than about 20), and to a distributional target (keep the split) when disagreement is itself the signal.
Aggregation choices are budget choices: redundancy improves each target but reduces the number of distinct targets. The numbers below make the trade-off explicit.
Redundancy. Under a symmetric binary model where each rater independently matches a latent consensus label with probability \(p\), two raters agree with probability \(p^2 + (1-p)^2\). Solving for \(p\) given observed agreement \(a\): \(p = \tfrac{1}{2}\left(1 + \sqrt{2a - 1}\right)\). Majority of three is correct with probability
\[ p_3 = p^3 + 3p^2(1-p). \]W1's 72% agreement gives \(p = \tfrac{1}{2}(1 + \sqrt{0.44}) \approx 0.832\) and \(p_3 \approx 0.925\) (the simulation in the Build block measures 0.927). Now compare two uses of 24,000 labels: (a) 24,000 single-labelled pairs with flip rate \(\varepsilon = 0.168\); (b) 8,000 triple-labelled pairs with \(\varepsilon = 0.075\). For a logistic (Bradley–Terry) loss with symmetric label flips, each example's information is scaled by roughly \((1 - 2\varepsilon)^2\), giving effective clean examples of \(24{,}000 \times 0.664^2 \approx 10{,}560\) versus \(8{,}000 \times 0.849^2 \approx 5{,}770\). Under these assumptions, single-labelling yields almost twice the information. Overlap is still bought, at 10%, for measurement and for estimating Dawid–Skene confusion matrices, not as the main route to clean labels.
The assumption doing the work is symmetric, independent noise. If errors are systematic (all raters prefer the longer answer), redundancy does not remove them and neither does more data; that is a guideline and detection problem.
Dawid–Skene. Let item \(i\) have unknown true class \(t_i \in \{1..K\}\) with prior \(\pi_k\), and rater \(w\) have confusion matrix \(\theta^{(w)}_{k\ell} = P(\text{label } \ell \mid t = k)\). Raters are assumed conditionally independent given the truth, so the likelihood of item \(i\)'s labels is \(\sum_k \pi_k \prod_{(w,\ell) \in i} \theta^{(w)}_{k\ell}\). EM alternates
\[ \text{E: } T_{ik} \propto \pi_k \prod_{(w,\ell)\in i} \theta^{(w)}_{k\ell}, \qquad \text{M: } \theta^{(w)}_{k\ell} = \frac{\alpha + \sum_{i:(w,\ell)\in i} T_{ik}}{K\alpha + \sum_{i: w \in i} T_{ik}}, \quad \pi_k \propto \alpha + \sum_i T_{ik}. \]Here \(T_{ik}\) is the posterior that item \(i\) has class \(k\), and \(\alpha\) is a smoothing count that keeps rows from collapsing to zero when a rater has few labels. Gold items fix \(T_{ik}\) to the known class. Each rater has \(K(K-1)\) free parameters (6 for A/B/tie); the information to estimate them comes from items where the rater can be compared with someone or something else.
Per rater: about 40 overlap labels and 8.4 gold labels, so roughly 48 informative labels for 6 parameters, which is why the smoothing prior matters. Single-labelled items contribute only through the current estimates. A rater estimated at 0.83 accuracy produces a posterior of roughly 0.8 on their chosen label for a single-labelled item, which becomes a soft target near 0.8 rather than 1.0. Only about 10% of single-labelled items reach a posterior above 0.9 in the simulation, and those are 92% correct.
Soft targets for the reward model. Map the posterior over {A, B, tie} to a target probability \(y = T_A + \tfrac12 T_{\text{tie}}\) and train with cross-entropy against the model's \(\sigma(r_A - r_B)\); weight each example by a confidence such as one minus normalised entropy. Ties counted as half a win is a simplification; dedicated tie models exist, but the half-win convention is common and easy to audit.
Bradley–Terry. With positive strengths \(p_i\), \(P(i \succ j) = p_i/(p_i + p_j)\); writing \(p_i = 10^{R_i/400}\) gives the Elo scale, where a 400-point gap means 10:1 odds. The maximum-likelihood strengths satisfy \(p_i = W_i / \sum_{j} n_{ij}/(p_i + p_j)\), where \(W_i\) is \(i\)'s total wins and \(n_{ij}\) the games between \(i\) and \(j\); iterating that equation and renormalising is the minorise–maximise (MM) algorithm, which converges to the unique maximum when the comparison graph is connected (Zermelo 1929; Hunter 2004; both summarised in the Bradley–Terry article). Online Elo instead updates \(R_w \leftarrow R_w + K(1 - E_w)\) after each game, which makes the result depend on game order and on \(K\).
A 55% candidate win rate is \(400 \log_{10}(0.55/0.45) \approx 35\) Elo points. With 18,400 useful comparisons, the standard error of the win rate is \(\sqrt{0.55 \cdot 0.45 / 18{,}400} \approx 0.0037\); converting through the slope of the logistic curve gives a 95% interval of about \(\pm 5\) Elo points. Ties (8%) are counted as half wins for both sides.
| Method | Uses rater identity | Works on single labels | Breaks when | Use for |
|---|---|---|---|---|
| Majority vote | no | no (passes label through) | many weak raters, correlated errors | baseline; sanity check |
| Dawid–Skene (+gold) | yes, confusion matrix | yes, via rater reliability | <~20 informative labels per rater; copied answers | default for categorical labels |
| MACE / GLAD | yes, + spam or item difficulty | yes | subjective tasks (removes dissenters) | spam-heavy crowds |
| Bradley–Terry MLE | no (per object) | yes | intransitive or rater-dependent preferences | checkpoint and policy ranking; RM loss |
| Online Elo | no | yes | order dependence, K tuning | live leaderboards only |
Table. Aggregation methods and when each breaks.
What you would actually do. Spend most labels on unique items; fit Dawid–Skene with gold clamped and a smoothing prior; export soft targets with weights; use Bradley–Terry with bootstrap intervals for checkpoint comparisons. Deviate toward more redundancy for evaluation sets (where each label is a test of the model, so per-item correctness matters more than volume).
The aggregation module operates on the label table as three aligned integer arrays: items, workers, labels, one entry per judgement (shape (M,)), with classes 0 = A, 1 = B, 2 = tie for W1. Dawid–Skene returns the item posterior T (n_items × K), the confusion tensor conf (n_workers × K × K, indexed [rater, true, given]) and the class prior pi (K,). Bradley–Terry takes winner and loser index arrays and returns ratings on the Elo scale.
"""aggregate.py: turning many noisy labels into training targets.
Label table = three aligned int arrays (item, worker, label), one row per judgement."""
import numpy as np
def majority_vote(items, labels, n_items, K, rng=None):
"""Plurality label per item; ties between classes broken at random. Items with no labels -> -1."""
rng = rng or np.random.default_rng(0)
counts = np.zeros((n_items, K)); np.add.at(counts, (items, labels), 1)
out = np.full(n_items, -1)
for i in np.flatnonzero(counts.sum(1)):
top = np.flatnonzero(counts[i] == counts[i].max())
out[i] = rng.choice(top)
return out
def dawid_skene(items, workers, labels, n_items, n_workers, K,
gold=None, iters=100, alpha=1.0, tol=1e-6):
"""Dawid & Skene (1979) EM with a Dirichlet(alpha) smoothing prior on every confusion row.
gold: optional {item: true_class}; those posteriors are clamped (semi-supervised DS).
Returns T (n_items, K) posterior over the true class, conf (n_workers, K, K) where
conf[w, true, given] = P(worker w answers `given` | truth is `true`), and class prior pi (K,)."""
T = np.full((n_items, K), 1e-3); np.add.at(T, (items, labels), 1.0) # init: soft vote
T /= T.sum(1, keepdims=True)
gi = np.array(list(gold), int) if gold else np.array([], int)
gc = np.array(list(gold.values()), int) if gold else np.array([], int)
T[gi] = np.eye(K)[gc]
prev = -np.inf
for _ in range(iters):
# M-step: class prior and each worker's confusion matrix from soft counts
pi = (T.sum(0) + alpha) / (n_items + K * alpha)
conf = np.full((n_workers, K, K), alpha)
np.add.at(conf, (workers, slice(None), labels), T[items])
conf /= conf.sum(2, keepdims=True)
# E-step: posterior over the true class of each item
logT = np.tile(np.log(pi), (n_items, 1))
np.add.at(logT, items, np.log(conf[workers, :, labels]))
m = logT.max(1, keepdims=True)
ll = float((m[:, 0] + np.log(np.exp(logT - m).sum(1))).sum()) # marginal log-lik
T = np.exp(logT - m); T /= T.sum(1, keepdims=True)
T[gi] = np.eye(K)[gc]
if ll - prev < tol: break
prev = ll
return T, conf, pi
def worker_accuracy(conf, pi):
"""Expected accuracy of each worker under the class prior: sum_k pi_k * conf[w, k, k]."""
return np.einsum("k,wkk->w", pi, conf)
def preference_targets(T, a=0, b=1, tie=2):
"""Map a posterior over {A, B, tie} to a soft reward-model target P(A preferred)
(a tie counts as half) and a confidence weight (1 - posterior entropy / log 3)."""
p_a = T[:, a] + 0.5 * T[:, tie]
H = -(T * np.log(np.clip(T, 1e-12, 1))).sum(1)
return p_a, 1 - H / np.log(T.shape[1])
def bradley_terry(winners, losers, n_players, ties=None, iters=500, tol=1e-10):
"""Bradley-Terry MLE by the MM algorithm (Zermelo 1929; Hunter 2004).
P(i beats j) = p_i / (p_i + p_j). ties: optional (i, j) pairs, each counted as half a win for both.
Returns ratings on the Elo scale: 400 * log10(p_i), centred to mean 0."""
W = np.zeros((n_players, n_players)) # W[i, j] = wins of i over j
np.add.at(W, (winners, losers), 1.0)
if ties is not None and len(ties):
ti, tj = np.asarray(ties).T
np.add.at(W, (ti, tj), 0.5); np.add.at(W, (tj, ti), 0.5)
N = W + W.T # games between i and j
wins = W.sum(1)
p = np.ones(n_players)
for _ in range(iters):
denom = (N / (p[:, None] + p[None, :])).sum(1)
new = wins / denom
new /= np.exp(np.log(new).mean()) # fix the scale (geometric mean 1)
if np.max(np.abs(new - p)) < tol: p = new; break
p = new
r = 400 * np.log10(p)
return r - r.mean()
def online_elo(winners, losers, n_players, k=16.0, base=1000.0):
"""Classic online Elo: one sequential update per game. Result depends on game order."""
r = np.full(n_players, base)
for w, l in zip(winners, losers):
e_w = 1 / (1 + 10 ** ((r[l] - r[w]) / 400))
r[w] += k * (1 - e_w); r[l] -= k * (1 - e_w)
return r - r.mean()
def win_prob(r_i, r_j):
return 1 / (1 + 10 ** ((r_j - r_i) / 400))
Two details matter for correctness. The M-step uses np.add.at with a slice in the middle index so that each judgement adds its item's whole posterior row into the column of the label given; plain fancy-index assignment would silently drop repeated indices. The E-step works in log space and subtracts the row maximum before exponentiating, because an item with many labels from confident raters underflows otherwise.
The tests simulate a W1-shaped campaign (150 raters, 2,000 triple-labelled items, 18,000 single-labelled, 1,263 gold; 144 honest raters with accuracy between 0.75 and 0.92 and 6 low-effort raters who pick A 70% of the time), then check that Dawid–Skene is at least as accurate as majority vote, ranks every low-effort rater below the 5th percentile of honest raters, and that Bradley–Terry recovers known strengths while online Elo depends on game order.
import numpy as np
from aggregate import *
def simulate_w1(seed=1):
"""W1-shaped synthetic campaign: 150 raters, 20,000 items (2,000 triple-labelled,
18,000 single), 1,263 gold assignments, classes 0=A, 1=B, 2=tie with shares .46/.46/.08.
144 honest raters with accuracy ~ U(0.75, 0.92); 6 low-effort raters (4%) who answer
'A' 70% of the time regardless of content (position bias) and otherwise at random."""
rng = np.random.default_rng(seed)
n_items, n_gold, R, K = 20000, 1263, 150, 3
truth = rng.choice(K, size=n_items + n_gold, p=[.46, .46, .08])
acc = rng.uniform(0.75, 0.92, R); lazy = np.arange(R) >= 144
rows = [(i, w) for i in range(2000) for w in rng.choice(R, 3, replace=False)]
rows += [(i, rng.integers(R)) for i in range(2000, n_items)]
rows += [(n_items + g, rng.integers(R)) for g in range(n_gold)]
items = np.array([r[0] for r in rows]); workers = np.array([r[1] for r in rows])
labels = np.empty(len(rows), int)
for t, (i, w) in enumerate(rows):
if lazy[w]:
labels[t] = 0 if rng.random() < 0.7 else rng.integers(K)
elif rng.random() < acc[w]:
labels[t] = truth[i]
else:
labels[t] = rng.choice([c for c in range(K) if c != truth[i]])
gold = {n_items + g: truth[n_items + g] for g in range(n_gold)}
return items, workers, labels, truth, acc, lazy, gold, n_items + n_gold, R, K
def test_dawid_skene_beats_majority_and_finds_lazy_raters():
items, workers, labels, truth, acc, lazy, gold, N, R, K = simulate_w1()
assert len(labels) == 2000 * 3 + 18000 + 1263 == 25263
T, conf, pi = dawid_skene(items, workers, labels, N, R, K, gold=gold)
ds = T.argmax(1); mv = majority_vote(items, labels, N, K)
ov = np.arange(2000)
acc_mv, acc_ds = (mv[ov] == truth[ov]).mean(), (ds[ov] == truth[ov]).mean()
print(f"overlap items: majority {acc_mv:.3f} Dawid-Skene {acc_ds:.3f}")
assert acc_ds >= acc_mv
est = worker_accuracy(conf, pi)
print(f"estimated accuracy: honest median {np.median(est[~lazy]):.2f}, lazy {np.round(est[lazy], 2)}")
assert np.corrcoef(est[~lazy], acc[~lazy])[0, 1] > 0.5
assert est[lazy].max() < np.percentile(est[~lazy], 5) # all 6 lazy raters rank at the bottom
# single-labelled items: posterior confidence should be calibrated
single = np.arange(2000, 20000); conf_max = T[single].max(1)
hi = conf_max > 0.9
print(f"single items with posterior>0.9: {hi.mean():.2f}, accuracy {(ds[single][hi] == truth[single][hi]).mean():.3f}")
assert (ds[single][hi] == truth[single][hi]).mean() > 0.88
def test_preference_targets():
T = np.array([[0.9, 0.05, 0.05], [0.4, 0.4, 0.2], [1/3, 1/3, 1/3]])
p, w = preference_targets(T)
assert np.allclose(p, [0.925, 0.5, 0.5]) and w[0] > w[1] > w[2] and abs(w[2]) < 1e-9
def test_bradley_terry_recovers_strengths_and_elo_is_order_dependent():
rng = np.random.default_rng(2)
true = np.array([0.0, 35.0, 70.0, -50.0]) # Elo-scale; 35 pts = 55% win rate
a = rng.integers(4, size=20000); b = (a + rng.integers(1, 4, size=20000)) % 4
a_wins = rng.random(20000) < win_prob(true[a], true[b])
w, l = np.where(a_wins, a, b), np.where(a_wins, b, a)
bt = bradley_terry(w, l, 4)
assert np.max(np.abs(bt - (true - true.mean()))) < 10
assert abs(win_prob(35, 0) - 0.55) < 0.001
e1 = online_elo(w, l, 4); order = np.argsort(l, kind="stable"); e2 = online_elo(w[order], l[order], 4)
print("BT", np.round(bt, 1), "Elo shuffled", np.round(e1, 1), "Elo sorted", np.round(e2, 1))
assert np.max(np.abs(e1 - e2)) > 20 # same games, different order, different ratings
perm = rng.permutation(20000)
assert np.allclose(bradley_terry(w[perm], l[perm], 4), bt) # BT ignores order
Output of python3 -m pytest -q -s test_aggregate.py: overlap items: majority 0.927 Dawid-Skene 0.933; estimated accuracy: honest median 0.80, lazy [0.47 0.45 0.44 0.49 0.46 0.47]; single items with posterior>0.9: 0.10, accuracy 0.922. For the four simulated policies (true ratings −14, 21, 56, −64 after centring), Bradley–Terry returns −15.9, 20.0, 54.6, −58.8; online Elo with K = 16 returns 47.9, −57.9, 72.0, −61.9 in shuffled order and 420, 344, 149, −913 when the same games are sorted by loser. The figure plots the first two.
Debugging tips. (1) If Dawid–Skene accuracy is far below majority vote, check for label switching (the model has learned "A" means B for everyone); clamping gold prevents it. (2) If all estimated accuracies sit near the prior, raters have too few overlap or gold labels; raise targeted overlap for those raters rather than lowering alpha. (3) Honest accuracies are underestimated by a few points (0.80 median versus about 0.835 true here) because of smoothing; use them for ranking and weighting, not as absolute scores. (4) If Bradley–Terry does not converge, the comparison graph is disconnected (a policy that never played others); report it separately.
In production, aggregation runs as a nightly job per campaign that rewrites the soft-target table the export reads from. The failure modes are quiet: weights shift, the reward model trains, and nobody sees a broken number. The controls are versioning and a few monitored distributions.
Versioning. Every aggregation run writes a new version keyed by (campaign, label snapshot, code version, parameters). Exports reference an aggregation version, never "latest". A reward-model run can therefore be reproduced and a bad aggregation rolled back.
Dashboard. Panel 1: Dawid–Skene versus majority disagreement rate on overlap items (normally a few percent; a jump means the model has learned something majority cannot see, or has gone wrong). Panel 2: distribution of exported weights and the share of items with posterior above 0.9. Panel 3: per-rater estimated accuracy with interval width; raters whose interval is wider than ±0.15 are marked "cold". Panel 4: exported tie share and A-share after de-randomising position (should be about 50/50 if position randomisation works). Panel 5: checkpoint Bradley–Terry ratings with bootstrap intervals.
Symptom. Mid-campaign, 30 new raters join the W1 pool to keep pace. Two days later, panel 2 shows the share of exported items with weight above 0.5 rising from 61% to 70%, and the reward-model team reports training loss on the new export falling faster than on previous ones.
Diagnosis. Panel 3 shows the 30 new raters with only about 6 overlap labels and 2 gold labels each so far; their confusion matrices are dominated by the smoothing prior, which (because the prior is fitted to pool-level class shares) assigns them an accuracy near the pool median. Their single labels therefore receive the same confident weight as experienced raters'. Spot review of 60 of their labels by T1 reviewers finds 71% agreement with reviewer judgement, versus 83% for the experienced pool. The faster-falling loss came from the model fitting confidently labelled noise.
Remedy options. (a) Exclude new raters' labels until they have 50 assignments: simple, delays about 1,500 labels. (b) Down-weight by interval width: weight multiplied by a factor that grows with informative labels. (c) Targeted overlap: raise overlap to 30% for each new rater's first 50 assignments; each overlapped item needs two extra labels, so the extra cost is about 30 raters × 50 × 0.2 × 2 = 600 labels × 4.5 min ≈ 45 rater-hours ≈ $1,800. The campaign chose (b) immediately and (c) as policy: (b) protects the export now, (c) gives Dawid–Skene the data to estimate new raters within a day.
Validation. After re-aggregation, the share of high-weight items returns to 62%, and the reward model trained on the corrected export matches the previous export's accuracy on the held-out expert-adjudicated set. If accuracy had not moved, the weighting change would have been cosmetic and the next suspect would be the new raters' guideline version.
Alert rules. Page the campaign owner if the Dawid–Skene/majority disagreement on overlap exceeds 8% or doubles day over day; warn if more than 10% of exported weight comes from raters with interval width above ±0.15; warn if de-randomised A-share leaves 47–53%.
Correlated raters. Dawid–Skene's independence assumption is the main production risk. Raters who consult the same model agree with each other and with gold, so the model will assign them high reliability and up-weight them. Aggregation cannot detect this; detection (next section) must, and its output should flow back as a hold on those raters' labels before aggregation runs.
Cost. Aggregation compute is trivial (seconds for W1). The real costs are the overlap labels that feed it and the reward-model retrains that a changed aggregation triggers; version exports so that only changed campaigns retrain.
Detecting Low-Effort, LLM-Assisted and Adversarial Work
Detection is the part of the quality system that looks for work that was not done the way it was paid for. Three kinds matter. Low-effort work is clicking through: answering faster than the item can be read, always choosing the same side, writing boilerplate rationales. LLM-assisted work, in the sense that matters here, is undisclosed substitution of a model's judgement for the rater's own on a task meant to capture human judgement (some campaigns allow model assistance by design, and then the rule is disclosure, not prohibition). Adversarial work is deliberate gaming: sharing answers, running several accounts, scripting the interface, or learning to recognise gold items.
The problem became pressing in 2023. A study of crowd workers summarising medical abstracts estimated that 33–46% of summaries were produced with LLM help, and 89% of submissions involved pasting text (Veselovsky et al. 2023a). A follow-up estimated about 30% LLM use on a similar task and found that asking workers not to use LLMs together with disabling copy-paste roughly halved it (Veselovsky et al. 2023b). Crowd platforms now ship detection: Prolific describes authenticity checks that look at more than 15 behavioural patterns, including copy-pasting and tab-switching on free-text answers, and reports a vendor-measured 98.7% precision (Prolific 2025).
Detection works by collecting evidence from four signal families, chosen so that their errors are roughly independent:
Behaviour comes from the interface's event log: active time on an item (time between opening and submitting, minus time the tab was hidden), focus and blur events, paste events and how many characters were pasted, keystrokes, and choice patterns such as always picking the left response. It needs instrumentation in the annotation interface (Chapter 5), and it is cheap and immediate. Its limitation is that honest raters vary: an expert reads fast, and a coding rater may legitimately switch to a terminal to run code.
Agreement compares a rater's answers with references: gold accuracy, agreement with peers on overlap items, agreement with an LLM judge's answer on the same items (the LLM mirror signal: a rater who agrees with the model much more than with other humans is suspicious), and peer prediction. Peer prediction scores a rater by how much information their answers share with other raters' answers, without needing ground truth. The variant built for this problem conditions on LLM labels: it rewards agreement with peers beyond what the LLM's answer already explains, so a rater who only echoes the model earns roughly zero (Zhang et al. 2025).
Content examines free text such as rationales and rewrites: similarity to outputs that several models produce for the same prompt, stylistic markers, and pasted text that does not appear in the source. Text classifiers can be accurate when trained for one task (the 2023 study trained its own), but they do not transfer reliably, so content signals are evidence, not verdicts. Account and device signals catch adversarial patterns: several accounts on one device, bursts of identical answer sequences, sign-ins from automation environments.
The signals feed a per-rater, per-week evidence record. A triage rule decides what happens: one family firing leads to coaching; two independent families lead to a pause and human review; only a review that confirms the pattern leads to removal (the quality program). The reason for this structure is base rates: most raters are honest, so even a good single detector flags more honest raters than dishonest ones.
W1's median time per comparison is 4.0 minutes, and its low-effort rule flags raters whose median is below 40 seconds (4% of raters, 6 of 150). In the W1-shaped simulation of LLM copying (9 raters answering with a model that is right 85% of the time), gold accuracy barely separates copiers from honest raters (0.77 versus 0.80), peer agreement separates them in the wrong direction (copiers agree more), and the peer-prediction score conditioned on LLM labels separates them almost perfectly (AUC 0.98).
Compare and contrast. Classic crowdsourcing quality control relied on gold and agreement because cheating meant random answers, which both catch. LLM assistance produces answers that are good on average, so gold and agreement can reward it. The newer signals (paste events, LLM mirror, conditioned peer prediction) target the specific fingerprint of model substitution: answers that carry the model's information and little of the rater's own.
What you would actually do. Instrument the interface from the first campaign; compute the four families daily; never act on one family alone; publish the rules to raters in general terms (what is measured, not thresholds). Deviate toward stricter prevention (disable paste into answer fields, embed the tools raters need) when the task is free text, where LLM substitution is easiest.
Detection design is a classification problem with a low base rate and an expensive false positive (an honest person's income and trust). The numbers that decide the design are prevalence, per-signal recall and false-positive rate, and the correlation between signals.
Precision at low prevalence. With prevalence \(\pi\), recall \(r\) and false-positive rate \(f\), precision is
\[ \text{prec} = \frac{r\pi}{r\pi + f(1-\pi)}. \]Requiring two signals that are conditionally independent given the rater's true status multiplies recall and false-positive rates: \(r_2 = r^2\), \(f_2 = f^2\). Independence is an assumption: timing and paste signals are correlated (pasting is fast), so they belong to the same family; agreement-based and behaviour-based signals are closer to independent.
With 6 low-effort raters among 150 (\(\pi = 0.04\)), \(r = 0.8\), \(f = 0.05\): one signal flags 4.8 true and 7.2 honest raters per week, precision 0.40. Two independent families: \(r_2 = 0.64\), \(f_2 = 0.0025\), flags 3.8 true and 0.36 honest, precision 0.91. The two-family rule gives up about one true detection per week to avoid about seven false accusations.
Disproportionate contamination. Low-effort raters are fast, so they produce more than their share of labels. If a fraction \(\pi\) of raters work \(s\) times faster at the same hours, their share of labels is
\[ \lambda = \frac{\pi s}{\pi s + (1 - \pi)}. \]Nine raters (6%) who switch to consulting a model and drop from 4.0 to 1.6 minutes per label (\(s = 2.5\)) produce \(\lambda = 0.15/(0.15 + 0.94) \approx 14\%\) of labels while active. At 20 hours a week (about 4 hours a day), each produces about 150 labels a day; three days of this is about 4,050 labels, 17% of W1's 24,000. Detection latency is therefore measured in labels: each day of delay costs about 1,350 contaminated labels.
Timing thresholds. A time floor should come from reading time, not intuition. W1 items are two coding answers to read and compare; the campaign median is 4.0 minutes and the mean 4.5. The 40-second floor (one sixth of the median) is set where no honest rater in the pilot fell; it catches click-through but not a rater who consults a model and spends 90 seconds doing so. Timing therefore catches low effort, not LLM use.
LLM mirror. For each rater, compute agreement with an LLM judge on their items, \(a_{\text{LLM}}\), and agreement with human peers on overlap, \(a_{\text{peer}}\). Honest raters have \(a_{\text{LLM}} \approx a_{\text{peer}}\) (both near 0.70 in W1); copiers have \(a_{\text{LLM}} \gg a_{\text{peer}}\). The flag is \(a_{\text{LLM}} - a_{\text{peer}} > 0.15\). Its limitation: a rater who uses a different model than the one used as the judge shows a weaker gap, so the judge should be an ensemble of commonly available models.
Conditioned peer prediction. Let \(X_i\) be rater \(i\)'s report and \(Z\) the LLM's label on the same question. Zhang et al. estimate, for each LLM label value \(k\), the matrix \(\Delta_k(h,l) = P(X_i = h, X_j = l \mid Z = k) - P(X_i = h \mid Z = k)\,P(X_j = l \mid Z = k)\), set \(T_k = \mathbb{1}[\Delta_k > 0]\), and score rater \(i\) on a shared question \(q\) with peer \(j\) as \(T_k(x_{iq}, x_{jq}) - T_k(x_{iq}, x_{jq'})\), where \(q'\) is another question of \(j\)'s with the same \(Z\). With truthful reporting the expected score equals the conditional total-variation mutual information between raters given \(Z\); answers that only carry \(Z\)'s information score near zero (Zhang et al. 2025). The method needs no gold, only LLM labels on (a subset of) items, and its effectiveness depends on how well \(Z\) represents the model raters actually use.
| Dataset (Zhang et al. 2025) | Output agreement | Correlated agreement | Dawid–Skene EM | Conditioned CA (CA|Z) |
|---|---|---|---|---|
| Hatefulness | 0.66 | 0.84 | 0.81 | 0.85 |
| Offensiveness | 0.80 | 0.92 | 0.89 | 0.94 |
| Toxicity | 0.60 | 0.89 | 0.85 | 0.91 |
| Preference alignment | 0.65 | 0.70 | 0.68 | 0.85 |
Table. Reported AUC for detecting GPT-4-reliant workers in mixed crowds (Table 1 of Zhang et al. 2025, v2). The gain is largest on the preference task, which is closest to W1. The paper also notes that EM often does better when the crowd is entirely random or biased.
Design decisions. Which signals per task type: pairwise preference (timing, position bias, LLM mirror, CA|Z); free text (paste events, content similarity, timing per word); expert transcript review (timing per step viewed, jump patterns, rationale similarity). Default: two-family rule, daily windows, CA|Z computed with an ensemble LLM judge on all items (judging is cheap next to human labels). Deviate toward prevention rather than detection for free text.
The detection module has three layers: assignment features computed from the interface event log, transparent rater-level rules that each name the evidence they used, and the conditioned correlated-agreement (CA|Z) score. The event log is one JSON object per event, written by the annotation client and keyed by assignment:
{"assignment_id": "w1-a18342", "rater_id": "r077", "type": "paste", "t_ms": 66000,
"field": "rationale", "chars": 412, "client": "web-3.8.1", "guideline_version": "w1-g2"}
Recording the field on paste events matters: pasting into a code sandbox is legitimate in a coding campaign, pasting into the rationale field is the signal. Rater-level aggregates (median active seconds, share of A choices, paste share on rationale, agreement with LLM and peers, gold posterior) are computed nightly per rater-week and passed to the rules.
"""detect.py: behavioural features from the annotation event log, rater-level flags,
and a conditioned correlated-agreement (peer prediction) score in the spirit of
Zhang et al. 2025 (arXiv 2506.06991)."""
import numpy as np
from collections import defaultdict
from itertools import combinations
# ---------- 1. assignment-level features from the client event log ----------
def assignment_features(events):
"""events: time-ordered dicts for ONE assignment, e.g.
{"type": "open"|"blur"|"focus"|"key"|"paste"|"choose"|"submit", "t_ms": int, "chars": int, "side": "A"|"B"|"tie"}
Returns active seconds (open->submit minus time the tab was hidden), paste and typing counts, choice."""
t_open = next(e["t_ms"] for e in events if e["type"] == "open")
t_sub = next(e["t_ms"] for e in events if e["type"] == "submit")
hidden, blur_at = 0, None
for e in events:
if e["type"] == "blur": blur_at = e["t_ms"]
elif e["type"] == "focus" and blur_at is not None: hidden += e["t_ms"] - blur_at; blur_at = None
choice = [e["side"] for e in events if e["type"] == "choose"]
return {"active_s": (t_sub - t_open - hidden) / 1000,
"hidden_s": hidden / 1000,
"pastes": sum(e["type"] == "paste" for e in events),
"paste_chars": sum(e.get("chars", 0) for e in events if e["type"] == "paste"),
"keys": sum(e["type"] == "key" for e in events),
"choice": choice[-1] if choice else None}
# ---------- 2. rater-level rules (transparent; each flag carries its evidence) ----------
RULES = { # W1 defaults; tune per campaign from the pilot distribution
"too_fast": lambda r: r["median_active_s"] < 40, # campaign median ~240 s
"position_bias": lambda r: r["n"] >= 30 and abs(r["share_A"] - 0.5) > 0.25,
"paste_heavy": lambda r: r["paste_rationale_share"] > 0.5,
"llm_mirror": lambda r: r["n"] >= 30 and r["agree_llm"] - r["agree_peers"] > 0.15,
"gold_low": lambda r: r["gold_p_below"] > 0.95,
}
def flag_rater(r):
return [name for name, rule in RULES.items() if rule(r)]
# ---------- 3. conditioned correlated agreement (CA conditioned on LLM labels Z) ----------
def ca_z_scores(reports, z, n_cats):
"""reports: {worker: {question: answer}}; z: {question: LLM label} for (a subset of) questions.
Step 1: estimate Delta_k(h, l) = P(x_i=h, x_j=l | Z=k) - P(x_i=h | Z=k) P(x_j=l | Z=k)
from all pairs of reports on the same question, and set T_k = 1[Delta_k > 0].
Step 2: worker i earns T_k(x_iq, x_jq) on a shared question q (bonus) minus the average of
T_k(x_iq, x_jq') over peer j's other questions q' with the same Z value k (penalty).
Honest work earns the conditional mutual information with peers; answers that only
echo the LLM earn about zero. (Expected-penalty form of the sampled score.)"""
by_q = defaultdict(dict)
for w, ans in reports.items():
for q, a in ans.items():
if q in z: by_q[q][w] = a
joint = np.zeros((n_cats, n_cats, n_cats)) + 1e-9 # [k, h, l]
for q, ws in by_q.items():
for i, j in combinations(ws, 2):
joint[z[q], ws[i], ws[j]] += 1; joint[z[q], ws[j], ws[i]] += 1
joint /= joint.sum((1, 2), keepdims=True)
marg = joint.sum(2)
T = ((joint - marg[:, :, None] * marg[:, None, :]) > 0).astype(float) # [k, h, l]
cnt = defaultdict(lambda: np.zeros((n_cats, n_cats))) # cnt[j][k, l]: j answered l when Z=k
for j, ans in reports.items():
for q, a in ans.items():
if q in z: cnt[j][z[q], a] += 1
scores = {}
for i, ans in reports.items():
s = []
for q, a in ans.items():
if q not in z: continue
k = z[q]
for j, b in by_q[q].items():
if j == i: continue
n_other = cnt[j][k].sum() - 1
if n_other < 1: continue
penalty = (cnt[j][k] @ T[k, a] - T[k, a, b]) / n_other
s.append(T[k, a, b] - penalty)
scores[i] = float(np.mean(s)) if s else np.nan
return scores
def auc(scores_pos, scores_neg):
"""P(random positive scores higher than random negative); ties count half."""
p, n = np.asarray(scores_pos)[:, None], np.asarray(scores_neg)[None, :]
return float((p > n).mean() + 0.5 * (p == n).mean())
The CA|Z implementation uses the expected value of the penalty term (averaging over all of the peer's questions with the same LLM label) instead of sampling one penalty question, which gives the same expected score with lower variance. The test simulates W1 volumes: 8,400 binary questions with 3 raters each (168 answers per rater, as in W1), honest raters right 80% of the time, an LLM right 85% of the time, and 9 copiers who report the LLM's answer with 10% sampling noise.
import numpy as np
from detect import *
def test_assignment_features_subtract_hidden_time():
ev = [{"type": "open", "t_ms": 0}, {"type": "blur", "t_ms": 5000}, {"type": "focus", "t_ms": 65000},
{"type": "paste", "t_ms": 66000, "chars": 900}, {"type": "choose", "t_ms": 70000, "side": "A"},
{"type": "submit", "t_ms": 75000}]
f = assignment_features(ev)
assert f["active_s"] == 15 and f["hidden_s"] == 60 and f["paste_chars"] == 900 and f["choice"] == "A"
def test_rules():
honest = dict(n=168, median_active_s=230, share_A=0.52, paste_rationale_share=0.02,
agree_llm=0.70, agree_peers=0.72, gold_p_below=0.10)
mirror = dict(honest, median_active_s=95, agree_llm=0.95, paste_rationale_share=0.8)
assert flag_rater(honest) == [] and flag_rater(mirror) == ["paste_heavy", "llm_mirror"]
def simulate(seed=3, n_q=8400, per_q=3, n_workers=150, n_cheat=9):
"""8,400 binary questions x 3 raters = 168 answers per rater (W1 workload per rater).
Truth Y; honest signal = Y w.p. 0.80 (independent per worker);
LLM label Z = Y w.p. 0.85; cheaters ask the same LLM and get Z w.p. 0.9 (sampling noise)."""
rng = np.random.default_rng(seed)
Y = rng.integers(2, size=n_q); Z = np.where(rng.random(n_q) < 0.85, Y, 1 - Y)
cheat = np.zeros(n_workers, bool); cheat[:n_cheat] = True
reports = {w: {} for w in range(n_workers)}
for q in range(n_q):
for w in rng.choice(n_workers, per_q, replace=False):
if cheat[w]: a = Z[q] if rng.random() < 0.9 else 1 - Z[q]
else: a = Y[q] if rng.random() < 0.8 else 1 - Y[q]
reports[w][q] = int(a)
return reports, Y, {q: int(Z[q]) for q in range(n_q)}, cheat
def test_ca_z_separates_llm_copiers_where_gold_and_agreement_do_not():
reports, Y, z, cheat = simulate()
acc = np.array([np.mean([a == Y[q] for q, a in reports[w].items()]) for w in reports])
# plain output agreement with peers (OA): fraction of matches with co-raters
by_q = {}
for w, ans in reports.items():
for q, a in ans.items(): by_q.setdefault(q, {})[w] = a
oa = np.array([np.mean([a == b for q, a in reports[w].items()
for j, b in by_q[q].items() if j != w]) for w in reports])
sc = ca_z_scores(reports, z, 2); ca = np.array([sc[w] for w in reports])
a_gold, a_oa, a_ca = auc(acc[~cheat], acc[cheat]), auc(oa[~cheat], oa[cheat]), auc(ca[~cheat], ca[cheat])
print(f"AUC honest-vs-copier gold accuracy {a_gold:.2f} peer agreement {a_oa:.2f} CA|Z {a_ca:.2f}")
print(f"mean CA|Z honest {ca[~cheat].mean():.3f} copier {ca[cheat].mean():.3f}")
print(f"mean gold acc honest {acc[~cheat].mean():.3f} copier {acc[cheat].mean():.3f}")
assert a_ca > 0.9 and a_ca > a_gold + 0.15 and a_ca > a_oa + 0.3
Output: AUC honest-vs-copier gold accuracy 0.76 peer agreement 0.40 CA|Z 0.98; mean CA|Z honest 0.080 copier -0.000; mean gold acc honest 0.799 copier 0.772. Note that "gold accuracy" here uses all 168 answers per rater as if every one were gold; with W1's 8 gold items per rater it would separate even less. Peer agreement below 0.5 means copiers look better than honest raters on that metric, because the model is more accurate than an individual rater.
Debugging tips. (1) If CA|Z is near zero for everyone, the LLM labels explain most of the agreement, either because the task is easy (everyone agrees with the model) or because the LLM labels are leaking into the interface; check the share of items where all raters and the LLM agree. (2) If active time is negative or huge, the client is missing focus events after a blur (mobile browsers suspend tabs); cap hidden intervals and log client versions. (3) Thresholds in RULES come from the pilot distribution; re-derive them per campaign, because a coding campaign and a short-text campaign have different time scales.
In production, detection is a daily batch over the previous 24 hours plus the rater's rolling history, feeding alerts, a triage queue and the enforcement ladder. Its quality is measured like any classifier, with labels from human review: precision of pauses (share of paused raters confirmed by review), recall estimated from audits (share of bad labels in random audits that came from unflagged raters), and latency (hours from first bad label to hold).
| Metric | Target | Source |
|---|---|---|
| Hold latency | ≤ 24 h from onset to quarantine | event timestamps vs hold timestamp |
| Pause precision | ≥ 0.8 confirmed by review | T2 review outcomes |
| Weekly flag rate | alert if > 2× trailing 4-week mean | evidence records |
| Audit-estimated undetected bad labels | ≤ 2% of exported labels | quality-program audit (next section) |
Table. Detection SLOs (illustrative W1 targets).
# alerts/w1_detection.yaml
- name: llm_mirror_gap
expr: rater_daily.agree_llm - rater_daily.agree_peers > 0.15 and rater_daily.n >= 30
window: 1d # was 7d; see incident in r-q-program
family: agreement
- name: ca_z_low
expr: rater_daily.ca_z < 0.25 * campaign_daily.ca_z_median and rater_daily.n >= 60
family: agreement
- name: rationale_paste
expr: rater_daily.paste_rationale_share > 0.5
family: behaviour
- name: flag_storm
expr: campaign_daily.flagged_raters > 2 * campaign_4w.flagged_raters_mean
action: page_quality_owner # a rule is probably wrong, not the pool
Symptom. In the first week of W1 a new behaviour rule, "hidden time above 50% of the assignment or any paste event", flags 22 of 150 raters (15%) against an expected 4%. The flag-storm alert fires.
Diagnosis. T2 reviewers sample 5 assignments from each flagged rater (110 assignments). In 96 of them the rater copied code from a response, pasted it into a local terminal or editor, ran it and came back: hidden time was long and paste events were real, but the paste was into the interface's code field, not the rationale. Prolific's documentation notes the same limitation for its own checks: they fit poorly when a study requires external tools (Prolific, authenticity checks). The rule measured the honest workflow of a coding campaign.
Remedy. (1) Embed a sandboxed run button in the interface so that running code no longer needs another tab (also reduces median time by an estimated few tens of seconds; to be measured with an interface experiment, Chapter 5). (2) Scope the paste rule to the rationale field and require the pasted text to be absent from both responses. (3) Exclude hidden time spent in the embedded sandbox from active-time calculations. (4) Retract the 22 flags and notify the raters that no action was taken.
Result and validation. The re-run rule flags 4 raters; review confirms 3 (pasted rationales matching model output), precision 0.75. The test that would have weakened the diagnosis: if, after scoping, flags had stayed above 10%, the cause would have been something other than code-running, such as raters drafting rationales elsewhere.
Cost. The 110-assignment review cost about 18 reviewer-hours. The bigger cost avoided is trust: 19 honest raters paused would have been about 13% of pool capacity (380 rater-hours a week) and a predictable rise in attrition.
Runbook: rater flagged. 1. Confirm the evidence record names at least one signal and its values; if only one family, send coaching (template message) and stop. 2. If two families: place the rater on pause, which quarantines labels since first flag. 3. Sample 10 of the rater's recent assignments for T2 review, with the evidence hidden from the reviewer to avoid anchoring. 4. If review confirms: proceed to the removal step with the appeal window. If not: lift the pause within 24 hours, release quarantined labels, record the false positive against the rule. 5. Any rule with pause precision below 0.6 over a month is disabled until re-derived.
Adversarial adaptation. Published rules get gamed: a rater who knows the time floor waits. Keep thresholds private, rotate gold, compute signals the rater cannot see (CA|Z, LLM mirror), and watch for sudden convergence of a cohort's answer sequences, which is the signature of shared answer keys.
Running the Quality Program
A quality program is the set of people, processes and rules that act on the measurements and detections of the previous sections: who reviews which work, what raters are told, what happens to a rater whose work is poor or dishonest, and how the campaign proves the quality of what it exports. Without a program, metrics are just dashboards; with a heavy-handed one, honest raters leave and the remaining pool learns to game the rules. The program has four parts.
Review tiers decide who looks at which work. Tier 0 is automatic and covers everything: schema validity, minimum active time, required fields, gold scoring. Tier 1 is peer review by senior raters on a small random sample (a few percent), checking that the label follows the guideline; it is cheap and fast. Tier 2 is expert or researcher audit on a smaller sample (around 1%), checking that the guideline itself produces the data the research needs; it is expensive and catches problems the other tiers share. Targeted review adds a heavier sample for raters who are new or flagged. Samples are drawn so that raters cannot tell which items will be reviewed, and each review produces a structured verdict (agree, disagree with reason, guideline gap), not free text.
Feedback to raters closes the loop. Each rater sees a scorecard (gold accuracy with an explanation of each missed gold item, agreement with peers, review verdicts) and, when a pattern appears, a coaching note that points to the guideline section involved. Calibration sessions (raters label the same small set, then compare against an expert key and discuss) align a pool at launch and after guideline changes. Feedback is the cheapest quality intervention: most raters who are told specifically what they got wrong improve.
Removal policy is a graduated enforcement ladder: coach, retrain, pause, remove. Each step requires more evidence than the last, every step is logged with its evidence, and removal requires a human reviewer's confirmation and an appeal window. Pausing a rater quarantines their recent labels: they are held out of exports, not deleted, so a reversed decision costs nothing. If removal is confirmed, quarantined labels are relabelled by trusted raters. Removal should be conservative for subjective tasks: a study of spam-filtering methods found that removing more than about 5% of annotators distorted label distributions, because filters remove raters who legitimately disagree (Fleisig et al. 2025). Published practice varies: Anthropic's HH work used spot-checks of writing quality rather than agreement-based filtering and banned a small number of very low-quality workers (Bai et al. 2022).
Audits estimate the error rate of what is actually exported. A random sample of exported items, independent of all detection, is relabelled by experts; the disagreement rate, with a confidence interval, is attached to the dataset version. Audits measure what the other parts missed, so they must not reuse their selection.
W1 reviews 100% of assignments automatically, about 1,263 by peer review (5%) and about 253 by expert audit (1%), and 25% of the work of flagged and new raters. QA rejects 8% of comparisons, leaving about 18,400 useful ones at about $4.12 each. A random audit of about 700 exported comparisons estimates the exported error rate to within ±2 points. In W2, 200 of 2,000 transcripts (10%) are double-reviewed at about $14,000 extra.
Compare and contrast. Early crowdsourcing programs were mostly filters: gold tests and automatic bans. RLHF programs with trained vendor pools and experts look more like a managed workforce: training, feedback and graduated responses, because each rater is expensive to onboard and train, and because a false accusation costs a skilled person their work. The cost of the managed approach is reviewer time and slower action; the cost of pure filtering is distorted data and attrition.
What you would actually do. Run T0 on everything, T1 at 5%, T2 at 1%, targeted at 25% for new and flagged raters; give weekly scorecards; use the four-step ladder with quarantine; cap removals per campaign at about 5% without a second review of the policy; audit about 700 exported items per campaign. Deviate toward heavier T2 when the guideline is new or the domain is expert (W2, W3), because then the guideline is the main source of error.
The program's design numbers are review costs, audit sample sizes and the latency the program adds to the request-to-mix path.
Review cost. For tier \(t\) with sampling rate \(s_t\), review time per item \(\tau_t\) and hourly rate \(c_t\), cost is \(N s_t \tau_t c_t\) for \(N\) assignments. Review is faster than labelling because the reviewer checks a decision rather than making one; the review times below are assumptions to replace with pilot measurements.
T1: \(25{,}260 \times 0.05 = 1{,}263\) reviews × 2 min (assumed) = 42 h × $40 ≈ $1,700. T2: \(25{,}260 \times 0.01 \approx 253\) audits × 6 min (assumed) ≈ 25 h × $120 (expert rate, as in W2) ≈ $3,000. Gold: 1,263 assignments × 4.5 min ≈ 95 h ≈ $3,800 of the $75,780 labour. Overlap: 4,000 extra labels × 4.5 min = 300 h ≈ $12,000. Total spend attributable to quality ≈ $20,500, about 27% of the $75,780 labour figure, of which overlap is the largest item, which is one more reason to keep overlap at 10% rather than more (aggregation).
Audit size. To estimate the exported error rate \(\varepsilon\) to a 95% half-width \(h\), a simple random audit needs
\[ n = \frac{1.96^2\,\varepsilon(1-\varepsilon)}{h^2}. \]At \(\varepsilon = 0.08\) and \(h = 0.02\), \(n = 707\). If the platform also has a cheap automatic quality score on every item (an LLM judge, the Dawid–Skene posterior), prediction-powered inference combines the small audit with the large automatic signal and gives valid intervals that are narrower when the automatic score is accurate (Angelopoulos et al. 2023); the audit remains the ground truth that corrects the automatic score's bias.
Removal budget. Let \(\rho\) be the share of raters removed. Fleisig et al. found that beyond about 5% removal every filtering method they tested increased error against non-spammers' average labels, and most real spammers looked statistically like genuine annotators (Fleisig et al. 2025). A program that removes more than 5% of a pool should treat that as a signal to re-examine the rules.
4% of W1 raters (6 of 150) are flagged for low effort, inside the 5% budget. Removing them and relabelling their work (each produced about 168 assignments, so about 1,000 labels) costs about \(1{,}000 \times 4.5/60 \approx 76\) rater-hours ≈ $3,000 and is absorbed by pool capacity (3,000 rater-hours a week) within a day.
Latency. In the W1 baseline, QA is a 3-day batch phase in a 21-day request-to-mix path. A batch phase adds its full duration; a continuous program adds only the lag of the last day's checks. With T0 real-time, T1 within 24 hours, detection on daily windows, and the audit drawn progressively during collection, QA at the end shrinks to sign-off (hours), removing most of those 3 days toward the 7-day target.
| Lever | More of it buys | Costs | Default |
|---|---|---|---|
| T1 rate | faster per-rater evidence | senior-rater hours | 5% |
| T2 rate | guideline-level errors found | expert hours, slow | 1% (higher for new guidelines) |
| Audit size | tighter exported-error interval | expert hours | ~700 per campaign |
| Ladder strictness | less contamination | false accusations, attrition | pause on two families; remove only after review |
| Feedback frequency | faster improvement | ops time | weekly scorecards, immediate gold explanations |
Table. Program levers and defaults.
What you would actually do. Budget roughly a quarter of labour for quality, most of it in overlap and gold; size audits from the formula; run the program continuously during collection. Deviate toward a larger T2 share when the campaign introduces a new feedback type (W3), where the dominant risk is a rubric that measures the wrong thing.
The program is configuration plus a small executor. Keeping the policy in a versioned YAML file means a change of threshold is reviewed like code and every decision can be traced to the policy version in force. The executor does four things: deterministic review sampling, audit sizing, the ladder decision and quarantine.
# w1_quality_policy.yaml: the quality program for the W1 pairwise campaign, as data.
campaign: w1_coding_pref
review_tiers:
t0_automatic: {coverage: 1.00, checks: [schema, min_active_s, rationale_present, gold_score]}
t1_peer_review: {rate: 0.05, reviewer_pool: senior_raters, sla_hours: 24}
t2_expert_audit: {rate: 0.01, reviewer_pool: researchers_and_leads, sla_hours: 72}
targeted: {rate: 0.25, applies_to: [flagged_raters, new_raters_first_50]}
gold:
share_of_assignments: 0.05
threshold: 0.80
prior: [8, 2] # Beta prior: mean 0.8, weight 10 items
evidence_p_below: 0.95 # act only when P(accuracy < threshold) > 0.95
rotate_after_exposures: 30 # retire a gold item once 30 raters have seen it
ladder: # graduated responses; each step logs evidence and is reversible
- {step: coach, when: "one_flag"}
- {step: retrain, when: "two_flags_or_gold_low"}
- {step: pause, when: "two_independent_signals", requires_human_review: true}
- {step: remove, when: "confirmed_by_review", requires_human_review: true, appeal_days: 5}
quarantine:
on: pause # labels since first flag are held out of exports, not deleted
relabel_if_removed: true
audit:
target_error_half_width: 0.02
expected_error_rate: 0.08
"""policy.py: executes w1_quality_policy.yaml: deterministic review sampling, audit sizing,
the graduated enforcement ladder and label quarantine."""
import hashlib, math, yaml
def load(path="w1_quality_policy.yaml"):
return yaml.safe_load(open(path))
def sampled(assignment_id: str, rate: float, salt: str) -> bool:
"""Deterministic, unpredictable sampling: the same assignment always gets the same answer
(replayable), raters cannot tell which items are reviewed, and tiers use different salts."""
h = int(hashlib.sha256(f"{salt}:{assignment_id}".encode()).hexdigest()[:12], 16)
return h / 16 ** 12 < rate
def review_tiers(assignment_id, rater_flagged, rater_n_done, pol):
t = pol["review_tiers"]; tiers = ["t0_automatic"]
if sampled(assignment_id, t["t1_peer_review"]["rate"], "t1"): tiers.append("t1_peer_review")
if sampled(assignment_id, t["t2_expert_audit"]["rate"], "t2"): tiers.append("t2_expert_audit")
if (rater_flagged or rater_n_done < 50) and sampled(assignment_id, t["targeted"]["rate"], "tg"):
tiers.append("targeted")
return tiers
def audit_sample_size(p, half_width, z=1.96):
return math.ceil(z * z * p * (1 - p) / half_width ** 2)
def next_step(flags, gold_low, independent_signals, review_confirmed):
"""flags: list of behavioural flags this week; independent_signals: count of signal FAMILIES
(behaviour, agreement/peer-prediction, gold, content) that fired. Returns the ladder step."""
if review_confirmed: return "remove"
if independent_signals >= 2: return "pause"
if len(flags) >= 2 or gold_low: return "retrain"
if len(flags) == 1: return "coach"
return "none"
def quarantine(labels, rater, since_ts):
"""labels: list of dicts with rater, ts. Returns (kept, held) without deleting anything."""
held = [l for l in labels if l["rater"] == rater and l["ts"] >= since_ts]
kept = [l for l in labels if not (l["rater"] == rater and l["ts"] >= since_ts)]
return kept, held
Why hash-based sampling. A random number generator called at assignment time produces a sample nobody can reproduce. Hashing the assignment id with a per-tier salt gives the same answer every time (so a re-run of the pipeline reviews the same items), independent samples per tier (different salts), and no pattern a rater can learn from the item. The salt must be secret from raters and vendors.
from policy import *
def test_sampling_rates_and_determinism():
pol = load()
ids = [f"w1-a{i}" for i in range(25260)]
t1 = sum(sampled(a, 0.05, "t1") for a in ids)
assert 1150 < t1 < 1380 # ~1,263 expected
assert sampled("w1-a7", 0.05, "t1") == sampled("w1-a7", 0.05, "t1")
both = sum(sampled(a, 0.05, "t1") and sampled(a, 0.01, "t2") for a in ids)
assert both < 40 # tiers independent: ~13 expected
assert review_tiers("w1-a1", False, 500, pol)[0] == "t0_automatic"
def test_audit_size():
assert audit_sample_size(0.08, 0.02) == 707
def test_ladder_requires_two_independent_signal_families_to_pause():
assert next_step(["too_fast"], False, 1, False) == "coach"
assert next_step(["too_fast", "paste_heavy"], False, 1, False) == "retrain" # same family
assert next_step(["llm_mirror"], True, 2, False) == "pause"
assert next_step([], False, 0, True) == "remove"
def test_quarantine_keeps_everything():
labels = [{"rater": "r9", "ts": t} for t in range(10)] + [{"rater": "r1", "ts": 5}]
kept, held = quarantine(labels, "r9", 6)
assert len(held) == 4 and len(kept) == 7 and len(kept) + len(held) == len(labels)
On 25,260 W1 assignment ids the T1 sampler selects close to the expected 1,263; the T1-and-T2 overlap is close to the expected 13; audit_sample_size(0.08, 0.02) returns 707. The ladder test encodes the policy that two flags from the same family (fast and paste-heavy, both behaviour) lead to retraining, not a pause. The full chapter suite: python3 -m pytest -q passes 15 tests in about 1.4 seconds.
Debugging tips. (1) If reviewers report that they keep seeing the same raters, check that targeted sampling is not stacking on top of T1 for the same item; dedupe by assignment. (2) If quarantine counts do not match flag counts, check clock skew between the label store and the evidence record; quarantine on server timestamps. (3) Store every ladder decision as an event with policy version, evidence ids and decider; an appeal needs all three.
Operating the program means keeping its loops fast and its decisions fair, and proving the quality of each exported dataset version. The SLOs below cover all four parts.
| Part | SLO (W1 defaults) |
|---|---|
| T1 review | 95% of sampled items reviewed within 24 h |
| T2 audit | 95% within 72 h; audit of ~700 exported items complete before export sign-off |
| Hold | quarantine applied ≤ 4 h after a pause decision |
| Feedback | gold explanation shown on submit; scorecard weekly |
| Fairness | pause precision ≥ 0.8; appeals answered within 5 days; removals ≤ 5% of pool per campaign without policy review |
| Exported quality | audit error ≤ 8% with 95% CI half-width ≤ 2 points, stored on the dataset version |
Table. Quality-program SLOs (illustrative).
Symptom. On day 3 of W1 collection the LLM-mirror rule (then on a 7-day window) fires for 9 raters (6% of the pool). The dashboard shows their median active time fell from 4.1 to 1.7 minutes on day 2 and their agreement with the ensemble LLM judge rose from 0.71 to 0.94, while the rest of the pool stayed at 4.0 minutes and 0.70. Their gold accuracy rose slightly, from 0.84 to 0.87, comfortably above the 0.80 threshold. The low-effort rule (median below 40 seconds) did not fire for any of them.
Separating causes. Hypotheses: (a) a cohort of genuinely fast experts, (b) a shared answer key, (c) undisclosed model use. CA|Z for the cohort is about 0 versus a pool median of 0.08, meaning their answers carry no information beyond the LLM's, which argues against (a). Their answer sequences do not match each other more than the LLM explains, which argues against (b). Rationale texts from 7 of the 9 are near-paraphrases of what the judge models produce for the same pair, and paste events into the rationale field appear in 80% of their assignments from day 2. All 9 joined the pool through the same vendor team. Two independent families (agreement and behaviour) fire, so the ladder places all 9 on pause.
Impact. At about 4 hours a day and 1.6 minutes a label, each produced about 150 labels a day; days 2–4 give about 9 × 150 × 3 = 4,050 labels, 17% of W1's 24,000. The labels were also measurably different: they chose the longer response 68% of the time versus 55% for the pool (illustrative), consistent with the verbosity bias documented for LLM judges (Zheng et al. 2023). A reward model trained on them would learn a length preference the guidelines did not ask for. Dawid–Skene had up-weighted these raters, because they agreed with gold and with each other.
Remedy. (1) Quarantine the 4,050 labels (within the 4-hour SLO). (2) T2 reviews 10 assignments per rater, with evidence hidden; review confirms 9 of 9. (3) Notify the vendor with the evidence summary; the raters enter the removal step with a 5-day appeal window. (4) Relabel the 4,050 items with the trusted pool: 4,050 × 4.5 min ≈ 304 rater-hours ≈ $12,150, about 10% of a week's pool capacity, completed in about half a day. Cost per useful comparison rises from about $4.12 to about $4.78 ((75,780 + 12,150) / 18,400). The request-to-mix path loses about one day.
Validation. Two checks. First, a reward model trained on the cleaned export versus one trained with the quarantined labels included, both evaluated on a held-out expert-adjudicated set: the cleaned model should be at least as accurate and should show a smaller length preference on pairs matched for quality. Second, the relabels of the quarantined items should agree with the quarantined labels at roughly the LLM–human agreement rate (about 0.70), not at the human–human rate on easy items. If the cleaned model were no better and showed the same length preference, the contamination would not be the main cause of length bias and the guideline would be the next suspect.
Follow-ups. Move agreement-family rules to daily windows (the 7-day window cost about one day, about 1,350 labels); add CA|Z to the default alert set; record vendor team on every rater so cohort effects are visible; remind raters in the guideline, in plain terms, what model use is and is not allowed in this campaign, which the 2023 study found roughly halves model use when combined with disabling paste (Veselovsky et al. 2023b).
Runbook: suspected quality collapse in a cohort. 1. Confirm the signal on the dashboard against the trailing week and the CI. 2. Identify the cohort (vendor team, start date, client version, guideline version). 3. Check which signal families fire; if only one, coach and watch daily. 4. If two or more: pause and quarantine since first anomaly (use the earliest panel that moved, not the alert time). 5. T2 review with evidence hidden. 6. Decide: release, or remove with appeal and relabel. 7. Re-run aggregation and re-cut any export that included quarantined labels; notify reward-model owners of the affected export versions. 8. Write the post-incident note with the label count, cost, rules changed and the validation result.
Gold is not enough. The lesson of this incident generalises: gold items measure whether answers are right, and a strong model gives right answers. A program that only watches gold will pass exactly the contamination that matters most for human-preference data, which is answers that are plausible, consistent and not the rater's own judgement.
From Feedback to Training Signal
A rater's click or an expert's corrected paragraph is not yet training data. Between the feedback interface and the training mix sits a data pipeline that has to answer five questions for every label: what exactly was recorded, which training example it becomes, where that example came from, whether it is fit to train on, and whether the answer will be the same tomorrow. This chapter covers that pipeline.
The pipeline has a fixed shape. Interfaces and services emit events: small, immutable records of something that happened (a rater submitted a choice, a reviewer rejected a label). Events are appended to a log and never edited. A fold reads the log and computes one current record per assignment. Transforms turn records into the formats each consumer needs: preference pairs for a reward model, prompt and completion pairs for supervised fine-tuning, per-step labels for a process reward model, rubric packages for a reward service. Gates check the rows against a written contract, remove duplicates, remove anything that overlaps evaluation sets, and scrub personal data. The result is published as an immutable, content-addressed snapshot with a manifest that records its inputs, code and counts.
The four sections follow the data: the data model and how to add a new feedback type (r-pipe-model), the transforms (r-pipe-transform), provenance and versioning (r-pipe-lineage), and validation, deduplication, decontamination and PII handling (r-pipe-validate). The design default throughout is that raw feedback is the system of record and everything after it is derived, so any bug downstream can be fixed by changing code and replaying rather than by asking people to label again.
The pipeline's job is measured by three numbers: how long an accepted label takes to reach a published dataset (freshness), whether every accepted label is either used or dropped for a stated reason (completeness), and whether a published dataset can be rebuilt bit for bit (reproducibility). The design choices in this chapter trade storage and compute, which are cheap at human-data volumes, for those three properties.
What you would actually do: size the pipeline for correctness and replay, not throughput. Keep raw events forever (or for the full retention period), make every transform a pure function of raw events plus versioned code and config, and spend engineering on contracts and lineage. Deviate only when a single campaign produces more data than one machine can replay in a few hours, which at human-labelling rates is unusual.
The Build blocks of this chapter share one small, standard-library Python package with a test suite. Each section shows the part it explains; together they run end to end from raw events to a verified, contract-checked dataset. The module layout follows the pipeline stages: a data model with a schema registry and a fold, pure transforms per consumer, a manifest and lineage module, and a validation module. Every snippet in the chapter is cut from these files, and the tests below were run on them.
feedback_pipe/
feedback_model.py # FeedbackEvent, SchemaRegistry (validate + upcast), fold()
transforms.py # to_rm_pairs, to_correction_sft, to_process_labels, rubric_reward, ...
lineage.py # canonical shards, build_manifest, verify, LineageGraph
validate.py # check_contract, near_duplicates (MinHash LSH), contaminated, scrub
test_pipe.py # W1 / W2 / W3 fixtures
$ python3 -m pytest -q test_pipe.py
.............. [100%]
14 passed in 0.11s
Three conventions hold everywhere. Every function that produces rows also returns a drop ledger (a counter of reasons), so tests can assert that inputs reconcile to outputs. Every artifact that crosses a boundary is identified by a content hash of its canonical JSON, so equality means byte equality. And no transform reads wall-clock time or random state, so a rebuild produces the same dataset id.
In production the pipeline is a service with its own objectives, separate from the collection services in earlier chapters. The Google SRE workbook's chapter on data pipelines recommends expressing freshness as the share of data processed within a time bound, checking correctness against known "golden" inputs, and measuring end to end because consumers only experience the sum of all stages; it also argues that stale data is almost always better than incorrect data, so a pipeline should stall rather than publish bad output (Sodt et al., 2018). The table applies that guidance to feedback data. The thresholds are recommended starting points for the reference workloads, not published figures.
| SLI | Definition | SLO (starting point) | On breach |
|---|---|---|---|
| Freshness | Time from QA acceptance to presence in a published snapshot | 99% within 24 h | Ticket; page if the oldest unpublished accepted label is older than 48 h |
| Completeness | (used + dropped with reason + quarantined) / accepted | Exactly 1.000 per snapshot | Block publish; any unexplained loss is a bug |
| Quarantine rate | Events failing schema validation / events ingested, per event type | < 0.5% daily | Page if > 0.5% for 15 min (a producer is broken) |
| Correctness | Contract violations in a candidate snapshot; golden-input replay diff | 0 violations; 0 diff | Block publish |
| Reproducibility | Published snapshots whose rebuild yields the same dataset id | 100% (weekly sample of 5) | Freeze code changes to the failing transform |
| Hygiene | Eval n-gram hits and residual structured PII in published data | 0 in published snapshots | Revoke snapshot; walk lineage downstream |
The rest of the Operate blocks work through one incident or scaling scenario per section: a schema break in W3, a slot-mapping bug in W1 transforms, a rater-removal request that has to propagate through lineage, and a decontamination finding.
The Feedback Data Model and Adding a New Feedback Type
A feedback data model is the set of types and rules that say what a piece of human feedback is when it is stored: which fields it has, what values are legal, how it refers to the prompt, the model responses and the person who gave it, and how it changes over time. Every later stage depends on it. A transform can only be as correct as the model it reads, and a new kind of feedback cannot be collected until the model can represent it.
The earlier approach and its limit. The obvious design is a table of labels with one row per item and rater, updated in place: when a rater edits an answer, the row is overwritten; when QA rejects a label, a status column flips. This is simple and it fails in three ways. History is lost, so nobody can say what the data looked like when a reward model was trained on it. Bugs are permanent, because a faulty conversion that was written into the row cannot be undone. And changing the format of a label means migrating every existing row in place, which is risky and often skipped.
Events and records. The alternative separates two things. An event is an immutable fact: "rater u1 submitted choice A with strength 4 for assignment a1 at 10:07". It carries an envelope (event id, event type, schema version, campaign, assignment, item, pseudonymous rater id, time) and a payload whose shape depends on the type. Events are appended to a log and never changed; an edit is a new submission event, and a mistaken label is cancelled by a retraction event. A record is derived: a fold reads all events for an assignment in time order and computes its current state (the latest submission, the QA verdict, whether it was retracted, and which events contributed). This is the event-sourcing pattern described by Fowler (2005): capture every change as an event so that state can be rebuilt, queried as of any past time, or recomputed after a bug fix.
Schema evolution. Interfaces change. A pairwise interface may add a tie option and a strength scale; a rubric interface may add partial credit. Each change creates a new schema version for that event type. Old events keep the version they were written with. A schema registry holds, per event type, the validator for every version and an upcaster between consecutive versions: a small function that converts a version-1 payload to version 2 (for example, setting strength to "unknown" for old pairwise events). Readers ask the registry for the latest shape; the stored bytes stay as written. An event that fails validation, or claims a version the reader does not know, goes to a quarantine area with the reason, rather than being dropped or guessed at. The cost is that every schema change needs an upcaster and a test, and that readers must handle all historical versions.
Adding a new feedback type. A new type is a new set of event types plus their validators, a transform, and an interface that emits them. The order matters: register the schema first so that the first event ever written is validated; build the transform and its tests against fixture events; only then ship the interface. Doing it in the opposite order produces events that nothing can read.
rubric.authored carries the prompt id, a rubric id and a list of items, each with an item id, text, an integer weight and a kind (essential, important, optional, or pitfall, the last for things a response must not do, with negative weight). rubric.scored carries the rubric id, a hash of the exact rubric the grader saw, the response id and a met/not-met decision per item. The hash ties every score to a specific rubric version, so editing a rubric after grading cannot silently re-label old scores. Volumes: 3,000 authored events, 12,000 scored events, 120,000 item judgments.Compared with the mutable table. Events cost more storage (every edit is kept), require a fold step, and make "the current label" a computed value rather than a lookup. In return they give audit history, reprocessing after bugs, and safe schema change. The mental model: the event log is the ledger of transactions, and records are account balances. Balances are convenient, but when they look wrong you recompute them from the ledger.
What you would actually do. Default to an append-only event log per campaign with a typed envelope, versioned payloads, a registry that validates on write and upcasts on read, and records as a rebuildable view. Deviate (store mutable records only) for throwaway pilots whose data will never be trained on.
The data model has four design decisions with measurable consequences: event granularity, identity, time, and compatibility policy.
Granularity and volume. Let \(A\) be assignments, \(e\) the mean events per assignment and \(s\) the mean event size. Raw log size is \(A \cdot e \cdot s\). Large texts (responses, transcripts, corrections) should not live inside events: store them once in a blob store keyed by the SHA-256 of their bytes and put only the hash in the payload. This makes events small, makes identical responses deduplicate automatically, and makes "which exact response did the rater see" a hash comparison.
Identity. Four identifiers matter. Item ids name the thing judged (prompt plus responses). Response ids should be content hashes, so two campaigns that show the same text agree on its id. Assignment ids name one rater-item pairing and are the fold key. Rater ids must be pseudonymous: the mapping from rater id to a person's name, email and payment details lives in a separate, access-controlled store, so the training pipeline never handles direct identifiers and a deletion request can be honoured by deleting the mapping plus the rater's events.
Time. Each event has an occurrence time from the client and an ingest time from the server. Folds order by occurrence time with the event id as a tie-breaker, which makes the result independent of arrival order. A snapshot is cut at an ingest-time watermark: "all events ingested before 02:00", so late events land in the next snapshot instead of mutating a published one.
Compatibility policy. Schema registries for streaming systems name the possible rules. In Confluent Schema Registry, for example, BACKWARD means consumers on the new schema can read data written with the previous one; FORWARD means consumers on the previous schema can read data written with the new one; FULL means both; the TRANSITIVE variants extend the check to all earlier versions rather than only the last; BACKWARD is the default; and adding a field with a default is compatible in all three modes (Confluent documentation). The same documentation gives the upgrade order: consumers first under BACKWARD, producers first under FORWARD, either order under FULL.
| Decision | Options | Recommended default for feedback events | Why |
|---|---|---|---|
| Where old versions are handled | Migrate stored data on write; upcast on read | Upcast on read | Raw bytes stay as the interface wrote them; the upcaster is code with tests and can be fixed |
| Reader guarantee | BACKWARD; BACKWARD_TRANSITIVE | Transitive: readers handle every historical version | Training reads years-old campaigns, not only the last version |
| Unknown future version | Ignore unknown fields; reject | Reject to quarantine (fail closed) | A changed meaning in a known field is invisible to "ignore unknown fields" |
| Semantic change of a field | Reuse field; new field or new version | New version with an explicit upcaster | A boolean that becomes a three-valued string must not be cast |
| Upgrade order | Producer first; consumer first | Registry and readers first, then interface | The first event ever written is then readable |
Cost of quarantine. If a producer emits bad events at rate \(r\) per hour and detection takes \(T\) hours, then \(rT\) events need repair. With immutable raw events, repair is a replay (compute minutes); without them, it is re-collection at the human cost per label. The detection time \(T\) is therefore the main lever, which is why validation belongs at ingest, not in a nightly job.
What you would actually do. Put large texts in a content-addressed store, keep events small, fold by occurrence time and snapshot by ingest watermark, require transitive reader compatibility with fail-closed handling of unknown versions, and validate at ingest so that \(T\) is minutes. Deviate from fail-closed only for purely additive optional fields that no transform reads.
The data model is three pieces of code: an immutable event type, a registry that validates and upcasts, and a fold. The event is a frozen dataclass; its content hash is SHA-256 over canonical JSON (sorted keys, no whitespace), so the same event always hashes the same way.
@dataclass(frozen=True)
class FeedbackEvent:
"""One immutable fact emitted by an interface or a service. Never updated in place:
a correction is a new event that supersedes or retracts an earlier one."""
event_id: str # globally unique, time-ordered (e.g. UUIDv7)
event_type: str # "pairwise.submitted", "rubric.scored", "label.retracted", ...
schema_version: int # version of the payload schema for this event_type
campaign_id: str
assignment_id: str # one rater x one item
item_id: str
rater_id: str # pseudonymous id; names and emails live in a separate store
occurred_at: str # ISO-8601 UTC, client clock; ingest time is stored separately
payload: dict[str, Any]
def content_hash(self) -> str:
return sha256_hex(asdict(self))
The registry stores, per event type, a validator for each version and an upcaster from each version to the next. register refuses out-of-order versions and refuses a new version without an upcaster, which turns "remember to write a migration" into an error at startup. read validates at the written version, upcasts step by step, then validates again at the latest version; anything else raises SchemaError.
Validator = Callable[[dict], list] # payload -> list of error strings (empty = valid)
Upcaster = Callable[[dict], dict] # payload at version v -> payload at version v+1
class SchemaRegistry:
"""Per event_type: an ordered list of payload versions, a validator for each,
and an upcaster between consecutive versions. Readers always see the latest version."""
def __init__(self) -> None:
self.latest: dict[str, int] = {}
self._validators: dict[tuple[str, int], Validator] = {}
self._upcasters: dict[tuple[str, int], Upcaster] = {}
def register(self, event_type: str, version: int, validator: Validator,
upcaster_from_prev: Upcaster | None = None) -> None:
have = self.latest.get(event_type, 0)
if version != have + 1:
raise ValueError(f"{event_type}: register versions in order (have v{have}, got v{version})")
if version > 1 and upcaster_from_prev is None:
raise ValueError(f"{event_type} v{version}: an upcaster from v{version - 1} is required")
self.latest[event_type] = version
self._validators[(event_type, version)] = validator
if upcaster_from_prev is not None:
self._upcasters[(event_type, version - 1)] = upcaster_from_prev
def read(self, ev: FeedbackEvent) -> FeedbackEvent:
"""Validate the event at the version it was written, then upcast it to the latest
version and validate again. The stored raw event is never modified."""
if ev.event_type not in self.latest:
raise SchemaError(ev.event_id, [f"unknown event_type {ev.event_type}"])
target, v = self.latest[ev.event_type], ev.schema_version
if not 1 <= v <= target:
raise SchemaError(ev.event_id, [f"unknown version v{v} (reader knows up to v{target})"])
errors = self._validators[(ev.event_type, v)](ev.payload)
if errors:
raise SchemaError(ev.event_id, errors)
payload = dict(ev.payload)
while v < target:
payload = self._upcasters[(ev.event_type, v)](payload)
v += 1
errors = self._validators[(ev.event_type, v)](payload)
if errors:
raise SchemaError(ev.event_id, errors)
return replace(ev, payload=payload, schema_version=v)
Validators return a list of error strings rather than raising, so a quarantine entry can carry every problem at once. The pairwise schema shows a typical evolution: version 2 added ties and a 1-to-4 strength scale; the upcaster maps old preferred to choice and sets strength to None, meaning "not collected", which is different from "weak".
def v_pairwise_v1(p: dict) -> list:
e = [f"missing {k}" for k in ("response_a", "response_b", "preferred") if k not in p]
if not e and p["preferred"] not in ("A", "B"):
e.append("preferred must be A or B")
return e
def v_pairwise_v2(p: dict) -> list:
e = [f"missing {k}" for k in ("response_a", "response_b", "choice", "strength") if k not in p]
if e:
return e
if p["choice"] not in ("A", "B", "tie"):
e.append("choice must be A, B or tie")
if p["strength"] is not None and p["strength"] not in (1, 2, 3, 4):
e.append("strength must be 1..4 or null")
if p["choice"] == "tie" and p["strength"] not in (None, 1):
e.append("a tie has no strength above 1")
return e
def up_pairwise_1_to_2(p: dict) -> dict:
# v2 added ties and a 4-point strength. v1 had neither: strength is unknown, not 0.
q = {k: v for k, v in p.items() if k != "preferred"}
q["choice"], q["strength"] = p["preferred"], None
return q
Adding W3 means registering two new event types. The authored-rubric validator enforces the rules that downstream reward computation relies on: 1 to 20 items, unique ids, nonzero integer weights in [-10, 10], pitfalls and only pitfalls negative, at least one positive item. The scored-event validator is strict about types; the reason appears in the Operate block.
RUBRIC_KINDS = ("essential", "important", "optional", "pitfall")
def v_rubric_authored_v1(p: dict) -> list:
e = [f"missing {k}" for k in ("prompt_id", "rubric_id", "items") if k not in p]
if e:
return e
if not 1 <= len(p["items"]) <= 20:
e.append("rubric needs 1..20 items")
ids = [it.get("item_id") for it in p["items"]]
if len(set(ids)) != len(ids):
e.append("duplicate item_id")
for it in p["items"]:
w = it.get("weight")
if not isinstance(w, int) or isinstance(w, bool) or not (-10 <= w <= 10) or w == 0:
e.append(f"{it.get('item_id')}: weight must be a nonzero int in [-10, 10]")
if it.get("kind") not in RUBRIC_KINDS:
e.append(f"{it.get('item_id')}: kind must be one of {RUBRIC_KINDS}")
if (it.get("kind") == "pitfall") != (isinstance(w, int) and w < 0):
e.append(f"{it.get('item_id')}: pitfalls and only pitfalls carry negative weight")
if not str(it.get("text", "")).strip():
e.append(f"{it.get('item_id')}: empty text")
if not any(isinstance(it.get("weight"), int) and it["weight"] > 0 for it in p["items"]):
e.append("rubric needs at least one positive-weight item")
return e
def v_rubric_scored_v1(p: dict) -> list:
e = [f"missing {k}" for k in ("rubric_id", "rubric_hash", "response_id", "scores") if k not in p]
if e:
return e
for item_id, s in p["scores"].items():
if not isinstance(s, bool): # strict: "not_met" is a truthy string
e.append(f"{item_id}: score must be a boolean in v1, got {type(s).__name__}")
return e
def v_rubric_scored_v2(p: dict) -> list:
e = [f"missing {k}" for k in ("rubric_id", "rubric_hash", "response_id", "scores") if k not in p]
if e:
return e
for item_id, s in p["scores"].items():
if s not in ("met", "partial", "not_met"):
e.append(f"{item_id}: score must be met|partial|not_met, got {s!r}")
return e
def up_rubric_scored_1_to_2(p: dict) -> dict:
q = dict(p)
q["scores"] = {k: ("met" if v else "not_met") for k, v in p["scores"].items()}
return q
The fold sorts by occurrence time and event id, reads each event through the registry, quarantines failures, applies "latest submission wins", records QA verdicts and applies retractions after the pass. Because ordering is total, any permutation of the same events yields the same records (one of the tests checks this by folding the reversed log).
LABEL_TYPES = ("pairwise.submitted", "correction.submitted", "rubric.scored")
def fold(events: list[FeedbackEvent], reg: SchemaRegistry):
"""Fold the raw event log into one current record per assignment.
Returns (records, quarantine). Deterministic: same events in any order -> same records."""
records: dict[str, dict] = {}
quarantine: list[tuple[str, list]] = []
retracted: set[str] = set()
ordered = sorted(events, key=lambda e: (e.occurred_at, e.event_id))
for raw in ordered:
try:
ev = reg.read(raw)
except SchemaError as err:
quarantine.append((err.event_id, err.errors))
continue
rec = records.setdefault(ev.assignment_id, {
"assignment_id": ev.assignment_id, "item_id": ev.item_id, "rater_id": ev.rater_id,
"campaign_id": ev.campaign_id, "label_type": None, "label": None,
"label_event_id": None, "qa": None, "source_event_ids": []})
rec["source_event_ids"].append(ev.event_id)
if ev.event_type in LABEL_TYPES: # latest submission wins
rec.update(label_type=ev.event_type, label=ev.payload, label_event_id=ev.event_id)
elif ev.event_type == "qa.verdict":
rec["qa"] = ev.payload["verdict"]
elif ev.event_type == "label.retracted":
retracted.add(ev.payload["retracts"])
for rec in records.values():
if rec["label_event_id"] in retracted:
rec.update(label=None, label_type=None)
return records, quarantine
The W1 fixture exercises each rule: a three-rater overlap item with randomised display order, a tie, a gold item, an event from an old version-1 client, a QA rejection, an edit, and a malformed event.
def w1_fixture():
items = {f"i{k}": {"prompt": f"Write a function #{k}", "responses": {f"r{k}a": f"code {k}a", f"r{k}b": f"code {k}b"}}
for k in range(1, 6)}
E = []
# i1: overlap item, 3 raters, display order randomised per rater; 2 prefer r1a, 1 prefers r1b
E.append(ev("pairwise.submitted", "a1", "i1", "u1", {"response_a": "r1a", "response_b": "r1b", "choice": "A", "strength": 3}, v=2))
E.append(ev("pairwise.submitted", "a2", "i1", "u2", {"response_a": "r1b", "response_b": "r1a", "choice": "B", "strength": 2}, v=2))
E.append(ev("pairwise.submitted", "a3", "i1", "u3", {"response_a": "r1a", "response_b": "r1b", "choice": "B", "strength": 1}, v=2))
# i2: single label, tie -> no pair
E.append(ev("pairwise.submitted", "a4", "i2", "u1", {"response_a": "r2a", "response_b": "r2b", "choice": "tie", "strength": None}, v=2))
# i3: gold item -> excluded from training
E.append(ev("pairwise.submitted", "a5", "i3", "u2", {"response_a": "r3a", "response_b": "r3b", "choice": "A", "strength": 4}, v=2))
# i4: written by an old v1 client (no ties, no strength) -> upcast
E.append(ev("pairwise.submitted", "a6", "i4", "u3", {"response_a": "r4b", "response_b": "r4a", "preferred": "A"}, v=1))
# i5: rejected by QA
E.append(ev("pairwise.submitted", "a7", "i5", "u1", {"response_a": "r5a", "response_b": "r5b", "choice": "A", "strength": 4}, v=2))
# a1 is edited: rater resubmits with a stronger preference (latest wins)
E.append(ev("pairwise.submitted", "a1", "i1", "u1", {"response_a": "r1a", "response_b": "r1b", "choice": "A", "strength": 4}, v=2))
for a, item in [("a1", "i1"), ("a2", "i1"), ("a3", "i1"), ("a4", "i2"), ("a5", "i3"), ("a6", "i4")]:
E.append(ev("qa.verdict", a, item, "qa", {"verdict": "accepted"}))
E.append(ev("qa.verdict", "a7", "i5", "qa", {"verdict": "rejected"}))
# a malformed event from a buggy client -> quarantine, never silently dropped
E.append(ev("pairwise.submitted", "a8", "i5", "u2", {"response_a": "r5a", "response_b": "r5b", "choice": "left", "strength": 2}, v=2))
return items, E
def test_w1_events_to_rm_pairs():
items, E = w1_fixture()
recs, quarantine = fold(E, default_registry())
assert [q[0] for q in quarantine] == [E[-1].event_id]
assert recs["a1"]["label"]["strength"] == 4 # resubmission won
assert recs["a6"]["label"] == {"response_a": "r4b", "response_b": "r4a", "choice": "A", "strength": None}
rows, ledger = to_rm_pairs(recs, items, gold_item_ids={"i3"})
by_item = {r["group_id"]: r for r in rows}
assert set(by_item) == {"i1", "i4"}
assert (by_item["i1"]["chosen"], by_item["i1"]["rejected"]) == ("code 1a", "code 1b")
assert by_item["i1"]["weight"] == pytest.approx(2 / 3, abs=1e-4)
assert by_item["i4"]["chosen"] == "code 4b" # slot A held r4b
# completeness: every assignment is used, dropped with a reason, or quarantined
assert sum(ledger.values()) + len(quarantine) == 8
assert ledger == {"used": 4, "tie_or_no_majority": 1, "gold_item": 1, "qa_not_accepted": 1}
Debugging tips. If records differ between two runs, check for a missing tie-breaker in the sort or for a transform that reads wall-clock time. If a QA verdict applies to the wrong submission after an edit, make verdicts reference the label_event_id they judged (the sketch keeps the latest verdict per assignment for brevity). If the quarantine is empty for a long time, test that it works by sending a deliberately malformed event through ingest in a staging environment.
Problem. A schema break is a change in what a field means or how it is encoded that reaches the pipeline without a matching schema version. It is the most damaging failure in a feedback pipeline because it usually produces data that looks valid: types still match, row counts are normal, and the error shows up only as shifted distributions or a downstream metric that moves for no visible reason.
Why it matters. Human labels are expensive and slow to replace. A break that corrupts a day of expert work either costs that day again or, worse, ships into a reward signal. The defence has three layers: validate on write so bad events never become records, monitor distributions so semantically wrong but well-typed data is noticed, and keep raw events so the repair is a replay.
Setup. W3 graders score responses against rubrics; the target is human–AI item-level agreement of at least 0.8, checked by a calibration job before any rubric-reward configuration is released to the RL reward service. In this scenario the ingest path does not yet validate payloads; validation runs only as a nightly dataset contract that checks field presence and container types.
Trigger. On day 1 at 09:00 an interface release adds partial credit. Item scores change from booleans to the strings "met", "partial" and "not_met", but the events still declare schema version 1. The record-building code converts scores with a truthiness check, so every non-empty string, including "not_met", becomes true.
Symptom. During the 8-hour day-1 shift, graders score 2,400 responses (24,000 item judgments); day-2 grading starts after the alert below and is paused. The nightly snapshot at 02:00 passes its contract because scores is still a mapping. At 06:00 the calibration job reports human–AI agreement of 0.61, below the 0.80 gate, and blocks the reward configuration release. Two explanations are on the table: the AI grader regressed, or the human data changed.
Measurements that separate causes. (1) Item met rate by interface build: 0.58 on the previous build over the trailing week, 0.96 on the new build. (2) AI met rate on the same responses: unchanged at 0.57. (3) Agreement restricted to events from the previous build: 0.83. The grader is stable and the human labels from one build are not, which points at the producer. Reading raw events from the new build shows string scores under version 1.
Remedy. (1) Roll back the interface (14:00). (2) Mark the 02:00 snapshot revoked in the lineage store so that nothing downstream picks it up. (3) Register rubric.scored version 2 with a three-valued validator and an upcaster from version 1 that maps true to "met" and false to "not_met". (4) Add a versioned ingest correction rule: events from interface build 2.3 that declare version 1 are read as version 2. The raw bytes are untouched; the rule is code, reviewed and recorded in the manifest of every snapshot it affects. (5) Decide what "partial" means for the reward: the research owner chooses to treat it as not met for the binary reward and to keep it for analysis; 7% of the affected judgments were partial in this scenario. (6) Replay the fold and rebuild the snapshot (18:00). Agreement on the rebuilt calibration set is 0.82, and the configuration is released.
Cost and trade-off. Replay compute is negligible. Re-grading would have cost 2,400 × 2 minutes ≈ 80 grader-hours. The real cost was time: 21 hours until the calibration gate caught the problem, 29 hours until the producer was rolled back, and a delayed reward configuration release. Validating on write adds a registry lookup and a validator call per event, microseconds at this volume.
Validation. After ingest validation was enabled, the same build was replayed in staging: every one of its version-1 events with string scores was quarantined within one ingest batch, and the quarantine-rate page fired after 15 minutes. If a future break of this kind is first noticed by the calibration gate rather than by the quarantine page, the ingest validators are too loose.
Runbook: schema break.
- Confirm: quarantine rate by event type and producer build; compare field distributions by build. If one build differs and others do not, treat it as a schema break.
- Contain: stop or roll back the producer; revoke any snapshot built from the affected window; pause consumers that auto-ingest new snapshots.
- Decide semantics with the data owner: for each new value, its meaning for every downstream transform. Do not proceed on a guess.
- Repair by code: new schema version, upcaster, ingest correction rule keyed by producer build and time range; tests that replay real quarantined events.
- Replay and rebuild; verify completeness (accepted equals used plus dropped plus quarantined) and rerun the gate that caught the problem.
- Prevent: add the producer's schema to the compatibility check in its CI so that a type change without a version bump fails the build; canary new interface builds on a small share of assignments with ingest validation on.
SLOs for the data model. Time from first invalid event to page: under 15 minutes. Quarantined events resolved (replayed or explicitly discarded with a reason) within 3 working days. Schema changes merged without a registered upcaster and a replay test: zero, enforced by CI. These keep the detection time short, which the Design block showed is the variable that sets the cost of every break.
Converting Feedback into Training Examples
A transform is a function that takes folded feedback records (plus the prompts and responses they refer to) and produces rows in the exact format a training consumer expects. It should be pure: the same records, code and configuration always give the same rows, with no hidden inputs such as the current time or a random seed. There is one transform per pair of feedback type and consumer, because the same judgment can feed several consumers in different shapes.
Why a separate stage. Early RLHF projects often exported labels with a one-off script per experiment. That works once and then fails quietly: two researchers convert the same labels differently, nobody can say which conversion a model saw, and a fix in one script never reaches the others. A transform stage makes the conversion a reviewed, versioned, tested piece of code whose version is recorded with every dataset it produces.
Preference feedback to reward-model pairs. A reward model is trained on pairs of responses to the same prompt, labelled with which one is better. The transform maps each vote from the display slot the rater saw (left or right, A or B) to the underlying response id, because interfaces randomise order to counter position bias. Where several raters judged the same item, it aggregates their votes: majority wins, and items with no majority are dropped or kept as ties for a tie-aware loss. Two refinements come from published practice. InstructGPT had labellers rank 4 to 9 responses per prompt, which yields every pairwise comparison among them, and found that shuffling those correlated comparisons into one dataset made the reward model overfit, so all comparisons from one prompt were treated as one batch element (Ouyang et al., 2022). Llama 2 collected a degree of preference (significantly better, better, slightly better, negligibly better or unsure) and added a margin to the ranking loss that is larger for clearly distinct pairs (Touvron et al., 2023). A transform therefore emits a group id per prompt and a margin per pair, not just chosen and rejected text.
Corrections to supervised examples. When an expert reviewing an agent transcript marks the first failing step and writes a corrected continuation, the transform builds a correction example: the transcript up to just before the failing step becomes the prompt, and the expert's continuation becomes the target. Training loss applies only to the target, so the model learns what to do at the point where it went wrong.
Step judgments to process labels. A process reward model scores each intermediate step rather than only the final answer. Its training data is a list of steps with a label per step. In PRM800K, labellers marked steps positive, negative or neutral and deliberately supervised only up to the first incorrect step; a solution's score is then the probability that every step is correct, the product of per-step probabilities (Lightman et al., 2023). The transform therefore labels steps before the failing one as correct, the failing step as incorrect, and leaves later steps unlabelled, because once a trajectory has gone wrong the correctness of what follows is ill-defined.
Rubrics to reward definitions. Rubric feedback becomes a reward function rather than a set of rows. Rubrics as Rewards attaches 7 to 20 weighted criteria to each prompt, has a judge model decide whether each is met, and normalises the weighted sum of met criteria by total weight (Gunjal et al., 2025); HealthBench uses nonzero criteria worth -10 to +10 points and divides the points earned by the maximum possible score, the sum of positive points; a single example can score below zero, and the benchmark clips the mean over examples to [0, 1] (Arora et al., 2025). An RL reward needs a bounded value per response, so the transform in this chapter clips each response's score instead. The transform exports each rubric as a package with a content hash, and exports human item scores as a calibration set that checks whether the AI grader applies the rubric the way people do.
What you would actually do. Write one pure transform per (feedback type, consumer), emit the consumer's native format, carry group ids and source assignment ids on every row, and return a drop ledger. Deviate only by adding consumers, never by letting a consumer re-derive labels from raw events on its own.
Each transform is a funnel with explicit drop reasons, and each design choice inside it moves rows between "used" and "dropped".
Overlap aggregation. Suppose \(n = 3\) raters judge an item with a binary choice and ignore ties for the moment. Each item is either unanimous or a 2–1 split. If \(u\) is the unanimous share, the pairwise agreement (the probability that two raters on the same item agree) is \(\bar{a} = u \cdot 1 + (1-u)\cdot\tfrac{1}{3}\), because in a 2–1 split exactly one of the three rater pairs agrees. Solving gives \(u = (\bar{a} - \tfrac{1}{3}) / \tfrac{2}{3}\).
Ties. A tie carries information ("these are equally good") that a plain Bradley–Terry loss, \(-\log \sigma(r_c - r_r)\) with \(r_c, r_r\) the reward of chosen and rejected responses, cannot use. Options: drop ties (simplest), keep them for a tie-aware loss, or keep them as a calibration set. In W1, 8% ties on 18,400 useful comparisons is about 1,470 rows.
Rankings and grouping. A ranking of \(K\) responses yields \(\binom{K}{2}\) pairs: 6 for \(K=4\), 36 for \(K=9\). These pairs share responses and a rater, so they are not independent. Two consequences: keep all pairs from a prompt in the same split (train, validation or test), and batch them together as InstructGPT did, which the group id enables. Splitting by row instead of by prompt leaks near-identical pairs into validation and inflates measured accuracy.
Correction examples. For a transcript of \(L\) steps with first failing step \(k\), the prompt holds steps \(1..k-1\) and the target is the correction. Only target tokens carry loss.
Reconciling double review. When two experts mark different failing steps \(k_1, k_2\), the transform can take the earliest, the latest, or send the item to adjudication. Taking the earliest never labels a bad step as good, at the price of sometimes labelling a good step as bad. A tolerance \(\tau\) decides when to adjudicate instead.
Rubric rewards. With item weights \(w_i\) (negative for pitfalls) and met indicators \(m_i \in \{0,1\}\), the reward is \(R = \mathrm{clip}\big(\sum_i w_i m_i \,/\, \sum_{i: w_i>0} w_i,\ 0,\ 1\big)\). For a four-item rubric with weights 5, 4, 2 and a pitfall of −6, meeting the first two gives \(R = 9/11 \approx 0.82\); meeting the first item and the pitfall gives \(R = \max(0, -1/11) = 0\).
Calibration sample size. Item-level agreement \(p\) between human and AI grader, estimated from \(N\) judgments, has standard error \(\sqrt{p(1-p)/N}\) if judgments were independent. They are clustered by rubric and response, so this is a lower bound.
| Choice | Default | Deviate when |
|---|---|---|
| Overlap aggregation | Majority, weight = vote share | Rater reliability varies widely: use a reliability model (Dawid–Skene style) to weight votes |
| Ties | Exclude from pairs, keep as a separate set | The consumer has a tie-aware loss |
| Split unit | Prompt (group id) | Never split by row |
| First-failing-step disagreement | Earliest within ±2; adjudicate beyond | A consumer needs high precision on negatives: adjudicate all disagreements |
| Rubric normalisation | Divide by positive points, clip to [0, 1] | Pitfall severity must not be clipped away: report the unclipped score alongside |
What you would actually do. Keep split votes with reduced weight, keep ties out of strict pairs but stored, group by prompt everywhere, reconcile failing steps conservatively, and size calibration gates for slices, not single rubrics.
Transforms read folded records (the output of the fold in the data-model section: one record per assignment with its current label, QA verdict and source events) and return (rows, ledger). The output formats match common trainer conventions: Hugging Face TRL documents a preference type with prompt, chosen and rejected columns used by its reward and DPO trainers (TRL documentation), and its experimental PRM trainer expects stepwise supervision with prompt, completions and labels (TRL PRM trainer). Extra columns (margin, weight, group id, source assignments) are ignored by trainers that do not use them and are essential for audits.
RM pairs. The function filters records (no label, gold item, not accepted), collects votes per item, maps each vote from display slot to response id, finds the majority, and emits one aggregated row per item. Every input lands in exactly one ledger bucket.
# Illustrative margin per strength level (4 = "significantly better" ... 1 = "negligibly better").
# A margin-aware loss uses it; a plain Bradley-Terry loss ignores it.
MARGIN = {4: 1.0, 3: 0.67, 2: 0.33, 1: 0.0, None: 0.0}
def to_rm_pairs(records: dict, items: dict, gold_item_ids: set, min_agreement: float = 0.5):
"""records: assignment_id -> folded record (label_type 'pairwise.submitted').
items: item_id -> {"prompt": str, "responses": {response_id: text}}.
Returns (rows, ledger). Every input assignment is either used or counted in the ledger."""
ledger: Counter = Counter()
votes: dict[str, list] = defaultdict(list)
for rec in records.values():
if rec["label_type"] != "pairwise.submitted" or rec["label"] is None:
ledger["no_label_or_retracted"] += 1
elif rec["item_id"] in gold_item_ids:
ledger["gold_item"] += 1 # gold stays unseen by training
elif rec["qa"] != "accepted":
ledger["qa_not_accepted"] += 1
else:
votes[rec["item_id"]].append(rec)
rows = []
for item_id, recs in sorted(votes.items()):
a, b = recs[0]["label"]["response_a"], recs[0]["label"]["response_b"]
# Interfaces randomise left/right; map each vote from display slot to response id.
tally: Counter = Counter()
for r in recs:
lab = r["label"]
if lab["choice"] == "tie":
tally["tie"] += 1
else:
tally[lab["response_a"] if lab["choice"] == "A" else lab["response_b"]] += 1
n = len(recs)
ranked = [(tally[a], a, b), (tally[b], b, a)]
ranked.sort(reverse=True)
top_votes, chosen, rejected = ranked[0]
if top_votes == ranked[1][0]:
ledger["tie_or_no_majority"] += n
continue
agreement = top_votes / n
if agreement <= min_agreement:
ledger["weak_majority"] += n
continue
winners = [r for r in recs if r["label"]["choice"] != "tie" and
(r["label"]["response_a"] if r["label"]["choice"] == "A" else r["label"]["response_b"]) == chosen]
strengths = [r["label"]["strength"] for r in winners if r["label"]["strength"] is not None]
strength = sorted(strengths)[len(strengths) // 2] if strengths else None # median-ish
responses = items[item_id]["responses"]
rows.append({
"prompt": items[item_id]["prompt"],
"chosen": responses[chosen], "rejected": responses[rejected],
"margin": MARGIN[strength], "weight": round(agreement, 4),
"group_id": item_id, # batch all pairs of a prompt together
"source_assignments": sorted(r["assignment_id"] for r in recs),
})
ledger["used"] += n
return rows, ledger
The W1 test shown with the data model checks the important properties: the three-rater item resolves to the majority response even though one rater saw the responses in the opposite order; the version-1 event is mapped through its own display order; gold items never reach training; and the ledger plus quarantine count equals the number of assignments.
Transcript transforms. Reconciliation, correction examples and process labels are each a few lines, which is the point: the policy (earliest step within a tolerance, supervise to the first error) is explicit and testable.
def reconcile_first_failing_step(ks: list, tolerance: int = 2):
"""Double review: experts may disagree on the first failing step.
Within tolerance -> take the EARLIEST step (never label a bad step as good).
Beyond tolerance -> None (send to adjudication)."""
if max(ks) - min(ks) > tolerance:
return None
return min(ks)
def to_correction_sft(task: str, steps: list, k: int, continuation: str) -> dict:
"""Correction example: the trajectory up to (not including) failing step k, then the expert's
corrected continuation as the target. Steps are 1-based; steps[k-1] is the failing step."""
return {"prompt": [{"role": "user", "content": task}] + steps[: k - 1],
"completion": [{"role": "assistant", "content": continuation}]}
def to_process_labels(task: str, steps: list, k: int) -> dict:
"""Stepwise supervision row (prompt, completions, labels): steps before k are correct,
step k is the first error, later steps are not labelled (supervise only to the first error)."""
return {"prompt": task,
"completions": [s["content"] for s in steps[:k]],
"labels": [True] * (k - 1) + [False]}
def test_w2_transcript_transforms():
steps = [{"role": "assistant", "content": f"step {i}"} for i in range(1, 61)] # 60 steps
k = reconcile_first_failing_step([31, 29]) # two experts, within +-2
assert k == 29 # earliest wins
assert reconcile_first_failing_step([12, 31]) is None # adjudicate
sft = to_correction_sft("Fix the failing CI job", steps, k, "Re-run the tests with ...")
assert len(sft["prompt"]) == 1 + 28 and sft["prompt"][-1]["content"] == "step 28"
pl = to_process_labels("Fix the failing CI job", steps, k)
assert len(pl["completions"]) == len(pl["labels"]) == 29
assert pl["labels"][-1] is False and all(pl["labels"][:-1])
Rubric packages and rewards. The rubric hash covers exactly what a grader sees (item ids, texts, weights, kinds), sorted by item id so that reordering does not change it and any edit does. The reward service stores packages by hash and refuses a score whose hash it does not hold. item_agreement returns raw agreement and Cohen's kappa, which corrects for agreement expected by chance from each side's met rate.
def rubric_hash(rubric: dict) -> str:
"""Hash over what the grader sees: item ids, texts, weights, kinds (order-independent)."""
items = sorted(({k: it[k] for k in ("item_id", "text", "weight", "kind")} for it in rubric["items"]),
key=lambda it: it["item_id"])
return sha256_hex({"rubric_id": rubric["rubric_id"], "items": items})
def rubric_reward(rubric: dict, met: dict) -> float:
"""Score in [0, 1]: points of met items over total positive points. A met pitfall
(negative weight) subtracts. Missing scores count as not met."""
pos = sum(it["weight"] for it in rubric["items"] if it["weight"] > 0)
got = sum(it["weight"] for it in rubric["items"] if met.get(it["item_id"], False))
return min(1.0, max(0.0, got / pos))
def to_rubric_package(rubric: dict, prompt: str) -> dict:
"""Export unit for the RL reward service: the rubric plus its content hash.
The service refuses scores whose rubric_hash it does not hold."""
return {"prompt_id": rubric["prompt_id"], "prompt": prompt, "rubric_id": rubric["rubric_id"],
"rubric_hash": rubric_hash(rubric),
"items": sorted(rubric["items"], key=lambda it: it["item_id"])}
def item_agreement(human: list, ai: list):
"""Item-level agreement and Cohen's kappa between human and AI met/not-met decisions."""
assert len(human) == len(ai) and human
n = len(human)
p_o = sum(h == a for h, a in zip(human, ai)) / n
ph, pa = sum(human) / n, sum(ai) / n
p_e = ph * pa + (1 - ph) * (1 - pa)
kappa = (p_o - p_e) / (1 - p_e) if p_e < 1 else 1.0
return round(p_o, 4), round(kappa, 4)
RUBRIC = {"prompt_id": "p17", "rubric_id": "rb17", "items": [
{"item_id": "c1", "text": "States the governing law clause correctly", "weight": 5, "kind": "essential"},
{"item_id": "c2", "text": "Defines Confidential Information with carve-outs", "weight": 4, "kind": "important"},
{"item_id": "c3", "text": "Uses defined terms consistently", "weight": 2, "kind": "optional"},
{"item_id": "c4", "text": "Invents a statute or case citation", "weight": -6, "kind": "pitfall"}]}
def test_w3_rubric_authoring_and_reward():
reg = default_registry()
e = ev("rubric.authored", "w3a1", "p17", "x1", RUBRIC)
assert reg.read(e).payload["rubric_id"] == "rb17"
bad = dict(RUBRIC, items=RUBRIC["items"] + [{"item_id": "c5", "text": "Cites a case", "weight": -2, "kind": "optional"}])
with pytest.raises(SchemaError):
reg.read(ev("rubric.authored", "w3a2", "p17", "x1", bad))
assert rubric_reward(RUBRIC, {"c1": True, "c2": True, "c3": False, "c4": False}) == pytest.approx(9 / 11)
assert rubric_reward(RUBRIC, {"c1": True, "c4": True}) == 0.0 # pitfall wipes it out, clipped
shuffled = dict(RUBRIC, items=list(reversed(RUBRIC["items"])))
assert rubric_hash(shuffled) == rubric_hash(RUBRIC) # order-independent
edited = dict(RUBRIC, items=[dict(RUBRIC["items"][0], weight=6)] + RUBRIC["items"][1:])
assert rubric_hash(edited) != rubric_hash(RUBRIC) # any edit -> new hash
assert to_rubric_package(RUBRIC, "Draft an NDA ...")["rubric_hash"] == rubric_hash(RUBRIC)
def test_w3_human_ai_agreement():
human = [1, 1, 0, 1, 0, 1, 1, 0, 1, 1]
ai = [1, 1, 0, 1, 1, 1, 1, 0, 1, 0]
p_o, kappa = item_agreement(human, ai)
assert p_o == 0.8 and 0.5 < kappa < 0.6 # 80% raw, kappa about 0.52
def test_w3_schema_break_is_quarantined_then_upcast():
reg = default_registry()
h = rubric_hash(RUBRIC)
good = ev("rubric.scored", "g1", "p17", "x2", {"rubric_id": "rb17", "rubric_hash": h, "response_id": "s1",
"scores": {"c1": True, "c2": False}})
broken = ev("rubric.scored", "g2", "p17", "x2", {"rubric_id": "rb17", "rubric_hash": h, "response_id": "s2",
"scores": {"c1": "met", "c2": "not_met"}}) # new UI, still says v1
recs, q = fold([good, broken], reg)
assert [x[0] for x in q] == [broken.event_id] # caught, not coerced to True
assert bool("not_met") is True # what a naive bool() cast would have done
reg.register("rubric.scored", 2, v_rubric_scored_v2, up_rubric_scored_1_to_2)
fixed = ev("rubric.scored", "g2", "p17", "x2", dict(broken.payload), v=2)
recs, q = fold([good, fixed], reg)
assert q == [] and recs["g1"]["label"]["scores"] == {"c1": "met", "c2": "not_met"}
Debugging tips. If reward-model validation accuracy is suspiciously high, check that splits are by group_id. If the chosen response's win rate in exported rows differs from the same statistic computed directly from raw events, the slot mapping is wrong. If kappa is much lower than raw agreement, one side is calling almost everything met, and raw agreement is mostly chance.
Problem. Transforms fail without errors. A wrong mapping or aggregation rule produces well-formed rows with the wrong meaning, and the first visible symptom is usually a worse model several days later. Production transforms therefore need checks that compare the output against an independent computation from raw events, and known-answer inputs that flow through the whole path.
Two tools. A two-path reconciliation computes one aggregate statistic twice, once from raw events with a few lines of independent code and once from the exported rows, and requires them to match. A sentinel item is a known-answer input injected into normal collection: for pairwise data, a pair in which one response is deliberately broken (it does not compile, or answers a different question). Sentinels differ from the gold items used to score raters: they are judged like any other item, flow through the transform, and are checked at the output. The SRE workbook recommends this "golden data" approach for pipeline correctness (Sodt et al., 2018).
Trigger. A refactor of the W1 pair transform maps choice A to "current checkpoint" and B to "candidate", an assumption that held for an early interface that showed responses in fixed order. The current interface randomises order per assignment, so for about half of all votes the chosen and rejected texts are swapped.
Symptom. The retrained reward model's accuracy on a fixed, separately curated held-out set falls from 0.68 to 0.59 (illustrative values). Candidate explanations: the new data is noisier, the training recipe changed, or the transform is wrong.
Measurements. (1) Sentinels: 200 sentinel items (1% of 20,000) in the batch. From raw events, raters picked the intact response 98% of the time; in exported rows, 51%. Raters were fine; the export was not. (2) Two-path check on candidate win rate: 0.56 from raw events, 0.50 in exported rows. A transform that preserves meaning must reproduce the raw statistic exactly, and 0.50 is what random swapping produces. (3) Split by display order: rows where the candidate was shown on the left are correct, rows where it was shown on the right are inverted.
Remedy. Revert the mapping to use response ids recorded in each event; bump the transform version; rebuild, which produces a new dataset id; mark the faulty dataset revoked; retrain the reward model from the rebuilt data. Add both checks as blocking gates on every future W1 export: sentinel accuracy in exported rows of at least 95%, and raw-versus-export candidate win rate equal to within 0.001.
Cost. The pipeline rebuild is minutes. The reward-model retrain and mix inclusion is the 3-day stage of the W1 request-to-mix path, spent twice. Sentinels cost 1% of collection, 200 comparisons or about \$800 at W1's \$4.12 per useful comparison, per batch.
Validation. After the fix, exported sentinel accuracy is 98% and the two-path candidate win rate matches to four decimals. Held-out accuracy returning to its earlier level supports the diagnosis; if it does not return, the transform was not the only cause, and the recipe change is next to examine.
Transform release checklist.
- Unit tests on fixtures covering every ledger reason, randomised display order, old schema versions and retractions.
- Golden replay: run the new version on a frozen sample of real raw events; diff the output against the previous version; every changed row must be explained by the change description.
- Two-path reconciliation for each consumer: candidate win rate (pairs), share of negative steps (process labels), mean item met rate (rubrics).
- Sentinel accuracy in the exported rows above threshold.
- Version bump recorded in the manifest; the old version stays available for rebuilding old snapshots.
Dashboard panels for transforms. Ledger shares per reason per batch (a jump in "tie_or_no_majority" or "qa_not_accepted" is a data or QA change, not a transform change); split-vote share; exported candidate win rate against the raw-event value; sentinel accuracy; for W2, the adjudication queue size; for W3, the human item met rate by rubric author. Each is cheap to compute because transforms already return ledgers.
Provenance, Versioning and Reproducibility of Datasets
Three related properties make a training dataset trustworthy after the fact. Provenance is the record of where each piece of data came from and how it was produced: which campaign, which raw events, which transform code and configuration, which filters. Versioning means every dataset that anyone trains on is an immutable, named version that never changes after publication. Reproducibility means that version can be rebuilt exactly from its recorded inputs. Together they let a team answer the questions that come up after training: what exactly did this reward model see, which runs used the labels of a rater who turned out to be cheating, and does the bug fixed today affect last month's model.
The earlier practice and its limit. Datasets often live as folders with names like prefs_final_v3_fixed, rewritten in place and described in a chat thread. Provenance decays quickly under such practice. A large audit of more than 1,800 text datasets found license information missing for over 70% of datasets on widely used hosting sites and license categorisation errors above 50% (Longpre et al., 2023). Inside a single organisation the same decay makes it impossible to remove bad data or to explain a change in a model.
The mechanism, end to end. (1) A transform writes its rows in a canonical byte form, split into shards. (2) Each shard is identified by its content hash, the SHA-256 digest of its bytes, so any change to any byte changes the hash. (3) A manifest lists the shard hashes and row counts, the parent datasets, the transform's code version and configuration hash, and the drop ledger. (4) The dataset's identifier is derived from the hash of the manifest body (excluding timestamps), so the same inputs and code always produce the same id and any difference produces a new one. (5) The manifest is registered as a node in a lineage graph with edges from its parents. (6) Consumers refer to datasets by id, and training runs record the ids they read, which closes the graph from raw events to models.
The vocabulary comes from W3C PROV-DM, which models provenance with entities (data), activities (processes that use and generate entities) and agents (who is responsible), linked by relations such as "was derived from" (W3C, 2013). The MLCommons Croissant format applies similar ideas to published ML datasets: it records a SHA-256 checksum per file, semantic version numbers, a flag for live datasets that keep changing, and PROV terms such as prov:wasDerivedFrom (MLCommons Croissant 1.1). Human-readable documentation of motivation, composition and collection process, as proposed in Datasheets for Datasets (Gebru et al., 2021), complements the machine-readable manifest; the manifest proves what is in the data, the datasheet explains why.
w1_rm_pairs@sha256:…, derived from a records snapshot records/w1@r7, which is derived from two daily batches of raw events. A mix rm_v14 combines it with a public preference dataset, and training run rm-14-0007 reads the mix. A held-out evaluation set is derived from the same records but is never part of a mix. Walking the graph downstream from a raw-event batch lists everything that must be rebuilt if that batch is corrected; walking upstream from the run lists everything needed to reproduce it.Compared with folders and naming conventions. Content addressing costs some storage (old versions are kept), a manifest-writing step and discipline in transforms (no hidden randomness or clock reads). In return, "is this the same data?" becomes a string comparison, and deletion, incident response and reproduction become graph queries rather than archaeology. Mental model: datasets are commits, manifests are commit objects, and the lineage graph is the history.
What you would actually do. Make every published dataset immutable and content-addressed, require a manifest with parents and transform version before publication, and make training runs log the dataset ids they read. Use human-friendly names and semantic versions as aliases that point to content ids, never as the identity itself.
The design choices are the hashing granularity, the identity scheme, the snapshot cadence and how much determinism to demand.
Hash granularity. Hashing per row gives fine-grained deduplication and per-row lineage but large manifests; hashing per dataset gives a single id but no way to tell which part changed. Hashing per shard with a manifest over shard hashes is the usual middle: the manifest is small (one entry per shard), the dataset id covers all bytes, and a verifier can locate a corrupted shard. With SHA-256 the probability of an accidental collision is negligible (birthday bound about \(2^{-128}\) for any realistic number of objects), so equal hashes can be treated as equal content.
Shard stability. If shards are formed by sorting all rows and cutting every \(S\) rows, a single inserted row shifts every later shard boundary, so a new snapshot shares almost no shards with the previous one. Assigning each row to shard \(\mathrm{hash}(\text{group id}) \bmod N\) keeps unchanged groups in unchanged shards, so an append of \(\Delta\) rows rewrites at most \(\min(N, \Delta)\) shards. The trade-off is uneven shard sizes.
Identity. Two identifiers serve different readers. A content id (name@sha256:…) is what training runs log and what the lineage graph stores. A human alias (w1_rm_pairs:1.3.0 or :latest) is a mutable pointer for people. Following the semantic-version convention that Croissant also adopts, a major version bump signals a change in meaning (a new transform rule), a minor bump new data, a patch bump a fix that does not change semantics.
Determinism budget. A rebuild reproduces the id only if every input is pinned: raw-event watermark, transform code commit, dependency lock, configuration and any external resource (an eval index for decontamination, a PII model version). Each unpinned input is a way for the id to drift. Practical rule: everything a transform reads is either a dataset id or part of the hashed transform record.
Deletion impact. If a fraction \(f\) of labels must be removed, every dataset downstream of those labels gets a new version, and every model trained on them is a candidate for retraining. The lineage graph turns "which models" into a query; the decision to retrain depends on \(f\) and on measured impact.
| Decision | Default | Deviate when |
|---|---|---|
| Hash unit | Shard (about 10,000 rows) plus manifest | Per-row lineage is required by policy: also store row hashes in the shard index |
| Dataset identity | Hash of manifest body, excluding timestamps | Never use a mutable name as identity |
| Shard assignment | Sort and cut (simple) | Snapshots exceed tens of GB: hash-partition by group id |
| Cadence | Every few hours during collection; on demand otherwise | Consumers cannot absorb frequent versions: publish fewer, keep the rest unaliased |
| Retention of old versions | Keep every version any run read | Legal deletion: delete bytes, keep the manifest with a tombstone |
What you would actually do. Shard-level hashes with a manifest, ids derived from content and recipe, aliases for humans, every external input pinned, and lineage queries wired into the deletion and incident runbooks.
The build has two parts: a manifest writer and verifier, and a lineage graph. Canonical bytes are the foundation: rows are serialised as canonical JSON (sorted keys, no whitespace) and sorted, so row order in memory cannot change the bytes. The dataset id is the hash of the manifest body, which includes shard hashes, parents, the transform record and the ledger, and excludes created_at.
def shard_bytes(rows: list) -> bytes:
"""Canonical JSONL: one canonical JSON object per line, rows in a stable order."""
lines = sorted(canonical_json(r) for r in rows)
return ("\n".join(lines) + "\n").encode("utf-8")
def build_manifest(name: str, rows: list, *, parents: list, transform: dict,
ledger: dict, shard_size: int = 10_000, created_at: str = "") -> tuple:
"""Return (manifest, shards). The dataset_id is a hash of content + recipe, so the same
inputs, code and config always produce the same id, and any change produces a new one."""
ordered = sorted(rows, key=canonical_json)
shards, entries = [], []
for i in range(0, max(len(ordered), 1), shard_size):
data = shard_bytes(ordered[i:i + shard_size])
h = hashlib.sha256(data).hexdigest()
shards.append(data)
entries.append({"path": f"part-{len(entries):05d}.jsonl", "sha256": h,
"rows": len(ordered[i:i + shard_size]), "bytes": len(data)})
body = {"name": name, "shards": entries, "parents": sorted(parents),
"transform": transform, "row_count": len(rows), "ledger": dict(sorted(ledger.items()))}
manifest = {"dataset_id": f"{name}@sha256:{sha256_hex(body)[:16]}", **body,
"created_at": created_at} # metadata only: excluded from the id
return manifest, shards
def verify(manifest: dict, shards: list) -> list:
"""Return a list of problems (empty = the bytes are exactly what the manifest promises)."""
problems = []
if len(shards) != len(manifest["shards"]):
problems.append("shard count mismatch")
for entry, data in zip(manifest["shards"], shards):
if hashlib.sha256(data).hexdigest() != entry["sha256"]:
problems.append(f"{entry['path']}: sha256 mismatch")
body = {k: manifest[k] for k in ("name", "shards", "parents", "transform", "row_count", "ledger")}
if manifest["dataset_id"] != f"{manifest['name']}@sha256:{sha256_hex(body)[:16]}":
problems.append("dataset_id does not match manifest body")
return problems
A manifest for a toy 25-row W1 dataset with 10-row shards looks like this (generated by the code above; shard hashes shortened here for width):
{"dataset_id": "w1_rm_pairs@sha256:65f2cf5b63c8fa66",
"name": "w1_rm_pairs",
"shards": [{"path": "part-00000.jsonl", "sha256": "e2c08016…", "rows": 10, "bytes": 448},
{"path": "part-00001.jsonl", "sha256": "b45987b3…", "rows": 10, "bytes": 447},
{"path": "part-00002.jsonl", "sha256": "9c6450eb…", "rows": 5, "bytes": 220}],
"parents": ["records/w1@r7"],
"transform": {"fn": "transforms.to_rm_pairs", "code": "git:4f2a9c1",
"config_sha256": "9e1c0b77d2a4", "min_agreement": 0.5},
"row_count": 25, "ledger": {"used": 25},
"created_at": "2026-11-02T02:00:00Z"}
The lineage graph stores edges both ways so it can walk downstream (impact) and upstream (reproduction) with a breadth-first search. In production this lives in a database or a lineage service; the structure is the same.
class LineageGraph:
"""Directed graph: raw event batches -> folded snapshots -> training datasets -> mixes -> runs.
Edges point from input to output (PROV 'wasDerivedFrom' read in reverse)."""
def __init__(self) -> None:
self.children: dict[str, set] = defaultdict(set)
self.parents: dict[str, set] = defaultdict(set)
self.attrs: dict[str, dict] = {}
def add(self, node: str, parents: list = (), **attrs) -> None:
self.attrs[node] = attrs
for p in parents:
self.children[p].add(node)
self.parents[node].add(p)
def _walk(self, start: str, nbrs: dict) -> list:
seen, q, out = {start}, deque([start]), []
while q:
for n in sorted(nbrs[q.popleft()]):
if n not in seen:
seen.add(n); q.append(n); out.append(n)
return out
def downstream(self, node: str) -> list:
"""Everything derived from node: what must be rebuilt or retrained if node is deleted."""
return self._walk(node, self.children)
def upstream(self, node: str) -> list:
"""Everything node was derived from: what you need to reproduce it."""
return self._walk(node, self.parents)
The tests check the properties that matter: row order and wall-clock time do not change the id; a one-byte change in a shard is located by verify; a new code version yields a new id; and a downstream walk from one raw-event batch returns the records, both derived datasets, the mix and the run.
def test_manifest_is_content_addressed():
rows = [{"prompt": f"p{i}", "chosen": "a", "rejected": "b"} for i in range(25)]
t = {"code": "git:4f2a9c1", "config_sha256": "c0ffee", "fn": "to_rm_pairs"}
m1, s1 = build_manifest("w1_rm_pairs", rows, parents=["w1_events@2026-11-02"], transform=t,
ledger={"used": 25}, shard_size=10, created_at="2026-11-02T12:00Z")
m2, s2 = build_manifest("w1_rm_pairs", list(reversed(rows)), parents=["w1_events@2026-11-02"], transform=t,
ledger={"used": 25}, shard_size=10, created_at="2026-11-09T08:00Z")
assert m1["dataset_id"] == m2["dataset_id"] and s1 == s2 # order and wall clock do not matter
assert [e["rows"] for e in m1["shards"]] == [10, 10, 5]
assert verify(m1, s1) == []
tampered = [s1[0], s1[1].replace(b'"a"', b'"A"', 1), s1[2]]
assert verify(m1, tampered) == ["part-00001.jsonl: sha256 mismatch"]
m3, _ = build_manifest("w1_rm_pairs", rows, parents=["w1_events@2026-11-02"],
transform=dict(t, code="git:9b1d7e0"), ledger={"used": 25}, shard_size=10)
assert m3["dataset_id"] != m1["dataset_id"] # new code -> new dataset
def test_lineage_deletion_impact():
g = LineageGraph()
g.add("events/w1/2026-11-02")
g.add("events/w1/2026-11-03")
g.add("records/w1@r7", ["events/w1/2026-11-02", "events/w1/2026-11-03"])
g.add("w1_rm_pairs@a1", ["records/w1@r7"])
g.add("eval/rm_heldout@b2", ["records/w1@r7"])
g.add("mix/rm_v14", ["w1_rm_pairs@a1", "hh_public@c3"])
g.add("run/rm-14-0007", ["mix/rm_v14"])
assert g.downstream("events/w1/2026-11-03") == [
"records/w1@r7", "eval/rm_heldout@b2", "w1_rm_pairs@a1", "mix/rm_v14", "run/rm-14-0007"]
assert "events/w1/2026-11-02" in g.upstream("run/rm-14-0007")
Debugging tips. If a rebuild yields a different id, diff the manifests first: a different transform.code or config_sha256 is a recipe change; identical recipes with different shard hashes mean non-determinism (unsorted output, a float formatted differently across library versions, a clock read). Floats are a common culprit: round them in the transform, as to_rm_pairs does for weights, so canonical JSON is stable.
Problem. Lineage is only valuable if it is complete and fast to query when something goes wrong. The two production scenarios that test it are removal (data that must leave every derived dataset) and reproduction (a past result that must be rebuilt exactly). Both arrive under time pressure.
Trigger. The quality program confirms that 3 W1 raters submitted assistant-generated answers; their work must be removed. They contributed about 1,140 of 24,000 labels (4.75%).
Diagnosis with lineage. (1) Select the raters' raw events by pseudonymous rater id: about 1,140 submission events plus QA events. (2) Walk downstream from the event batches that contain them: one records snapshot, w1_rm_pairs, the held-out set, mix rm_v14 and two training runs. The query runs in seconds because the graph is small. (3) Estimate row impact by re-running the transform with the raters excluded, a minutes-long rebuild: assuming the removed labels split between single-labelled and overlap items in the campaign's proportion (18,000 to 6,000), about 855 single-labelled pairs disappear and about 285 overlap votes are removed, so up to 285 overlap items fall from three votes to two (fewer if two removed raters judged the same item), of which some now tie and drop.
Remedy. (1) Append label.retracted events for every affected submission, with the incident id as the reason, so the raw log remains the record of what happened. (2) Rebuild records, pairs and held-out set; each gets a new content id, and the old ids are marked revoked with a pointer to the incident. (3) Rebuild the mix. (4) Retrain the reward model; compare its held-out accuracy with the tainted run on the cleaned held-out set. (5) Record in the incident which conclusions drawn from the tainted run were rechecked.
Cost and trade-off. Pipeline work is minutes; the retrain is the dominant cost. The alternative of not retraining saves that cost but leaves a model trained on known-bad data in the lineage of everything built on it. At 4.75% the default is to retrain; below about 1% a team might instead document and fold the fix into the next scheduled retrain, provided an ablation shows no measurable difference.
Validation. The rebuilt pairs dataset contains no rows whose source_assignments include the removed raters (checked by a query over the new shards), the ledger shows the retractions as no_label_or_retracted, and completeness still reconciles.
Runbook: remove data and propagate.
- Identify the raw events to remove (by rater id, item id, campaign or time range) and write the selection as a saved query attached to the incident.
- Run the downstream walk; list datasets, mixes and runs. If any run is in production, notify its owner now.
- Append retraction events (never edit raw events). For privacy deletion, also delete the bytes and the identity mapping, and replace manifests of deleted datasets with tombstones that keep ids and the deletion reason.
- Rebuild affected datasets; verify that no removed source id appears; publish with new ids; revoke the old ids.
- Decide retraining per run from the share of affected rows and a measured ablation; record the decision.
Reproducibility audit. Weekly, pick 5 published datasets at random, rebuild each from its manifest in a clean environment and compare ids. A mismatch freezes changes to the transform involved until the cause is found.
| SLI | SLO (starting point) |
|---|---|
| Published datasets with complete manifests (parents, transform code, config hash, ledger) | 100%; publication blocked otherwise |
| Training runs that log the dataset ids they read | 100%; run launch blocked otherwise |
| Time from removal request to impact report (datasets, mixes, runs) | < 1 hour |
| Time from removal request to rebuilt, revoked and republished datasets | < 2 working days, or the policy deadline if shorter |
| Reproducibility audit pass rate | 5 of 5 weekly |
These SLOs make lineage a property the platform enforces at publication and launch time rather than documentation written afterwards, which is the only way it stays complete.
Data Contracts, Validation, Deduplication, Decontamination and PII Handling
The last stage before publication decides whether transformed rows are fit to train on. It does five jobs: checks rows against a written data contract, removes duplicates, removes anything that overlaps evaluation data, removes or masks personal data, and checks dataset-level properties such as counts and label distributions. Every failure goes to a quarantine with a reason, never to silent deletion.
Data contracts. A data contract is a written agreement between the team that produces a dataset and the teams that consume it: the schema (fields, types, allowed values), the meaning of each field, quality rules, ownership and service levels. The Open Data Contract Standard, maintained under the Bitol project in the LF AI & Data Foundation, specifies such contracts as YAML documents with sections for schema, data quality, service-level agreements, roles and support (ODCS). The value is not the file format but the fact that checks become executable and that a consumer can rely on a stated guarantee. Before contracts, validation lived in whichever notebook a researcher happened to use, and a producer change broke consumers without anyone being told.
Deduplication. Duplicates enter feedback data in several ways: the same prompt drawn twice from different sources, a prompt with trivial edits, a rater pasting the same correction into several tasks. They overweight some items and, when copies land on both sides of a train/evaluation split, inflate measured accuracy. Exact duplicates are found by hashing a normalised form of the text. Near duplicates are found with MinHash, which summarises each text's set of word n-grams ("shingles") into a short signature such that the share of matching signature positions estimates the Jaccard similarity of the two sets (Broder, 1997), combined with locality-sensitive hashing (LSH), which groups signatures into bands so that only likely matches are compared. For pretraining corpora, Lee et al. (2022) found that deduplication reduced the rate at which models emit memorised training text by a factor of 10 and that train–test overlap affected over 4% of the validation sets of standard datasets.
Eval decontamination. If a training prompt is a copy of an evaluation item, the evaluation measures memory, not skill. The usual check looks for shared word n-grams between training and evaluation texts. It catches copies and light edits but not paraphrases or translations: Yang et al. (2023) showed that a 13B model trained on rephrased MMLU test items reached an MMLU score of 85.9, and proposed an "LLM decontaminator" that retrieves the most similar training items for each test item with embeddings and asks a strong model whether each is a rephrasing; it found rephrased test items in real training sets including CodeAlpaca and StarCoder-Data (LMSYS, 2023). For feedback data, decontamination runs in both directions: training rows must not contain evaluation items, and evaluation sets built from the same campaign must be split by prompt group, never by row.
PII handling. Feedback data contains personal information from three sources: prompts (especially user-sourced ones), model responses that echo them, and annotators who type their own details or paste real data into corrections. Code adds credentials. Tools such as Microsoft Presidio split the job into an analyzer, whose recognizers (rule-based, ML-based or both, helped by surrounding context) find entities, and an anonymizer, whose operators replace, redact or encrypt them (Presidio documentation). Recall differs sharply by entity type: in StarCoder's PII pipeline, trained on 12,000 annotated files, detection reached an F1 of about 98% for emails but about 70% for secret keys (Li et al., 2023). Detected entities are replaced by typed placeholders such as <EMAIL> and <KEY>, which keeps the text readable for training.
Compared with ad hoc checks. Gates cost compute, a few false positives and the discipline of maintaining contracts. They replace a failure mode that is far more expensive: a model trained on contaminated or leaking data, discovered only after release.
What you would actually do. Write a contract per published dataset, enforce it as a blocking gate, run gates cheapest first, deduplicate within and across campaigns, decontaminate against a registry of every evaluation set, and scrub PII with typed placeholders plus a human audit sample. Deviate only in what you add: an LLM-judge paraphrase check for high-stakes evaluations, stricter PII handling for user-sourced prompts.
Each gate has a cost, a miss rate and a false-positive rate. The design work is choosing thresholds and ordering gates so that cheap checks run on everything and expensive ones on few rows.
MinHash and LSH. For two shingle sets with Jaccard similarity \(s\), each MinHash position matches with probability \(s\). With the signature cut into \(b\) bands of \(r\) rows, two texts become candidates if any band matches exactly, with probability \(P(s) = 1 - (1 - s^r)^b\). This is an S-curve whose midpoint sits near \((1/b)^{1/r}\). Candidates are then confirmed with an exact similarity check, so LSH controls cost and misses, while the confirmation step controls false positives.
Decontamination n. Let \(n\) be the n-gram length. Smaller \(n\) catches more edited copies but flags more innocent overlap: in code, 5-word sequences like "return the length of the" are common everywhere. Larger \(n\) misses edited copies. A practical setup uses \(n\) around 13 words for natural-language prompts, compares short texts (fewer than \(n\) words) whole, and adds a weekly embedding-plus-judge pass on the highest-similarity pairs to catch paraphrases.
PII residual. If a fraction \(\pi\) of rows contains a PII entity of some type and the detector's recall for that type is \(\rho\), the expected share of published rows still containing it is \(\pi(1-\rho)\). A human audit of \(m\) rows that finds zero cases bounds the residual rate at about \(3/m\) with 95% confidence (the "rule of three").
Gate order and cost. Schema and row rules are linear and microseconds per row; exact dedup is a hash per row; n-gram decontamination is a set lookup per n-gram; MinHash is about \(b \cdot r\) hashes per shingle; PII models are the slowest per row; an LLM judge is the most expensive and runs only on candidates. Ordering cheapest first means expensive gates see fewer rows.
| Gate | Default | Main risk | Deviate when |
|---|---|---|---|
| Contract | Blocking; violations quarantined | Rules too loose to catch semantic breaks | Add distribution rules (met rate, slot win rate) for every categorical label |
| Exact dedup | sha256 of NFKC-lowercased, whitespace-collapsed text | Misses edits | Never skip; it is nearly free |
| Near dedup | MinHash 128, b=16, r=8, confirm Jaccard ≥ 0.8 | Templates look like duplicates | Templated prompt sets: dedup on the variable part only |
| Decontamination | 13-word n-grams against an eval registry; whole-text for short items | Paraphrases pass | High-stakes evals: add embedding top-k plus LLM judge |
| PII | Regex for structured ids + NER model + secret scanner; typed placeholders | Low recall on keys and names | User-sourced prompts: stricter thresholds and human review |
What you would actually do. Use the defaults in the table, treat every evaluation set in the organisation as an entry in a decontamination registry with its own n-gram index, and measure PII recall per entity type on an audited sample rather than trusting a single overall number.
The validation module provides a contract checker, exact and near deduplication, n-gram decontamination and a PII scrubber. A contract is data: field types, row-level checks and dataset-level checks. In production the contract would be a YAML file in the dataset's repository, reviewed like code; the sketch below follows the spirit of ODCS (schema, quality, ownership, service levels) but is not a conforming ODCS document.
# contracts/w1_rm_pairs.yaml (ODCS-inspired sketch)
name: w1_rm_pairs
version: 1.2.0
owner: rl-data-platform
consumers: [reward-model-training]
schema:
prompt: {type: string, nonempty: true}
chosen: {type: string, nonempty: true}
rejected: {type: string, nonempty: true, differs_from: chosen}
margin: {type: float, min: 0.0, max: 1.0}
weight: {type: float, min: 0.5, max: 1.0} # vote share of the majority
group_id: {type: string, unique: true} # one aggregated pair per item
source_assignments: {type: list}
quality:
row_count: {min: 15000, max: 20000}
max_share: {field: weight, where: "weight < 1.0", max: 0.15}
sla:
freshness: "99% of accepted labels published within 24h"
on_violation: block_publish
The checker implements the same rules in Python. Types are checked strictly (an integer margin is a violation, because it signals a producer change), and each row rule reports the first offending rows so the quarantine entry is actionable.
W1_RM_PAIRS_CONTRACT = {
"name": "w1_rm_pairs", "version": "1.2.0",
"fields": {"prompt": str, "chosen": str, "rejected": str, "margin": float,
"weight": float, "group_id": str, "source_assignments": list},
"row_checks": [
("nonempty", "prompt"), ("nonempty", "chosen"), ("nonempty", "rejected"),
("range", "margin", 0.0, 1.0), ("range", "weight", 0.5, 1.0),
("different", "chosen", "rejected"),
],
"dataset_checks": [
("row_count", 15_000, 20_000), # W1 expects about 16,900 strict pairs
("unique", ("group_id",)), # one aggregated pair per item
("max_share", "weight", lambda w: w < 1.0, 0.15), # split-vote pairs at most 15%
],
}
def check_contract(rows: list, contract: dict) -> list:
"""Return violations as strings. Row checks report the first 5 offending rows per check."""
v = []
for name, typ in contract["fields"].items():
bad = [i for i, r in enumerate(rows) if not isinstance(r.get(name), typ)
or (typ is float and isinstance(r.get(name), bool))]
if bad:
v.append(f"type {name}: expected {typ.__name__}, rows {bad[:5]}")
for chk in contract["row_checks"]:
kind, bad = chk[0], []
for i, r in enumerate(rows):
try:
if kind == "nonempty" and not str(r[chk[1]]).strip(): bad.append(i)
if kind == "range" and not chk[2] <= r[chk[1]] <= chk[3]: bad.append(i)
if kind == "different" and r[chk[1]] == r[chk[2]]: bad.append(i)
except (KeyError, TypeError):
bad.append(i)
if bad:
v.append(f"{kind} {chk[1:]}: rows {bad[:5]} ({len(bad)} total)")
for chk in contract["dataset_checks"]:
if chk[0] == "row_count" and not chk[1] <= len(rows) <= chk[2]:
v.append(f"row_count {len(rows)} outside [{chk[1]}, {chk[2]}]")
if chk[0] == "unique":
keys = [tuple(r.get(k) for k in chk[1]) for r in rows]
if len(set(keys)) != len(keys):
v.append(f"unique {chk[1]}: {len(keys) - len(set(keys))} duplicates")
if chk[0] == "max_share" and rows:
share = sum(1 for r in rows if chk[2](r.get(chk[1]))) / len(rows)
if share > chk[3]:
v.append(f"max_share {chk[1]}: {share:.3f} > {chk[3]}")
return v
Deduplication normalises text (Unicode NFKC, lowercase, collapsed whitespace), builds 5-word shingles, computes a 128-value MinHash signature with seeded BLAKE2b hashes, buckets signatures by band and confirms candidates with exact Jaccard similarity.
def normalize(text: str) -> str:
"""Unicode NFKC, lowercase, collapse whitespace. Exact-dup key = sha256 of this."""
return re.sub(r"\s+", " ", unicodedata.normalize("NFKC", text).lower()).strip()
def shingles(text: str, n: int = 5) -> set:
w = normalize(text).split()
return {" ".join(w[i:i + n]) for i in range(max(len(w) - n + 1, 1))}
def minhash(sh: set, num_perm: int = 128) -> list:
"""Signature: for each of num_perm seeded hash functions, the minimum hash over shingles.
P(sig_a[i] == sig_b[i]) equals the Jaccard similarity of the two shingle sets."""
sig = []
for seed in range(num_perm):
salt = seed.to_bytes(4, "little")
sig.append(min(int.from_bytes(hashlib.blake2b(s.encode(), digest_size=8, salt=salt).digest(), "little")
for s in sh))
return sig
def near_duplicates(texts: dict, bands: int = 16, rows: int = 8, threshold: float = 0.8) -> list:
"""LSH: split each signature into `bands` bands of `rows` values; texts sharing any band are
candidates; candidates are confirmed with exact Jaccard >= threshold. Returns sorted pairs."""
sh = {k: shingles(t) for k, t in texts.items()}
buckets = defaultdict(list)
for k, s in sh.items():
sig = minhash(s, bands * rows)
for b in range(bands):
buckets[(b, tuple(sig[b * rows:(b + 1) * rows]))].append(k)
cands = {tuple(sorted((x, y))) for ks in buckets.values() for i, x in enumerate(ks) for y in ks[i + 1:]}
return sorted(p for p in cands if len(sh[p[0]] & sh[p[1]]) / len(sh[p[0]] | sh[p[1]]) >= threshold)
Decontamination builds one n-gram index per evaluation registry and reports, per training row, how many n-grams it shares with any evaluation item. The docstring states the known blind spot.
def ngrams(text: str, n: int) -> set:
w = normalize(text).split()
if len(w) < n:
return {" ".join(w)} # short text: compare it whole
return {" ".join(w[i:i + n]) for i in range(len(w) - n + 1)}
def build_eval_index(eval_texts: list, n: int = 13) -> set:
idx = set()
for t in eval_texts:
idx |= ngrams(t, n)
return idx
def contaminated(train_texts: dict, eval_index: set, n: int = 13) -> dict:
"""train id -> number of n-grams shared with any eval item. Catches verbatim and lightly
edited copies; misses paraphrases and translations (pair with an embedding + judge pass)."""
hits = {}
for k, t in train_texts.items():
c = len(ngrams(t, n) & eval_index)
if c:
hits[k] = c
return hits
The PII scrubber handles structured identifiers with regular expressions and typed placeholders. Names and street addresses need an NER-based analyzer such as Presidio's; the function returns counts per type so the dashboard can track detection rates over time.
PII_PATTERNS = [ # order matters: keys before generic long tokens
("KEY", re.compile(r"\b(?:sk-[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{36})\b")),
("EMAIL", re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")),
("IP", re.compile(r"\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b")),
("PHONE", re.compile(r"(?<!\w)\+?\d[\d ()-]{8,}\d(?!\w)")),
]
def scrub(text: str) -> tuple:
"""Replace structured PII with typed placeholders. Returns (clean_text, counts).
Regexes catch structured identifiers only; names and addresses need an NER pass."""
counts = {}
for label, pat in PII_PATTERNS:
text, n = pat.subn(f"<{label}>", text)
if n:
counts[label] = n
return text, counts
The tests include one that documents a limitation on purpose: a paraphrased evaluation item passes the n-gram gate.
def test_contract_flags_bad_rows():
good = {"prompt": "p", "chosen": "x", "rejected": "y", "margin": 0.67, "weight": 1.0,
"group_id": "i1", "source_assignments": ["a1"]}
rows = [dict(good, group_id=f"i{i}") for i in range(15_000)]
assert check_contract(rows, W1_RM_PAIRS_CONTRACT) == []
rows[3] = dict(rows[3], rejected="x") # chosen == rejected
rows[4] = dict(rows[4], margin=1) # int, not float
v = check_contract(rows, W1_RM_PAIRS_CONTRACT)
assert any(s.startswith("different") for s in v) and any(s.startswith("type margin") for s in v)
def test_near_duplicate_prompts():
base = ("Write a Python function that parses an ISO 8601 timestamp string and returns a timezone "
"aware datetime object, raising ValueError on malformed input and handling the Z suffix")
texts = {"p1": base,
"p2": base.replace("Write", "Please write"), # light edit
"p3": "Implement a thread safe LRU cache class in Python with get and put methods and a "
"configurable capacity, evicting the least recently used entry when full"}
assert near_duplicates(texts) == [("p1", "p2")]
def test_decontamination_catches_copies_not_paraphrases():
eval_q = ("Given a list of integers, return the length of the longest strictly increasing "
"subsequence using an algorithm that runs in O(n log n) time")
idx = build_eval_index([eval_q])
train = {"t1": "Solve this: " + eval_q + " and explain.",
"t2": "Find how long the longest strictly rising subsequence of an int array is, in n log n."}
assert set(contaminated(train, idx)) == {"t1"} # paraphrase t2 slips through
def test_pii_scrub():
t = ("Contact jane.doe@example.com or +1 (415) 555-0137; server 10.0.12.7; "
"key sk-abcdefghijklmnopqrstuvwx1234")
clean, counts = scrub(t)
assert counts == {"KEY": 1, "EMAIL": 1, "IP": 1, "PHONE": 1}
assert "example.com" not in clean and "<KEY>" in clean
assert normalize(" Hello\tWORLD ") == "hello world"
Debugging tips. If near-dedup flags many unrelated prompts, look for shared boilerplate (system prompts, templates) and strip it before shingling. If decontamination flags a large share of rows, check whether an evaluation set contains generic text (instructions, licence headers) that should be excluded from its index. If PII counts drop to zero after a change, test the scrubber on a fixed sample with known entities; a silent regex failure looks exactly like clean data.
Problem. Validation gates fail in two directions. Too loose, and contaminated, duplicated or personal data reaches training; too strict, and good data piles up in quarantine while freshness SLOs burn. Operating the gates means measuring both directions and having a decision procedure for each kind of finding.
Trigger. A new evaluation suite for coding is registered with the decontamination service. The next W1 export runs the gate against it and flags 37 of the 10,000 prompts (0.37%) for 13-gram overlap. The weekly embedding-plus-judge pass, run early because of the finding, flags another 112 prompts (1.1%) as paraphrases. All counts in this incident are illustrative.
Diagnosis. All 149 prompts came from one public prompt source that, it turns out, the evaluation authors also drew from. The overlap is in the prompt source, not caused by the platform. Two questions follow: which W1 rows to drop, and whether other datasets drew on the same source.
Remedy. (1) Drop the 298 comparisons built on the 149 prompts (two response pairs per prompt) and record the eval suite id and the dropped item hashes in the manifest ledger under decontaminated. (2) Walk lineage downstream from the prompt source to find every dataset and mix that used it; run the gate against each. (3) Notify the evaluation owners that 149 of their items are reproduced in a public source, so that scores on those items can be reported separately. (4) Add the evaluation suite to the prompt-selection filter used before generation, so overlapping prompts are never sent to raters.
Cost. The 298 dropped comparisons had already been labelled: at about \$4.12 per useful comparison, roughly \$1,230 of labelling was spent on unusable rows. Running the same check at prompt-selection time costs one index lookup per prompt and would have avoided it. The trade-off is that the evaluation registry must be shared with the sampling service, so the registry needs access control (evaluation items are themselves sensitive).
Validation. The evaluation owners compare model scores on the 149 flagged items with scores on the rest. A clearly higher score on flagged items for models trained on data from that source supports the contamination hypothesis; no difference weakens it but does not justify keeping the rows, since future models may memorise them.
PII scenario. The weekly PII audit samples 500 published W1 rows, over-sampling code with configuration content. It finds 2 rows containing a cloud credential in a format the regex set did not cover. Remedy: add the pattern and a secret scanner to the gate; re-scan every published dataset (lineage tells which ones) and republish; if the credential could be real, report it to its owner for rotation. With 2 hits in 500 over-sampled rows, the residual rate in the over-sampled stratum is about 0.4%; after the fix, a re-audit with 0 hits bounds it at about 0.6% (rule of three), so the audit is repeated with a larger sample before the issue is closed.
Alert rules.
# evaluated per candidate snapshot unless noted
- alert: ContractViolation
expr: contract_violations_total{snapshot="candidate"} > 0
action: block_publish; ticket owner
- alert: QuarantineSpike # evaluated every 5 min on the ingest stream
expr: rate(quarantined_events[15m]) / rate(ingested_events[15m]) > 0.005
action: page pipeline on-call
- alert: LabelDistributionDrift
expr: abs(met_rate{campaign="w3"} - avg_over_7d(met_rate{campaign="w3"})) > 0.10
or abs(left_slot_win_rate{campaign="w1"} - avg_over_7d(left_slot_win_rate{campaign="w1"})) > 0.10
action: hold publish; page data owner
- alert: DecontamHit
expr: eval_ngram_hits{snapshot="candidate"} > 0
action: drop rows to quarantine; ticket eval owner
- alert: PIIAuditFailure
expr: pii_audit_residual_hits_7d > 0
action: revoke affected snapshots; rescan via lineage
| SLI | SLO (starting point) | Why this level |
|---|---|---|
| Contract violations in published snapshots | 0 | Contracts are blocking; any violation in published data means a gate was bypassed |
| Quarantine resolved (replayed or discarded with reason) | 95% within 3 working days | Unresolved quarantine is data the campaign paid for and cannot use |
| False-positive rate of near-dedup (audited weekly, 50 flagged pairs) | < 10% | Higher means good data is being dropped; retune bands or threshold |
| Eval n-gram hits in published data | 0 | Contamination invalidates evaluation for every downstream model |
| Residual structured PII in audit sample | 0 hits; audit size raised until the 95% bound is < 0.2% | Requires about 1,500 audited rows with zero hits (rule of three) |
These gates close the loop with the earlier sections: the data model keeps raw events so that quarantined rows can be replayed after a fix, transforms return ledgers so that every dropped row has a reason, and lineage turns each finding into a list of datasets to rebuild. What leaves this stage is a versioned, verified dataset ready for the training mix, the subject of the next chapter.
Into the Training Mix
A campaign is finished when its labels pass quality checks and leave the platform as a versioned dataset. It is useful only when that dataset changes a model. Between the two sits the last stretch of the platform's loop: consumers that turn labels into gradients, a measurement step that says whether the data helped, and a path whose length decides how quickly a research idea becomes a training signal.
A consumer is any training component that reads human data and turns it into a loss or a reward. Four kinds matter most for RL post-training. A reward model learns a scalar score from pairwise preferences and later scores the policy's samples during RL. Direct preference optimisation (DPO) and its relatives skip the separate reward model and update the policy directly from the same pairs. A process reward model (PRM) learns to score individual steps of a solution or agent transcript from step-level labels. A rubric grader applies expert-written criteria to each response and returns a reward made of per-criterion scores. Each consumer reads the same raw material differently, so the properties of the data that matter (how noisy the labels are, how often raters call a tie, how large the preference is, where in a transcript an error is marked) differ by consumer.
The second topic is data value: an estimate of how much a dataset, or a source within it, improves a model per unit of cost. Without it, a platform cannot say whether a campaign was worth what it cost, which vendor or rater population to buy more from, or when to stop collecting. The tools are ablations (train with and without the data), scaling curves (train on growing subsets), attribution methods (trace a model's behaviour back to individual training examples) and per-source accounting.
The third topic is request-to-mix latency: the elapsed time from a researcher's data request to the moment the resulting data is in the training mix of a model. Most of that time is usually waiting, not work. Treating the path as a value stream, mapping where time goes and removing the waits, is the main lever on how many data ideas a team can test.
W1 collects 20,000 pairwise comparisons of coding responses for a reward model. After QA rejects 8%, about 18,400 useful comparisons remain at about $4.12 each. The reward model is the consumer. The questions this chapter answers for W1 are: how the 8% ties and the 72% inter-rater agreement shape the reward model; whether the 18,400 comparisons were worth $75,780; and how the 21 days from request to mix (scoping 3, guidelines and pilot 4, collection 6, QA 3, export 2, retrain and mix inclusion 3) can become 7.
Compared with a classic supervised-learning pipeline, where a labelled dataset is the end product, here the dataset is an intermediate. Its worth is measured downstream, through a consumer that may be retrained weekly, and the time it takes to get there sets the pace of research. What you would actually do: record, for every exported dataset, which consumers used it, how ties and preference strength were encoded, what measured effect it had and how long it took to arrive. Deviate from per-dataset impact measurement only for tiny datasets whose effect cannot be measured at any affordable evaluation size; for those, measure at the level of the source they belong to.
Three quantities govern this chapter. The first is the effective information a dataset carries for its consumer. Let \(n\) be the number of useful labelled comparisons and \(\varepsilon\) the probability that a label is reversed relative to the preference a careful, well-informed rater would give (the flip rate). Under symmetric, independent flips, the excess error of a preference learner grows by a factor of about \(1/(1-2\varepsilon)\) relative to clean data (Chowdhury et al. 2024), which is equivalent to an effective sample size
\[ n_{\text{eff}} = n\,(1-2\varepsilon)^2 . \]The second is value per dollar. If \(\Delta Q\) is the measured change in a quality metric \(Q\) (held-out reward-model accuracy, or a policy's win rate) from adding the dataset, and \(C\) its cost, the figure of merit is \(\Delta Q / C\), or its inverse, the cost per point of \(Q\).
The third is lead time. If stage \(i\) of the path takes process time \(p_i\) and waiting time \(w_i\), a strictly sequential path has lead time \(T = \sum_i (p_i + w_i)\), and the flow efficiency \(\eta = \sum_i p_i / T\) says what fraction of elapsed time anyone is working.
Information. If 72% pairwise agreement on the overlap items comes from two raters who each flip independently with probability \(\varepsilon\), then \(0.72 = (1-\varepsilon)^2 + \varepsilon^2\), so \(\varepsilon \approx 0.168\) and \(n_{\text{eff}} \approx 18{,}400 \times 0.44 \approx 8{,}100\). This treats all disagreement as error; genuine ambiguity is part of it, so 0.168 is an upper bound on rater error and a fair description of how noisy the labels look to the consumer.
Value. An illustrative leave-W1-out ablation moves held-out coding reward-model accuracy from 64.5% to 68.5%: \(\Delta Q = 4.0\) points for $75,780, about $18,900 per point.
Lead time. \(T = 21\) days. If the process times are 0.5, 1.5, 4.4, 0.5, 0.25 and 1.0 days (an assumption made for this chapter's analysis), \(\eta = 8.15/21 \approx 39\%\).
| Feedback type | Typical consumer | Data property it is most sensitive to |
|---|---|---|
| Pairwise preference (W1) | Bradley–Terry reward model, or DPO-style loss | flip rate, ties, preference strength, correlation within a prompt |
| First failing step + correction (W2) | Process reward model; supervised correction data | position noise of the marked step; steps after the error are unlabelled |
| Rubric + item scores (W3) | Rubric grader (an AI judge applying the rubric) as RL reward | item-level grader agreement; weight calibration; item coverage |
Table. Feedback types of the three reference workloads and the consumer each feeds.
What you would actually do: compute \(n_{\text{eff}}\), \(\Delta Q/C\) and \(\eta\) for every campaign, because each one points at a different lever: label quality, what to buy next, and where the calendar goes. The default is to report all three on the dataset's record; deviate only when a consumer has no affordable held-out metric, in which case report \(n_{\text{eff}}\) and \(T\) and say that value is unmeasured.
The artifact that ties the chapter together is a data card: one record per dataset version, written at export and appended to as consumers use the data and as impact is measured. It holds the counts, the quality statistics the consumer cares about, how each consumer encoded the data (tie policy, margin scheme, mix weight), the measured impact with the evaluation set pinned to a version, the cost, and the two timestamps that define request-to-mix latency. The checker below rejects cards that cannot support a decision: an impact number whose interval does not contain it, an evaluation set without a version, or a preference consumer that did not record how it handled ties.
# w1_datacard.py -- the record that links a dataset version to its consumers and its measured impact.
# python3 w1_datacard.py (stdlib only)
import json
CARD = json.loads("""{
"dataset": "w1_coding_pairs", "version": "v3", "campaign": "w1",
"request_opened": "2026-10-01T09:00Z", "in_mix": "2026-10-22T09:00Z",
"counts": {"labels": 24000, "useful_comparisons": 18400, "ties": 1472},
"quality": {"gold_accuracy_min": 0.80, "overlap_agreement": 0.72,
"implied_flip_rate": 0.168, "low_effort_raters_removed": 6},
"consumers": [
{"kind": "reward_model", "run": "rm-2026-10-21", "tie_policy": "drop",
"margin": "llama2_small", "weight_in_mix": 0.15}
],
"impact": [
{"metric": "rm_heldout_coding_acc", "eval_set": "code-pairs-4k@v2",
"delta": 0.040, "ci95": [0.032, 0.049], "method": "leave-source-out, paired bootstrap"}
],
"cost_usd": 75780
}""")
REQUIRED = ["dataset", "version", "campaign", "request_opened", "in_mix", "counts", "quality", "consumers", "impact", "cost_usd"]
def check(card):
errs = [f"missing {k}" for k in REQUIRED if k not in card]
c = card.get("counts", {})
if c.get("ties", 0) > c.get("useful_comparisons", 0):
errs.append("ties exceed comparisons")
for imp in card.get("impact", []):
lo, hi = imp["ci95"]
if not lo <= imp["delta"] <= hi:
errs.append(f"{imp['metric']}: delta outside its interval")
if "eval_set" not in imp or "@" not in imp["eval_set"]:
errs.append(f"{imp['metric']}: eval set must be pinned to a version")
for con in card.get("consumers", []):
if con["kind"] in ("reward_model", "dpo") and "tie_policy" not in con:
errs.append(f"{con['kind']}: tie policy not recorded")
return errs
def cost_per_point(card, metric):
imp = next(i for i in card["impact"] if i["metric"] == metric)
return card["cost_usd"] / (imp["delta"] * 100)
if __name__ == "__main__":
assert check(CARD) == [], check(CARD)
bad = dict(CARD, impact=[dict(CARD["impact"][0], eval_set="code-pairs-4k")])
assert check(bad) == ["rm_heldout_coding_acc: eval set must be pinned to a version"]
print(f"cost per accuracy point: ${cost_per_point(CARD, 'rm_heldout_coding_acc'):,.0f}")
print("ok")
Output:
cost per accuracy point: $18,945
ok
The card records 24,000 labels, 18,400 useful comparisons and 1,472 ties (8% of the useful comparisons, assuming the tie rate applies uniformly), the implied flip rate 0.168, a reward-model consumer that drops ties and uses Llama 2's small margins, and a +4.0-point ablation on a pinned 4,000-pair evaluation set. Cost per accuracy point is $75,780 / 4.0 ≈ $18,945. Request opened 2026-10-01 and in the mix 2026-10-22: 21 days.
Debugging tips. If impact numbers drift between reports for the same dataset, check first whether the evaluation set changed without a version bump. If two consumers disagree about a dataset's value, compare their tie policies and mix weights on the cards before suspecting the data.
Operating this part of the platform means owning three service levels: that every dataset reaches a consumer quickly, that its consumer uses it the way the card says, and that its impact is measured soon enough to inform the next purchase. Each is a measurable objective with a target set from the team's own history; the targets below are starting points, not published standards.
| Objective | Indicator | Starting target |
|---|---|---|
| Request-to-mix latency | days from request opened to dataset in a training mix, per campaign | p50 ≤ 7 d, p90 ≤ 10 d |
| Consumer fidelity | fraction of exports whose tie count, margin distribution and row count in the training job match the card (±0.5%) | 100% (any mismatch pages) |
| Impact coverage | fraction of datasets above a size floor with an ablation or scaling estimate within 7 days of mix inclusion | ≥ 90% |
| Card completeness | cards passing the checker | 100% |
Table. Service levels for the "into the mix" stage. Targets are illustrative defaults to be replaced by the team's own baseline.
The W1 baseline breaks two of the four objectives: 21 days against a 7-day target, and impact known only when someone ran an ablation by hand. The sections that follow work through the consumer fidelity check (an incident in which ties were exported incorrectly), the impact process (an incident in which a follow-up campaign did not help) and the latency budget (an incident in which collection capacity was taken by another campaign).
The cost of running these objectives is mostly evaluation compute: a leave-one-source-out ablation retrains the consumer once per source. For a reward model retrained on a fixed schedule this can ride along with the scheduled run as an extra arm. The validation that the objectives are worth having is simple: over a quarter, compare the number of data experiments that reached a decision (keep, buy more, stop) before and after impact coverage was enforced. If the count does not rise, the measurement is being produced but not used, and the dashboard needs an owner more than a new metric.
Reward models and other consumers of human data
The platform's output is a table of labels. What a training run needs is a loss. The component in between, the consumer, decides which properties of the labels the model will actually learn from. Four consumers dominate RL post-training, and each has its own sensitivities.
Reward models. A reward model is a language model with a scalar output head. It receives a prompt and one response and outputs a number. It is trained on pairs: for each comparison, it scores the chosen and the rejected response, and the loss pushes the chosen score above the rejected one. This is the Bradley–Terry model of paired comparison: the probability that one item beats another depends only on the difference of their scores. Once trained, the reward model scores fresh policy samples during RL, so its errors become the policy's targets. InstructGPT collected rankings of 4 to 9 responses per prompt and, because all comparisons from one prompt are highly correlated, trained on all of a prompt's pairs together as one batch element instead of shuffling them independently, which had caused overfitting (Ouyang et al. 2022; Lambert). The general lesson for a platform: the grouping of labels, not only the labels, is part of what the consumer needs.
Preference strength and margins. Llama 2's raters chose the better of two responses and then rated how much better: significantly better, better, slightly better, or negligibly better/unsure. The reward model's accuracy tracked that rating closely: on Meta's helpfulness test set it was about 81% on "significantly better" pairs and 55% on "negligibly better/unsure" pairs, close to chance (Touvron et al. 2023). The authors added a margin to the loss, so that pairs rated as clearly different must be separated by a larger score gap, and reported a small gain concentrated on the clearly different pairs. Lambert's survey notes the margin term was dropped in Llama 3 as gains diminished at scale (Lambert). Strength ratings are cheap to collect and also serve as a filter and a diagnostic, whether or not the loss uses them.
Ties. A tie means the rater saw no meaningful difference. Bradley–Terry has no tie outcome, so the consumer must choose: drop ties, train them toward equal scores (a target probability of one half), or use a tie-aware model. Dropping is safe and wastes the rater time spent on them. Training toward equality teaches the model which differences do not matter, such as formatting changes, but makes the loss more sensitive to raters who use "tie" as an escape from hard items. The choice must be recorded, because it changes what the model learns.
DPO-style methods. DPO rewrites the RL objective so that the policy itself plays the role of the reward model: the implied reward of a response is how much more likely the policy makes it than a frozen reference model does (Rafailov et al. 2023). It consumes the same pairs, without a separate reward-model training or RL sampling stage. The cost is that label noise goes straight into the policy. Azar et al. showed that when preferences are (near-)deterministic, DPO can overfit and drift from the reference despite its regularisation, and proposed IPO as a fix (Azar et al. 2023). Robust variants take the flip rate as an input: conservative DPO smooths the labels, and robust DPO corrects the loss so that, on average over flips, it equals the loss on clean data (Chowdhury et al. 2024). Both need the platform to supply an estimate of the flip rate.
Process reward models. A PRM scores each step of a solution. PRM800K, the dataset behind OpenAI's study, holds about 800,000 step-level labels on about 75,000 solutions to 12,000 math problems, each step marked positive, negative or neutral; neutral was kept for ambiguous steps so that it could be treated as either positive or negative later, and the study's scoring treats neutral steps as positive. A solution's score is the probability that every step is correct. The study also chose which solutions to label: it showed raters "convincing wrong-answer" solutions, rated highly by the current PRM but reaching a wrong answer, and estimated a 2.6× gain in data efficiency over uniform selection (Lightman et al. 2023). For a PRM the critical data property is position: whether the marked step is the right one.
Rubric graders. For tasks that cannot be checked by a program, experts write a rubric per prompt, a list of weighted criteria, and an AI grader scores each policy sample against it during RL. Rubrics as Rewards reported gains over Likert-style judge rewards of up to 31% relative on HealthBench and 7% on GPQA-Diamond (Gunjal et al. 2025), and checklist-based feedback improved instruction following on every benchmark tested (Viswanathan et al. 2025). Human data enters twice: as the rubric itself, and as human item scores that validate the AI grader.
W1 feeds a Bradley–Terry reward model: 18,400 useful comparisons, 8% ties, 72% agreement on the 2,000 triple-labelled items. Decisions: group pairs by prompt, record the tie policy, and keep strength ratings even if the loss ignores them.
W2 feeds a process reward model and a correction dataset: 2,000 transcripts with a marked first failing step. Exact agreement on that step is 58%, within ±2 steps 81%, so most disagreement is about position, not about whether the transcript failed.
W3 feeds a rubric grader: 3,000 legal-drafting rubrics of about 10 weighted items each; the AI grader must agree with human item scores at 0.8 or better before its scores are used as the RL reward.
Compared with supervised fine-tuning, where each label is a target text, these consumers learn from relations (this is better than that, this step is wrong) and amplify any systematic pattern in those relations. What you would actually do: for preferences, default to a grouped Bradley–Terry reward model with ties dropped and strength recorded; switch to a tie-aware or margin loss only when an ablation on the team's own data shows a gain. For DPO, pass an explicit flip-rate estimate to a robust variant. For PRMs and rubric graders, measure position agreement and item agreement before training on the data.
Bradley–Terry with margin and ties. Let \(r_\theta(x,y)\) be the reward model's score for response \(y\) to prompt \(x\), \(\sigma(z) = 1/(1+e^{-z})\) the logistic function, and \(d = r_\theta(x,y_c) - r_\theta(x,y_r)\) the score gap between chosen and rejected responses. Bradley–Terry models \(P(y_c \succ y_r) = \sigma(d)\). With a margin \(m \ge 0\) that depends on the rated strength, and a target \(t\) (1 for a strict preference, ½ for a tie in the "train toward equality" policy), the loss per comparison is
\[ \ell(\theta) = -\,t \log \sigma(d - m) \;-\; (1-t)\log \sigma(-d). \]For \(t = 1\) this is Llama 2's margin loss; for \(t = \tfrac12, m = 0\) it is minimised at \(d = 0\), equal scores. Llama 2's "small" margins were 1, ⅔, ⅓ and 0 for the four strength levels, and the "large" ones 3, 2, 1, 0. On the helpfulness test set average accuracy was 62.5% with no margin, 63.0% with the small margin and 62.9% with the large margin; the large margin helped "significantly better" pairs (79.1% → 80.7%) and slightly hurt the "negligibly better" ones (54.5% → 54.3%) (Touvron et al. 2023, Tables 27–28). The gains are small; the larger value of strength labels is as a covariate for diagnosis.
Correlated pairs. A prompt with \(K\) ranked responses yields \(\binom{K}{2}\) pairs, 6 to 36 for \(K = 4\ldots 9\). Weighting each pair by \(1/\binom{K}{2}\) and keeping a prompt's pairs in one batch makes each prompt one unit of evidence, which is what InstructGPT did (Ouyang et al. 2022).
DPO and noise. With policy \(\pi_\theta\), reference \(\pi_{\text{ref}}\) and temperature \(\beta\), DPO's logit for a pair is \(h = \beta[\log\frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - \log\frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)}]\) and its loss is \(-\log\sigma(h)\) (Rafailov et al. 2023). If each observed label is flipped with probability \(\varepsilon\), write \(\mathcal{L}(h) = -\log\sigma(h)\). Conservative DPO uses \((1-\varepsilon)\mathcal{L}(h) + \varepsilon\mathcal{L}(-h)\); robust DPO uses
\[ \hat{\mathcal{L}}_\varepsilon(h) = \frac{(1-\varepsilon)\,\mathcal{L}(h) - \varepsilon\,\mathcal{L}(-h)}{1-2\varepsilon}, \]whose expectation over random flips equals the clean loss. Its error bound grows as \(\frac{1}{1-2\varepsilon}\sqrt{d/n}\), with \(d\) the parameter dimension and \(n\) the number of pairs (Chowdhury et al. 2024); matching clean-data error therefore takes about \(1/(1-2\varepsilon)^2\) times as many noisy pairs, which is the \(n_{\text{eff}}\) rule. On Anthropic HH with Llama-2-7B and \(\varepsilon = 0.1\), they report improvements in GPT-4-judged win rate over the SFT policy of 45.8% (DPO), 39.2% (conservative DPO) and 51.2% (robust DPO).
Estimating \(\varepsilon\) from overlap. If two raters independently flip the true preference with probability \(\varepsilon\), they agree with probability \(a = (1-\varepsilon)^2 + \varepsilon^2\), so
\[ \varepsilon = \tfrac12\left(1 - \sqrt{2a - 1}\right). \]A majority of three raters errs with probability \(\varepsilon_3 = 3\varepsilon^2(1-\varepsilon) + \varepsilon^3\). The assumptions (symmetric, independent, rater-agnostic flips, ties excluded) are strong; the estimate is a calibration input, not a fact about the raters. Wang et al. instead estimate per-pair preference strength from the votes of an ensemble of reward models and flip or down-weight pairs the ensemble confidently contradicts (Wang et al. 2024).
With \(a = 0.72\): \(\varepsilon = \tfrac12(1 - \sqrt{0.44}) = 0.168\); \(n_{\text{eff}} = 18{,}400 \times (1 - 0.336)^2 \approx 8{,}100\). A majority of three errs with \(\varepsilon_3 \approx 0.075\), a factor \((1-0.15)^2 \approx 0.72\). Three single labels on three different items are worth \(3 \times 0.44 = 1.32\) clean-equivalent comparisons; the same three labels spent on one item are worth 0.72. Under this model, overlap is a measurement cost, not a way to buy training signal; W1's 10% overlap is the right size for estimating \(\varepsilon\), not a candidate for expansion.
Ties: 8% of 18,400 ≈ 1,472 comparisons. Dropping them leaves about 16,928 strict pairs; training them toward equal scores keeps all 18,400 but adds 1,472 targets of ½.
PRMs. A PRM outputs per-step correctness probabilities \(p_1,\dots,p_S\); PRM800K scored a solution as \(\prod_s p_s\) (Lightman et al. 2023). From a "first failing step" label at step \(k\), the natural targets are positive for steps \(1..k-1\), negative at \(k\), and no label after \(k\). If raters disagree about \(k\) by a step or two, a hard target makes neighbouring steps noisy; a soft target spread over \(k\pm2\) uses the measured disagreement.
Rubric rewards. With item weights \(w_j\) and grader scores \(s_j \in [0,1]\), the reward is \(R = \sum_j w_j s_j / \sum_j w_j\). If the grader's item scores are wrong independently with probability \(q\), the reward's noise variance for \(J\) equally weighted items is about \(q/J\) (each item contributes variance \(q/J^2\)), so it falls with the number of items, which is one reason itemised rubrics give a steadier signal than one holistic score.
W2: exact first-failing-step agreement 58%, within ±2 steps 81%. Two experts mark different steps on 42% of transcripts, but land within two steps of each other on 81%; a target spread over ±2 steps encodes that measured uncertainty instead of treating the neighbours of the marked step as certainly correct or certainly unlabelled. W3: with 10 equally weighted binary items and item-level human–AI agreement of 0.8, about 2 of 10 items are mis-scored per response. If those errors point in random directions, the grader-induced standard deviation of the reward is about \(\sqrt{10 \times 0.2 \times 0.1^2} \approx 0.14\) on a 0–1 scale, the \(q/J\) variance rule in numbers.
| Decision | Default | Deviate when |
|---|---|---|
| Ties in a Bradley–Terry RM | drop, record the count | an ablation shows equal-score targets improve held-out accuracy on near-identical pairs |
| Strength ratings | collect; use small margins or none | clearly separable pairs dominate the use case |
| Overlap fraction | enough to estimate \(\varepsilon\) (W1: 10%) | labels feed an evaluation set, where accuracy per item matters more than volume |
| DPO on noisy data | robust variant with \(\varepsilon\) from overlap | \(\varepsilon\) cannot be estimated; then use a reward model plus RL with an ensemble |
Table. Consumer-side decisions and defaults.
What you would actually do: publish \(\varepsilon\), tie rate and strength distribution with every preference export, because they are the inputs the consumer's loss needs; otherwise the training team will guess them.
The code below implements the consumer side of W1: converting labels to pairs under a tie policy, the Bradley–Terry loss with margin and soft target, the DPO logit and three DPO losses (plain, conservative, robust), the flip rate implied by overlap agreement, and the clean-equivalent sample size. Inputs are plain Python dicts and NumPy arrays of shape \([n]\); in a real trainer the scores come from the reward model's head, one per response, and the log-probabilities from summed token log-probabilities of the policy and reference.
# w1_consume.py -- turn W1 pairwise labels into training pairs and losses.
# python3 w1_consume.py (numpy only)
import numpy as np
# Llama 2 style margins per strength level (Touvron et al. 2023, Table 27, "small")
MARGIN = {"significant": 1.0, "better": 2/3, "slight": 1/3, "negligible": 0.0}
def to_pairs(labels, tie_policy="drop"):
"""labels: list of dicts {item, a, b, choice in {'a','b','tie'}, strength}.
Returns list of (chosen, rejected, margin, target) where target is the
probability that 'chosen' beats 'rejected' (1.0 strict, 0.5 for a tie)."""
out = []
for l in labels:
if l["choice"] == "tie":
if tie_policy == "drop":
continue
if tie_policy == "half": # BT with a 0.5 target
out.append((l["a"], l["b"], 0.0, 0.5))
continue
c, r = (l["a"], l["b"]) if l["choice"] == "a" else (l["b"], l["a"])
out.append((c, r, MARGIN[l["strength"]], 1.0))
return out
def log_sigmoid(x):
return -np.logaddexp(0.0, -x)
def bt_loss(rc, rr, margin=0.0, target=1.0):
"""Bradley-Terry loss with optional margin and soft target.
rc, rr: reward scores (arrays, shape [n]). target 1.0 = strict, 0.5 = tie."""
d = rc - rr
return -(target * log_sigmoid(d - margin) + (1 - target) * log_sigmoid(-d))
def dpo_logit(beta, lp_w, lr_w, lp_l, lr_l):
"""DPO implicit reward difference: beta*[(log pi - log ref)_w - (log pi - log ref)_l]."""
return beta * ((lp_w - lr_w) - (lp_l - lr_l))
def dpo_loss(h): # standard DPO on observed (possibly flipped) labels
return -log_sigmoid(h)
def cdpo_loss(h, eps): # conservative DPO / label smoothing (biased)
return -(1 - eps) * log_sigmoid(h) - eps * log_sigmoid(-h)
def rdpo_loss(h, eps): # robust DPO (Chowdhury et al. 2024), unbiased for flip rate eps
return ((1 - eps) * -log_sigmoid(h) - eps * -log_sigmoid(-h)) / (1 - 2 * eps)
def flip_rate_from_agreement(agree):
"""Two raters, each flips the true label independently with prob eps:
agree = (1-eps)^2 + eps^2 -> eps = (1 - sqrt(2*agree - 1)) / 2."""
return (1 - np.sqrt(2 * agree - 1)) / 2
def majority3_error(eps):
return 3 * eps**2 * (1 - eps) + eps**3
def clean_equivalent(n, eps):
"""Effective clean sample size under symmetric flips (rDPO bound scales as 1/(1-2eps))."""
return n * (1 - 2 * eps) ** 2
if __name__ == "__main__":
# 1. Tie handling and margins
labels = [
{"item": 1, "a": "x1", "b": "y1", "choice": "a", "strength": "significant"},
{"item": 2, "a": "x2", "b": "y2", "choice": "b", "strength": "slight"},
{"item": 3, "a": "x3", "b": "y3", "choice": "tie", "strength": "negligible"},
]
assert len(to_pairs(labels, "drop")) == 2
pairs = to_pairs(labels, "half")
assert pairs[1] == ("y2", "x2", 1/3, 1.0) and pairs[2][3] == 0.5
# a tie with target 0.5 is minimised at equal scores
grid = np.linspace(-3, 3, 601)
assert abs(grid[np.argmin(bt_loss(grid, 0.0, 0.0, 0.5))]) < 1e-9
# 2. rDPO is unbiased: expected noisy loss equals clean loss
rng = np.random.default_rng(0)
h = rng.normal(0.5, 1.0, 200_000); eps = 0.17
flip = rng.random(h.size) < eps
h_obs = np.where(flip, -h, h)
clean = dpo_loss(h).mean()
print(f"clean {clean:.4f} dpo-on-noisy {dpo_loss(h_obs).mean():.4f} "
f"cdpo {cdpo_loss(h_obs, eps).mean():.4f} rdpo {rdpo_loss(h_obs, eps).mean():.4f}")
assert abs(rdpo_loss(h_obs, eps).mean() - clean) < 0.01
# 3. W1 numbers: agreement 72% on overlap
e = flip_rate_from_agreement(0.72)
print(f"implied flip rate {e:.3f}; majority-of-3 error {majority3_error(e):.3f}")
print(f"18,400 single labels ~ {clean_equivalent(18_400, e):,.0f} clean-equivalent")
print(f"per 3 labels: single x3 = {3*(1-2*e)**2:.2f}, one majority-of-3 = {(1-2*majority3_error(e))**2:.2f}")
assert 0.16 < e < 0.18
print("ok")
Output:
clean 0.5819 dpo-on-noisy 0.6671 cdpo 0.7231 rdpo 0.5821
implied flip rate 0.168; majority-of-3 error 0.075
18,400 single labels ~ 8,096 clean-equivalent
per 3 labels: single x3 = 1.32, one majority-of-3 = 0.72
ok
The tests check three things. A tie with target ½ is minimised at equal scores. Robust DPO on labels flipped with \(\varepsilon = 0.17\) recovers the clean loss (0.5821 against 0.5819), while plain DPO (0.6671) and conservative DPO (0.7231) do not: they optimise a different objective. And the W1 numbers reproduce: \(\varepsilon \approx 0.168\), about 8,100 clean-equivalent comparisons.
Export configuration for the W1 reward-model consumer, written next to the dataset and copied onto its data card:
consumer: reward_model
dataset: w1_coding_pairs@v3
group_by: prompt_id # all pairs of one prompt in one batch element
tie_policy: drop # 1,472 ties recorded, not trained on
margin: llama2_small # significant 1, better 2/3, slight 1/3, negligible 0
flip_rate_estimate: 0.168 # from 2,000 triple-labelled items, agreement 0.72
position_randomised: true # which response was shown as A is random per item
epochs: 1Debugging tips. If held-out accuracy on "negligibly better" pairs is far above chance, check for leakage between train and test prompts before celebrating. If the tie count in the training job differs from the export, the mapping from UI choice to chosen/rejected is wrong; the incident in the Operate level of this section is that bug. If robust DPO diverges, \(\varepsilon\) is set too close to ½, where the \(1/(1-2\varepsilon)\) factor explodes.
In production the consumer is a scheduled training job owned by another team, and the platform's job is to make sure the job sees what the data card says. Problems here are silent: a reward model trained on mis-encoded labels still trains, still reports a plausible accuracy, and quietly steers RL in the wrong direction. Reward-model overoptimisation makes this worse, because a policy pushed hard against a flawed proxy improves on the proxy while the true objective peaks and falls (Gao et al. 2022); ensembles of reward models reduce the effect, including under 25% synthetic label noise (Coste et al. 2023).
Monitors for a preference consumer.
- Export contract: row count, tie count and strength histogram in the training job equal the card's, within 0.5%.
- Sliced accuracy: held-out accuracy by strength level, by agreement bucket (unanimous, 2–1), by which model produced the chosen response, and by display position. Asymmetry between slices that should be symmetric is the earliest signal of an encoding error.
- Ensemble disagreement: for each pair, the spread of score gaps across a small ensemble; pairs that the ensemble confidently contradicts are candidates for re-labelling, following the voting idea of Wang et al. (2024).
- Invariance probes: pairs that differ only in whitespace or in a neutral rewording should score within a small gap.
Symptom. After W1 v2 entered the reward model, held-out accuracy overall was 68.4%, as expected, but sliced by source it was asymmetric: 74% on pairs where raters preferred the current checkpoint's response and 61% where they preferred the candidate's. On the previous dataset version the two slices were 68% and 69%. RL runs against the new reward model moved the candidate policy back toward the current checkpoint's style.
Measurements that separate causes. (1) Rater bias would show in the labels: the raw label share for the current checkpoint was 49%, unchanged. (2) A training bug would affect all datasets: the general-chat slice was symmetric. (3) An export bug would show in the contract: the training job contained 0 ties against 1,472 on the card, and 1,472 more "current checkpoint preferred" rows than the labels contain.
Root cause. A refactor of the export mapping turned the UI's "tie" into "A preferred", and the pair builder placed the current checkpoint's response in slot A by default before position randomisation was applied at display time. Every tie became a vote for the current checkpoint: 1,472 systematic labels, 8% of the data, all pointing one way.
Remedy, in order. (1) Roll the reward model back to the previous version (one config change). (2) Fix the mapping and make ties explicit in the schema rather than encoded through slot labels. (3) Re-export W1 as v3 and retrain in the next slot (1 day). (4) Add the export-contract check to the training job's start-up, failing the job if tie count or the current-vs-candidate label share differs from the card by more than 0.5 points.
Cost. One reward-model retrain and the RL runs launched against the bad model, about two days of RL compute in this scenario, plus the engineering to make the contract check blocking.
Validation. On v3 the slices returned to 68.3% and 68.7%, a difference well inside the 95% interval of about ±2.9 points for two independent 2,000-pair slices. Had the asymmetry remained after the fix, the hypothesis would have been wrong, and the next suspect would be a real style difference between checkpoints that the raters reward and the reward model over-learns, tested by an invariance probe on reformatted responses.
| Alert | Condition | Action |
|---|---|---|
| Export contract mismatch | |tiesjob − tiescard| / rows > 0.5% | block training job; page data-platform on-call |
| Slice asymmetry | |acc(current preferred) − acc(candidate preferred)| > 3 pt on ≥ 2,000 pairs each | freeze promotion of the RM; open investigation |
| Near-chance strength slice drift | acc on "negligible" pairs > 60% | check for train/test prompt leakage |
Table. Alert rules for a preference consumer. Thresholds are starting points sized to W1's evaluation slices.
The connection to the next section is direct: a consumer that uses the data correctly is a precondition for measuring its value. Every impact number assumes the export contract held.
Estimating data value
Human data is expensive, and its effect on a model is indirect. A platform that cannot say what a dataset contributed cannot decide whether to buy more of it, from whom, or whether to stop. Data value estimation answers that question with experiments and approximations, each trading cost for precision. The evidence that it matters is direct: when Ivison et al. separated the ingredients of preference learning (data, algorithm, reward model, prompts), the quality of the preference data had the largest effect, ahead of the choice between PPO and DPO (Ivison et al. 2024).
The quantity being estimated. Value is always relative to a metric and a baseline. The metric is usually one of: held-out accuracy of the reward model on a fixed set of human comparisons; a policy's win rate against a reference, judged by humans or a calibrated AI judge; or a task benchmark. The baseline is the training mix without the data. Value per dollar divides the change by the cost of the data.
Ablation. Train the consumer twice, with and without the dataset (or one source within it), and compare on the same evaluation items. This is the most trustworthy estimate, because it measures exactly the decision being made. It costs one extra training run per question, and its precision is limited by the size of the evaluation set: small effects need thousands of evaluation items to be distinguished from noise.
Scaling curve. Train on nested subsets of the dataset (an eighth, a quarter, a half, all of it) and plot the metric against the amount of data. The curve answers the purchasing question "what would the next batch buy?". Preference-model accuracy has been reported to rise roughly log-linearly with dataset size (Bai et al. 2022), and Llama 2's reward models had not saturated at their data scale (Touvron et al. 2023). On a log-linear curve, each doubling of data buys about the same gain, so the gain per added example falls as data grows.
Attribution. Ablation and scaling answer questions about whole datasets. Influence functions estimate the effect of each training example on a test prediction without retraining, using the gradient of the loss and the model's curvature (Koh & Liang 2017). Approximations make this feasible for large models: TRAK uses random projections and a handful of trained models (Park et al. 2023), and LESS selects instruction-tuning data by gradient similarity, finding that a selected 5% can often beat the full set (Xia et al. 2024). For human feedback specifically, influence functions have been used to find labeller biases in preference datasets and to guide labellers toward expert behaviour (Min et al. 2025). Attribution is cheap per example and approximate; it is best for ranking examples and finding bad ones, not for headline numbers.
Per-source value. A mix has several sources: vendors, rater populations, prompt categories, AI-labelled data. Data Shapley assigns each contributor its average marginal contribution over all orders in which contributors could be added (Ghorbani & Zou 2019). For individual examples it must be approximated; for a handful of sources it can be computed exactly, because \(K\) sources need only \(2^K\) training runs, 16 for four sources. A related line of work sets mixture weights directly: DoReMi tunes domain weights with a small proxy model (Xie et al. 2023), and data mixing laws predict performance from mixture proportions using small runs (Ye et al. 2024); both come from pretraining, and their transfer to preference data is an open question.
All W1 numbers here are illustrative. Ablation: a reward model trained on the full mix scores 68.5% on a pinned 4,000-pair coding evaluation set; without W1 it scores 64.5%. W1 is worth 4.0 points, about $18,900 per point at $75,780. Scaling: training with a quarter, half and all of W1 gives 66.5%, 67.5% and 68.5%, one point per doubling. A second campaign of the same size would add about one more point, at about $75,800 per point: four times the average cost. Per-source: with four sources (general chat preferences, W1, AI-labelled coding preferences, older coding preferences), exact Shapley credits W1 with about 7.1 of the 18.5 points the mix gains over chance.
Compared with judging data by its label quality alone, value estimation measures the thing that matters, a change in a model, and catches datasets that are clean but redundant. It costs training compute and evaluation effort, and it can mislead when the evaluation set does not reflect what the data was meant to improve. What you would actually do: run a leave-one-source-out ablation for every dataset above a size floor, alongside the consumer's scheduled retrain; build a scaling curve before any repeat purchase; use attribution to find bad examples, not to report value. Deviate toward full Shapley only when sources are few and the mix decision is expensive.
Ablation and its precision. Let \(Q(\mathcal{D})\) be the metric of a consumer trained on mix \(\mathcal{D}\) and \(S\) the dataset in question. The leave-out value is \(\Delta_S = Q(\mathcal{D}) - Q(\mathcal{D}\setminus S)\). When both models are scored on the same \(N\) evaluation pairs, define \(d_k \in \{-1, 0, 1\}\) for pair \(k\): +1 if only the model with \(S\) is right, −1 if only the one without is. Then \(\hat\Delta = \bar d\) and
\[ \mathrm{SE}(\hat\Delta) = \sqrt{\frac{p_+ + p_- - \hat\Delta^2}{N}}, \]where \(p_+\) and \(p_-\) are the fractions of pairs in each discordant direction. Pairing matters: only discordant pairs add variance. For a policy-level metric such as a win rate near 50%, \(\mathrm{SE} \approx 0.5/\sqrt{N}\), so a ±2-point 95% interval needs about 2,500 judged prompts.
On \(N = 4{,}000\) pairs, the model without W1 is right on 2,580 (64.5%); with W1, 240 more pairs become right and 80 become wrong, so 2,740 (68.5%). \(p_+ = 0.06\), \(p_- = 0.02\), \(\hat\Delta = 0.04\), \(\mathrm{SE} = \sqrt{(0.08 - 0.0016)/4000} \approx 0.0044\): 4.0 ± 0.9 points. To resolve a 1-point effect at the same discordance (SE ≤ 0.5 point), \(N \approx 0.08/0.005^2 = 3{,}200\) pairs suffice.
Scaling curve and marginal value. Fit \(Q(n) = a + b \ln n\) to nested subsets of size \(n\). Then each doubling adds \(b \ln 2\), and the marginal value of one more example is \(dQ/dn = b/n\). With unit cost \(c\), the marginal value per dollar is \(b/(n c)\), which falls as \(1/n\); the average value per dollar of the whole dataset is \(\Delta_S/(n c)\). Buying more is justified when the marginal value per dollar beats the best alternative use of the money, for example a new source whose own curve starts steeper.
Points (2,300, 65.5%), (4,600, 66.5%), (9,200, 67.5%), (18,400, 68.5%) give \(b = 0.01/\ln 2 \approx 0.0144\). At \(n = 18{,}400\), \(dQ/dn \approx 7.8 \times 10^{-7}\): 0.078 points per extra 1,000 comparisons. At $4.12 per useful comparison, 1,000 more cost $4,120, so the marginal cost is about $53,000 per point at the current size and rising; the next doubling (18,400 more, about $75,800) buys about 1 point. Compare the average: 4.0 points for $75,780.
Noise-adjusted value. If the consumer's gain depends on \(n_{\text{eff}} = n(1-2\varepsilon)^2\) rather than \(n\), then on a log-linear curve, cutting the flip rate is worth \(b \ln \frac{(1-2\varepsilon')^2}{(1-2\varepsilon)^2}\). Halving W1's implied \(\varepsilon\) from 0.168 to 0.084 multiplies \(n_{\text{eff}}\) by \((0.832/0.664)^2 \approx 1.57\), worth about \(0.0144 \ln 1.57 \approx 0.65\) points: two thirds of a doubling, if better guidelines or rater selection can deliver it. This is a model-based estimate that an ablation must confirm.
Influence. For a consumer with parameters \(\hat\theta\) minimising the average training loss \(\frac1n\sum_i \ell(z_i;\theta)\), with Hessian \(H = \nabla^2_\theta \frac1n\sum_i \ell(z_i;\hat\theta)\), removing example \(z_i\) changes the loss on test example \(z_t\) by approximately
\[ \Delta\ell(z_t) \approx \frac{1}{n}\, \nabla_\theta \ell(z_t;\hat\theta)^{\top} H^{-1}\, \nabla_\theta \ell(z_i;\hat\theta) \](Koh & Liang 2017). A positive value means removing \(z_i\) would raise test loss, so \(z_i\) helps. For a reward model, \(z_i\) is a comparison and \(z_t\) a held-out comparison; summing over a test set gives each training pair a score, and summing over a source gives a cheap source-level estimate. At LLM scale, \(H^{-1}\) is replaced by approximations (TRAK's projected kernel, or LESS's gradient cosine similarity), which preserve rankings better than magnitudes.
Shapley over sources. For sources \(\{1,\dots,K\}\) and value function \(V(S)\) (the metric when trained on the subset \(S\)),
\[ \phi_k = \sum_{S \subseteq \{1..K\}\setminus\{k\}} \frac{|S|!\,(K-|S|-1)!}{K!}\,\big[V(S\cup\{k\}) - V(S)\big], \]and the \(\phi_k\) sum to \(V(\text{all}) - V(\varnothing)\) (Ghorbani & Zou 2019). Leave-one-out value is the last term only; Shapley also credits a source for what it contributes in smaller mixes, which matters when sources overlap.
With illustrative accuracies for all 16 subsets of four sources, from 50% (empty mix, chance) to 68.5% (all four), Shapley gives general 3.86, W1 7.09, AI-labelled coding 4.28, older coding 3.28 points; they sum to 18.5. W1's leave-one-out value is 4.0 points, smaller than its Shapley value, because the AI-labelled coding source partly substitutes for it. Per $1,000, W1 returns 7.09/75.78 ≈ 0.094 Shapley points.
| Method | Question answered | Cost | Main failure mode |
|---|---|---|---|
| Leave-out ablation | did this dataset help the current mix? | 1 retrain + eval | underpowered evaluation set |
| Scaling curve | what would more of it buy? | 3–5 retrains | extrapolating beyond the fitted range |
| Source-level Shapley | how to split credit and budget across sources | \(2^K\) retrains (small proxy model) | proxy model ranks differ from full scale |
| Influence / TRAK / LESS | which examples help or hurt | gradients over train and test sets | approximation error in magnitudes |
Table. Data value methods compared.
What you would actually do: default to the ablation with a power calculation done before the run; add a scaling curve whenever a repeat purchase is on the table; run source-level Shapley on a small proxy reward model each quarter when the mix has at most five or six sources.
The module below implements the four estimators on the W1 numbers: a paired bootstrap ablation (inputs are two boolean arrays of shape \([N]\), one per model, marking which evaluation pairs each gets right), a log-linear scaling fit, exact source-level Shapley from a table of \(2^K\) subset scores, and influence functions on a small linear Bradley–Terry reward model, checked against actual leave-one-out retraining. The linear model stands in for a reward model's final layer on frozen features, the setting in which influence functions are exact enough to test.
# w1_value.py -- data value estimation for a preference dataset.
# python3 w1_value.py (numpy only)
import itertools, math
import numpy as np
# ---------- 1. Ablation with a paired bootstrap ----------
def paired_ablation(correct_with, correct_without, n_boot=5000, seed=0):
"""correct_*: bool arrays [n_eval], same held-out pairs scored by two RMs.
Returns delta accuracy and a 95% bootstrap interval."""
rng = np.random.default_rng(seed)
d = correct_with.astype(float) - correct_without.astype(float)
idx = rng.integers(0, d.size, (n_boot, d.size))
boots = d[idx].mean(axis=1)
return d.mean(), np.percentile(boots, [2.5, 97.5])
# ---------- 2. Log-linear scaling curve and marginal value ----------
def fit_loglinear(n, acc):
"""acc = a + b ln n, least squares. Returns (a, b)."""
X = np.column_stack([np.ones(len(n)), np.log(n)])
a, b = np.linalg.lstsq(X, np.asarray(acc), rcond=None)[0]
return a, b
def marginal_per_1k(b, n):
return 1000 * b / n # d acc / d n = b / n
# ---------- 3. Exact source-level Shapley ----------
def shapley(sources, value):
"""value: dict frozenset(sources) -> metric (e.g. RM accuracy). 2^K entries."""
K = len(sources); phi = {}
for s in sources:
others = [o for o in sources if o != s]; tot = 0.0
for k in range(K):
for S in itertools.combinations(others, k):
w = math.factorial(k) * math.factorial(K - k - 1) / math.factorial(K)
tot += w * (value[frozenset(S) | {s}] - value[frozenset(S)])
phi[s] = tot
return phi
# ---------- 4. Influence functions on a linear Bradley-Terry RM ----------
def sig(x): return 1 / (1 + np.exp(-x))
def train_bt(D, lam=1e-2, iters=50):
"""D: [n, d] feature differences phi(chosen) - phi(rejected). Newton's method."""
th = np.zeros(D.shape[1])
for _ in range(iters):
p = sig(D @ th)
g = -D.T @ (1 - p) / len(D) + lam * th
H = (D.T * (p * (1 - p))) @ D / len(D) + lam * np.eye(D.shape[1])
th -= np.linalg.solve(H, g)
return th, H
def test_loss(th, T): return -np.log(sig(T @ th)).mean()
def influence_remove(th, H, D, T):
"""Predicted change in test loss when each training pair is removed (Koh & Liang 2017):
delta_i ~ (1/n) * grad_test^T H^-1 grad_i."""
p_t = sig(T @ th); g_test = -(T.T @ (1 - p_t)) / len(T)
p = sig(D @ th); G = -D * (1 - p)[:, None] # per-example gradients [n, d]
return (G @ np.linalg.solve(H, g_test)) / len(D)
if __name__ == "__main__":
rng = np.random.default_rng(1)
# 1. ablation on 4,000 held-out coding pairs: mix with W1 vs mix without W1.
# without: 2,580 correct (64.5%); with: 2,740 (68.5%); 240 fixed, 80 broken.
without = np.zeros(4000, bool); without[:2580] = True
with_w1 = without.copy(); with_w1[2580:2820] = True; with_w1[:80] = False
d, ci = paired_ablation(with_w1, without)
print(f"ablation: delta {d*100:+.1f} pt, 95% CI [{ci[0]*100:+.1f}, {ci[1]*100:+.1f}]")
assert abs(d - 0.040) < 1e-12 and ci[0] > 0
# 2. scaling curve: rest of the mix + nested subsets of the 18,400 useful W1 comparisons
n = np.array([2300, 4600, 9200, 18400]); acc = np.array([0.655, 0.665, 0.675, 0.685])
a, b = fit_loglinear(n, acc)
print(f"fit: acc = {a:.3f} + {b:.4f} ln n; +{b*math.log(2)*100:.1f} pt per doubling; "
f"+{marginal_per_1k(b, 18400)*100:.3f} pt per extra 1k at n=18,400")
assert abs(b * math.log(2) - 0.010) < 1e-6
# 3. source-level Shapley over four sources (illustrative accuracies)
S = ["general", "w1_coding", "ai_coding", "legacy_code"]
V = {frozenset(): 0.50}
acc_tab = {("general",): .600, ("w1_coding",): .650, ("ai_coding",): .620, ("legacy_code",): .610,
("general","w1_coding"): .670, ("general","ai_coding"): .640, ("general","legacy_code"): .630,
("w1_coding","ai_coding"): .665, ("w1_coding","legacy_code"): .655, ("ai_coding","legacy_code"): .630,
("general","w1_coding","ai_coding"): .682, ("general","w1_coding","legacy_code"): .672,
("general","ai_coding","legacy_code"): .645, ("w1_coding","ai_coding","legacy_code"): .667,
("general","w1_coding","ai_coding","legacy_code"): .685}
V.update({frozenset(k): v for k, v in acc_tab.items()})
phi = shapley(S, V)
for s in S: print(f" shapley {s:12s} {phi[s]*100:+.2f} pt")
assert abs(sum(phi.values()) - (V[frozenset(S)] - V[frozenset()])) < 1e-12 # efficiency
# 4. influence vs actual leave-one-out on a small linear BT model
d_ = 8; w_true = rng.normal(size=d_)
def make(n):
X = rng.normal(size=(n, d_)); y = rng.random(n) < sig(X @ w_true)
return np.where(y[:, None], X, -X) # orient so row = chosen - rejected
D, T = make(400), make(2000)
th, H = train_bt(D); base_loss = test_loss(th, T)
pred = influence_remove(th, H, D, T)
idx = rng.choice(len(D), 40, replace=False); actual = []
for i in idx:
th_i, _ = train_bt(np.delete(D, i, axis=0)); actual.append(test_loss(th_i, T) - base_loss)
r = np.corrcoef(pred[idx], actual)[0, 1]
print(f"influence vs retrain (40 pairs): r = {r:.3f}")
assert r > 0.9
print("ok")
Output:
ablation: delta +4.0 pt, 95% CI [+3.2, +4.9]
fit: acc = 0.543 + 0.0144 ln n; +1.0 pt per doubling; +0.078 pt per extra 1k at n=18,400
shapley general +3.86 pt
shapley w1_coding +7.09 pt
shapley ai_coding +4.28 pt
shapley legacy_code +3.28 pt
influence vs retrain (40 pairs): r = 0.994
ok
The assertions check that the ablation interval excludes zero, that the fitted slope is one point per doubling, that Shapley values satisfy efficiency (they sum to the total gain), and that influence estimates track actual retraining (correlation 0.99 on 40 removed pairs). In a production version, train_bt is the scheduled reward-model training job and the value table is filled by a sweep of jobs keyed by source subset.
Sweep configuration for the source-level Shapley run on a small proxy reward model:
sweep: rm_source_shapley_2026q4
proxy_model: rm-small # same recipe, smaller base, 1 epoch
eval_set: code-pairs-4k@v2 # pinned
sources: [general, w1_coding, ai_coding, legacy_code]
subsets: all # 2^4 = 16 runs, empty set scored as 0.50
seeds_per_subset: 2 # average to reduce run-to-run noise
report: shapley, leave_one_out, value_per_1k_usdDebugging tips. If Shapley values do not sum to the total gain, a subset score is missing or duplicated. If influence estimates correlate poorly with retraining on a small model, check that the model is trained to convergence (influence assumes an optimum) and that the regulariser is included in the Hessian. If a scaling curve is flat at the low end, the smallest subset may be below the size at which the consumer learns anything; drop it from the fit rather than extrapolating from it.
Tracking data impact in production means every dataset gets a measured effect, attached to its data card, soon enough to change the next purchase. The design choice is to piggyback on the consumer's scheduled retrains: each scheduled reward-model run trains an extra arm with one source left out, rotating through sources, so ablations cost marginal compute and no extra coordination.
Dashboard panels and their formulas.
- Ablation delta per campaign: \(\hat\Delta\) with paired bootstrap 95% interval; a campaign is "measured" when the interval half-width is below a pre-registered threshold (1 point for W1-sized datasets).
- Scaling curve per source: slope \(b \ln 2\) per doubling with its standard error from the fit, and the predicted gain of the next purchase.
- Value per $1k: \(\hat\Delta / (C/1000)\) and quarterly Shapley per $1k, by source and by vendor.
- Quality covariates: implied flip rate, tie rate, share of low-margin pairs (strength "slightly" or "negligibly"), near-duplicate rate against the existing mix. These are what explain a disappointing delta.
Symptom. After W1's +4.0-point result, a follow-up campaign, W1-b, collected another 20,000 comparisons on the same spec and budget (about $75,800). The scaling curve predicted about +1.0 point. The ablation returned +0.1 point, 95% interval [−0.6, +0.8]: the data did not help, and the interval excludes the predicted gain.
Measurements that separate causes. Each candidate cause predicts a different covariate. (1) Underpowered evaluation: the interval half-width is 0.7 point, below the 1-point threshold, so the null result is real. (2) Noisier labels: overlap agreement was 71%, implied flip rate about 0.18, close to W1's 0.168. (3) Redundancy: 6% of W1-b prompts were near-duplicates of W1 prompts, too few to erase a 1-point gain. (4) Low-information pairs: 41% of W1-b comparisons were rated "slightly" or "negligibly" better, against 22% in W1. The reward model trained on W1-b alone scored 53% on its own low-margin held-out pairs, near chance, consistent with Llama 2's finding that such pairs carry little learnable signal (Touvron et al. 2023).
Root cause. W1-b sampled its response pairs from the current checkpoint and a candidate only a few hundred RL steps apart, so the two responses were often nearly the same. Raters were labelling noise between near-identical responses.
Remedy options and costs. (a) Regenerate pairs with more diversity: different checkpoints further apart, different sampling temperatures, or a best and worst of several samples; cost is generation compute only. (b) Filter candidate pairs before labelling by the score gap of a reward-model ensemble, skipping pairs the ensemble rates as near-identical; cost is scoring compute, plus the risk of filtering out exactly the hard pairs the model most needs, so keep a 10% unfiltered sample. (c) Weight by strength or use margins at training time; this salvages W1-b without new labels, but Llama 2's margin gains were well under a point. The chosen remedy was (a) with (b) as a guard, plus (c) for the existing W1-b data.
Validation. A 2,000-pair pilot cannot show a sub-point accuracy gain, so the pilot was judged on the covariate that explained the failure: the low-margin share fell from 41% to 20%, close to W1's 22%. The full campaign then had to pass the real test, an ablation interval excluding zero and overlapping the scaling curve's prediction. If the low-margin share had fallen but the ablation stayed flat, the hypothesis would have been weakened and redundancy with the AI-labelled coding source, which Shapley showed partly substitutes for W1, would be the next suspect.
Runbook: "data didn't help".
- Check power: interval half-width against the pre-registered threshold. If wider, enlarge the evaluation set before concluding anything.
- Check the export contract (previous section). A mis-encoded dataset looks like a useless one.
- Compare covariates with the last dataset that helped: flip rate, tie rate, low-margin share, near-duplicate rate, prompt-category mix.
- Check the evaluation set matches the intended effect: a coding-preference dataset should be judged on coding pairs, not a general mix.
- Run attribution on a sample: if influence scores for the new data are near zero or negative, inspect the top negative examples by hand.
- Decide: fix and re-collect (cause found), stop buying this source (curve flat), or re-weight in the mix (useful but redundant).
The connection to the next section: a measurement that arrives three weeks after the data does is a measurement that informs the campaign after next. Fast impact tracking depends on a fast path into the mix.
The request-to-mix path
Request-to-mix latency is the elapsed time from the moment a researcher asks for data to the moment that data is in the training mix of a model the researcher can evaluate. It is the platform's cycle time for research: a team with a 21-day path can test about one data idea every three weeks per campaign slot; a team with a 7-day path can test three. Because data ideas are often wrong, the number of ideas tested matters more than the polish of any one.
The path crosses many owners: the researcher, the platform team, guideline writers, a vendor's rater pool, quality reviewers, the export pipeline and the training team. Each owner sees only its own stage and usually optimises its own work time. The time that matters, though, is mostly spent between stages: in queues, waiting for a batch to fill, waiting for a meeting, waiting for a weekly training slot. No single owner sees that time, so no one removes it.
Value-stream mapping is the standard tool for this problem. It comes from the Toyota Production System, where it was called a material and information flow diagram, and was popularised by the workbook Learning to See (Lean Enterprise Institute). A value-stream map draws every step from order to delivery and, for each step, records two numbers: process time, when someone or something is actually working on the item, and lead time, the elapsed time the step occupies including waiting. A current-state map shows how work flows today; a future-state map shows how it should flow. The ratio of total process time to total lead time, the flow efficiency, is typically low, and the gap is where the fixes are.
The map leads to a bottleneck analysis. A bottleneck (or constraint) is the stage whose capacity limits how fast work can move. On the request-to-mix path, most stages are not capacity-bound at all: scoping, guideline writing, QA review and export take hours of work but days of calendar, so their lead time is waiting and can be cut without more people. One stage, collection, is capacity-bound: its duration is the labelling work divided by the rater-hours available. Shortening it requires more rater-hours, less work per item, or fewer items.
Where the waiting comes from, in roughly the order it is usually found:
- Batch hand-offs. QA starts only when collection ends; export starts only when QA ends. Streaming each item through checks as it is labelled turns these stages into short tails.
- Fixed cadences. A reward model retrained once a week makes data wait, on average, half a week for the next run, regardless of how fast everything else was.
- Synchronous approvals. Scoping by meeting and guideline sign-off by email add days of calendar to hours of work. A campaign template with validation (Chapter 3's launcher) turns most of this into a form.
- Serial pilots. A pilot round that waits for a vendor slot, then for analysis, then for a second round, can take as long as collection. A one-day pilot on a pre-generated sample buffer, with automatic agreement and timing reports, keeps calibration without the wait.
Baseline: scoping 3 days, guidelines and pilot 4, collection 6, QA 3, export 2, reward-model retrain and mix inclusion 3: 21 days. Assumed process times are 0.5, 1.5, 4.4, 0.5, 0.25 and 1.0 days, 8.15 days in total, so flow efficiency is 39%. Collection needs about 1,895 rater-hours (25,260 assignments at a mean of 4.5 minutes) from a pool of 3,000 rater-hours a week, 4.4 days of the whole pool; it is the constraint. Future state: scoping 0.5 day from a template, a 1-day pilot, collection 4.0 days with about 10% more rater-hours scheduled, QA and export streaming behind collection and finishing a quarter-day each after it, and a pre-booked 1-day retrain slot: 7 days.
Compared with the usual instinct, which is to speed up the visible work (faster labelling, faster training), the value stream shows that most of the calendar is not work. The fixes are organisational and architectural: streaming instead of batches, slots instead of cadences, templates instead of meetings. What you would actually do: instrument every stage with start and finish timestamps, draw the current-state map from data rather than recollection, remove the largest wait first, and only then buy capacity for the constraint. Deviate from this order only when the constraint is so tight that even a perfect flow misses the target, as with W1, where the last 0.4 day comes from scheduling more rater-hours.
Lead time and flow efficiency. For stages \(i = 1..m\) with process time \(p_i\) and waiting \(w_i\), a sequential path has \(T = \sum_i (p_i + w_i)\) and flow efficiency \(\eta = \sum_i p_i / T\). When stages overlap, \(T\) is the length of the critical path, the longest chain of dependent work, and stages off the critical path do not add to \(T\).
The constraint. Collection of \(A\) assignments at mean handling time \(\bar t\) (hours) with \(C\) rater-hours per day available takes
\[ T_{\text{collect}} = \frac{A\,\bar t}{C}. \]The mean, not the median, belongs here, because capacity is consumed by total time. Gold items and overlap labels are part of \(A\): they are the price of quality measurement.
\(A = 25{,}260\), \(\bar t = 4.5/60\) h, so \(A\bar t \approx 1{,}895\) rater-hours. With 3,000 rater-hours a week, \(C = 3000/7 \approx 429\) per day and \(T_{\text{collect}} \approx 4.42\) days. To hit 4.0 days, \(C\) must be \(1{,}895/4.0 \approx 474\) per day, 3,316 a week: about 10.5% more scheduled hours from the same 150 raters (about 22 instead of 20 hours a week each) or about 16 more raters. The labour cost is unchanged at about $75,780, because the work is the same; only its calendar density changes.
Cadence waits. A stage that runs every \(P\) days, receiving work at a uniformly random moment, imposes a mean wait of \(P/2\). A weekly retrain adds 3.5 days on average; a daily one adds half a day; a slot booked when the campaign is launched adds close to zero, at the cost of reserving training capacity that may sit idle if the data is late.
Queues at shared resources. When a stage is a shared resource (QA reviewers, the training cluster), its waiting time grows sharply with utilisation. Kingman's approximation for a single-server queue gives mean wait \(W_q \approx \frac{\rho}{1-\rho}\cdot\frac{c_a^2 + c_s^2}{2}\cdot \bar s\), where \(\rho\) is utilisation, \(\bar s\) the mean service time and \(c_a, c_s\) the coefficients of variation of inter-arrival and service times (Kingman's formula). At \(\rho = 0.9\) the factor \(\rho/(1-\rho)\) is 9; at \(\rho = 0.7\) it is 2.3. A review team kept 90% busy is a review team with a queue. Little's law, \(L = \lambda W\), links the number of requests in flight \(L\), their arrival rate \(\lambda\) and the time each spends in the system \(W\) (Little 1961); at fixed throughput, halving lead time halves the work in progress, and with it the number of campaigns competing for the same raters.
Streaming. If QA processes each labelled batch as it arrives, it finishes a tail \(\tau_{QA}\) after collection ends, and export a tail \(\tau_{\text{ex}}\) after QA ends. The path becomes
\[ T = T_{\text{scope}} + T_{\text{pilot}} + T_{\text{collect}} + \tau_{QA} + \tau_{\text{ex}} + T_{\text{train}}. \]Future state: \(0.5 + 1.0 + 4.0 + 0.25 + 0.25 + 1.0 = 7.0\) days. With the current pool (collection 4.42 days), the same flow gives 7.42 days, which misses the target; that is why capacity is part of the plan. Every stage on the future critical path is process time, so the remaining waiting on that path is essentially zero, and further cuts need either more rater-hours or less work per useful comparison.
| Stage | Baseline (d) | Future (d) | Fix | Cost / trade-off |
|---|---|---|---|---|
| Scoping | 3 | 0.5 | campaign template + validating launcher; async review | template upkeep; unusual requests still need a meeting |
| Guidelines + pilot | 4 | 1.0 | guideline library; 1-day pilot on pre-generated buffer; auto agreement/timing report | one calibration round instead of two; guideline v2 ships mid-collection if needed |
| Collection | 6 | 4.0 | reserve rater capacity at launch; +10.5% scheduled hours | reservation can idle if launch slips |
| QA | 3 | tail 0.25 | inline gold checks; rolling review of each batch | reviewers must be staffed during collection |
| Export | 2 | tail 0.25 | incremental, validated export per batch | more pipeline runs; contract checks per batch |
| RM retrain + mix | 3 | 1.0 | slot booked at launch; automatic evaluation gate | reserved training capacity |
| Total | 21 | 7.0 | QA and export overlap collection, so they add only their tails | |
Table. W1 bottleneck analysis: baseline, future state and the fix for each stage (illustrative).
What you would actually do: attack waits in order of size (here collection's ramp, pilot rounds, batch QA, cadence), then size the constraint with \(T_{\text{collect}} = A\bar t / C\). If the target is still missed, reduce \(A\) (smaller overlap or gold share, if quality measurement allows) or \(\bar t\) (interface work, Chapter 5) before buying more \(C\).
The model below encodes the value stream as a list of stages, each with process time, lead time, its predecessor and a link type: fs (finish-to-start, the stage starts when its predecessor finishes) or ff (finish-to-finish, the stage streams behind its predecessor and finishes a tail after it). It computes the schedule, lead time and flow efficiency, sizes collection from assignments and capacity, and checks the baseline (21 days) and the future state (7.0 days).
# w1_vsm.py -- value-stream model of the request-to-mix path.
# python3 w1_vsm.py (stdlib only)
from dataclasses import dataclass
@dataclass
class Stage:
name: str
touch: float # process (hands-on or machine) time, days
lead: float # elapsed time the stage occupies on its own, days
after: str = None # predecessor stage
link: str = "fs" # "fs": starts when predecessor finishes;
# "ff": streams behind predecessor, finishes `lead` after it
def schedule(stages):
"""Returns {name: (start, finish)} and the overall lead time."""
t = {}
for s in stages:
if s.after is None:
start, fin = 0.0, s.lead
elif s.link == "fs":
start = t[s.after][1]; fin = start + s.lead
else: # streaming: overlaps predecessor
start = t[s.after][0]; fin = t[s.after][1] + s.lead
t[s.name] = (start, fin)
return t, max(f for _, f in t.values())
def flow_efficiency(stages, lead):
return sum(s.touch for s in stages) / lead
def collection_days(assignments, mean_min, rater_hours_per_week):
return assignments * mean_min / 60 / (rater_hours_per_week / 7)
def cadence_wait(period_days):
"""Work arriving at a random time waits on average half the period for a fixed-cadence job."""
return period_days / 2
BASELINE = [
Stage("scoping", 0.5, 3.0),
Stage("guidelines_pilot", 1.5, 4.0, "scoping"),
Stage("collection", 4.4, 6.0, "guidelines_pilot"),
Stage("qa", 0.5, 3.0, "collection"),
Stage("export", 0.25, 2.0, "qa"),
Stage("rm_retrain_mix", 1.0, 3.0, "export"),
]
def future(collect_days):
return [
Stage("scoping", 0.5, 0.5), # template spec + launcher
Stage("guidelines_pilot", 1.0, 1.0, "scoping"), # guideline library, 1-day pilot
Stage("collection", collect_days, collect_days, "guidelines_pilot"),
Stage("qa", 0.5, 0.25, "collection", "ff"), # inline gold + rolling review
Stage("export", 0.25, 0.25, "qa", "ff"), # incremental export
Stage("rm_retrain_mix", 1.0, 1.0, "export"), # pre-booked slot, auto eval gate
]
if __name__ == "__main__":
t, lead = schedule(BASELINE)
print(f"baseline lead {lead:.1f} d, touch {sum(s.touch for s in BASELINE):.2f} d, "
f"flow efficiency {flow_efficiency(BASELINE, lead):.0%}")
assert lead == 21.0
hours = 25_260 * 4.5 / 60
c_now = collection_days(25_260, 4.5, 3_000)
c_need = 4.0; cap_need = hours / c_need * 7
print(f"collection: {hours:,.0f} rater-h -> {c_now:.2f} d at 3,000 h/wk; "
f"{c_need} d needs {cap_need:,.0f} h/wk (+{cap_need/3000-1:.1%})")
for c in (c_now, collection_days(25_260, 4.5, cap_need)):
t, lead = schedule(future(c))
print(f"future with collection {c:.2f} d -> lead {lead:.2f} d; "
+ ", ".join(f"{k} {v[0]:.2f}-{v[1]:.2f}" for k, v in t.items()))
assert abs(lead - 7.0) < 1e-9
print(f"weekly retrain cadence adds {cadence_wait(7):.1f} d mean wait; daily adds {cadence_wait(1):.1f} d")
print("ok")
Output:
baseline lead 21.0 d, touch 8.15 d, flow efficiency 39%
collection: 1,894 rater-h -> 4.42 d at 3,000 h/wk; 4.0 d needs 3,315 h/wk (+10.5%)
future with collection 4.42 d -> lead 7.42 d; scoping 0.00-0.50, guidelines_pilot 0.50-1.50, collection 1.50-5.92, qa 1.50-6.17, export 1.50-6.42, rm_retrain_mix 6.42-7.42
future with collection 4.00 d -> lead 7.00 d; scoping 0.00-0.50, guidelines_pilot 0.50-1.50, collection 1.50-5.50, qa 1.50-5.75, export 1.50-6.00, rm_retrain_mix 6.00-7.00
weekly retrain cadence adds 3.5 d mean wait; daily adds 0.5 d
ok
The model needs real stage times, so the platform must emit an event at every stage boundary. The schema below is the minimum: one event per transition, keyed by campaign, with the actor and the reason for any wait.
# stage_event.schema.yaml
type: object
required: [campaign_id, stage, event, at]
properties:
campaign_id: {type: string} # e.g. w1
stage:
enum: [scoping, guidelines_pilot, collection, qa, export, rm_retrain_mix]
event:
enum: [queued, started, blocked, unblocked, finished]
at: {type: string, format: date-time}
actor: {type: string} # team or service that acts next
blocked_reason: # required when event == blocked
enum: [awaiting_review, awaiting_vendor_slot, awaiting_training_slot,
awaiting_batch, schema_error, capacity, other]
items_done: {type: integer} # for streaming stages: progress counter
Process time for a stage is the sum of started→blocked/finished intervals; waiting is everything else between queued and finished. Summed per blocked_reason across campaigns, these give the waste ranking that orders the fixes by the waiting each one removes.
In the baseline, the events show the QA stage queued on day 13 and started only on day 15 with reason awaiting_batch (the full dataset), and the retrain stage blocked with awaiting_training_slot for 2 of its 3 days. Those two reasons account for 4 of the 12.85 waiting days and are the first two fixes in the table.
Debugging tips. If the model's lead time disagrees with the timestamps, a stage boundary is missing an event, usually queued, so waiting time is mis-attributed to the previous stage. If future-state flow efficiency comes out above 100%, stages overlap and the calculation is summing process time across parallel streams; report critical-path waiting instead.
Operating the path means holding a latency budget per stage and noticing quickly when one stage eats another's share. The budget comes from the future-state map; alerts fire on the stage that overruns, not on the total, because by the time the total is late, the cause is days old.
| Stage | Budget (d) | Indicator | Alert |
|---|---|---|---|
| Scoping | 0.5 | request opened → spec validated | > 1 d |
| Guidelines + pilot | 1.0 | spec validated → pilot report accepted | > 1.5 d |
| Collection | 4.0 | items/day vs. plan (\(C / \bar t\)) | throughput < 85% of plan for 12 h |
| QA tail | 0.25 | last label → last batch reviewed | review backlog > 0.5 d of labels |
| Export tail | 0.25 | last review → validated export | any contract failure |
| RM retrain + mix | 1.0 | export → in mix with eval gate passed | slot not confirmed 48 h before needed |
| End to end | 7.0 | request → in mix | p50 > 7 d or p90 > 10 d over trailing 8 campaigns |
Table. Request-to-mix latency budget and alert rules for W1-sized campaigns (illustrative).
Dashboard. One row per active campaign showing a Gantt of actual stage intervals against budget, the current blocked reason, and a burn-up of collected items against plan. Below it, a waste chart: total waiting days per blocked_reason over the last quarter, which is the backlog for platform work.
Symptom. A W1 rerun was planned for 7 days. On day 3 the collection burn-up was at 61% of plan; the stage alert fired after 12 hours below 85%. Projected end-to-end: about 9.5 days.
Measurements that separate causes. (1) Slower labelling: median handling time was 4.1 minutes, unchanged from 4.0, so \(\bar t\) had not moved. (2) Fewer rater-hours: active rater-hours were 290 a day against 474 planned. (3) Generation outage: the pre-generated buffer held more than 1,800 pairs throughout, so raters were never starved. Cause (2): the same vendor pool had been assigned a second campaign at equal priority, and the router split raters between the two.
Diagnosis in numbers. Collection started on day 1.5, so by day 3 it had run 1.5 days at about 290 rater-hours a day: about 435 of the 1,895 rater-hours, 23% of the work against a plan of 1.5/4.0 = 37.5% (61% of plan). The remaining 1,460 rater-hours at 290 a day need 5.0 more days, ending collection on day 8.0 instead of 5.5; with the two quarter-day tails and the 1-day retrain, the data reaches the mix on day 9.5.
Remedy options. (a) Raise W1's priority in the router so it takes its reserved 474 rater-hours a day: the remaining 1,460 hours finish in 3.1 days, ending collection on day 6.1 and reaching the mix on day 7.6, and the other campaign slips by the same hours. (b) Add a second vendor's qualified raters: no slip for the other campaign, but onboarding and qualification take longer than the days saved. (c) Reduce \(A\) by cutting the overlap share for the remainder from 10% to 5%: over a whole campaign this would save 2,000 assignments; applied to the 77% of work still to do, it saves about 1,540, roughly 115 rater-hours or 8% of the remaining hours, and weakens the flip-rate estimate. The team chose (a), because the reservation existed precisely to make this decision mechanical, and recorded the miss as a planning failure: two campaigns were launched against one pool without a capacity check.
Runbook steps added.
- At launch, reserve rater-hours per day equal to \(A\bar t / T_{\text{collect}}\); the launcher refuses a launch whose reservation exceeds the pool's free capacity.
- If throughput < 85% of plan for 12 h: check \(\bar t\), active rater-hours and buffer depth, in that order.
- If rater-hours are short because of a competing campaign: enforce the reservation; if there is no reservation, escalate to the owners of both campaigns with the projected slip of each option.
- If \(\bar t\) has risen: check for an interface or guideline change in the last 24 hours (Chapter 5's interface experiments apply).
- If the buffer is empty: follow the buffer-runway runbook (Chapter 11).
Validation. After the change, the 4 campaigns launched under reservations had collection stages within 10% of budget. If campaigns had kept overrunning with reservations in place, the binding problem would be the estimate of \(\bar t\), not capacity, and the next fix would be to size reservations from the pilot's measured mean rather than from the spec.
Latency and value close the loop of this book's platform: a short path makes impact measurements arrive while they can still change the next campaign, and a measured impact tells the platform which requests deserve the fast path at all.
AI in the Loop
Every earlier chapter treated the human as the source of the label and the model as the thing being labelled. By 2026 that picture is incomplete. Models now sit inside the feedback loop in three distinct roles. They assist human annotators: they pre-fill a label, write a critique that points at a suspected bug, or fetch the documentation and test results a rater needs. They replace humans on part of the work: an AI judge labels every item first, and only the items it is unsure about go to people. And they threaten the data from inside: annotators who paste a chatbot's answer into a free-text field produce labels that look human but are not.
Each role changes what a label means. An assisted label is a joint product of the person and the assistant, and a rater who sees the model's opinion first tends to agree with it; that is anchoring, and it can be measured. An AI label is cheap and consistent but carries the judge's own biases into the reward model. An undisclosed LLM-written label is the worst case: it costs human prices and carries AI biases while being recorded as human. The chapter takes the three roles in order. Model-assisted annotation covers pre-labels, critique assistance and retrieval, and how to measure the anchoring they cause. AI judges and routing covers RLAIF as a first pass and the cost and quality math of deciding which items humans still see. The boundary covers where humans remain essential and how to keep human data human.
The mental model to carry: AI in the loop is a division of labour with a measurement contract. Every AI contribution is allowed only where a human-labelled measurement says it is at least as good as the human work it displaces, and every label records which contributions it received.
The design question in this chapter is economic and statistical at once: for each item, which mix of model and human effort produces a label of acceptable quality at the lowest cost, and how is that quality shown to be acceptable? Three quantities frame it, all evaluated on the reference workloads.
| Quantity | Meaning | Reference workload (illustrative) | Section |
|---|---|---|---|
| Follow-wrong rate | How often raters choose the answer the assistance points to when that answer is wrong, by arm | W1 sizing: 138 AI-wrong gold items per arm to detect 20% → 35% | Assist |
| Coverage \(\kappa\) at a quality bar | Share of items whose AI label is kept while agreement with humans stays at the human–human level | W1: \(\kappa = 0.56\) at a 0.72 agreement bar | Judge |
| Cost per useful label | All-in cost including judge calls and human audits | W1: $4.12 all-human → about $1.99 routed | Judge |
| Human-provenance share | Share of labels that can be shown to be human-produced | W3: rubric drafts flagged by two independent signal families | Boundary |
Table. The quantities this chapter derives. Running-example values are illustrative workload figures, not published results; published numbers are cited where they appear.
What you would actually do: treat each AI role as a separately versioned component with its own experiment arm, its own calibration set of human labels, and its own field in the label's provenance record. The default is to keep the AI's verdict away from the rater, to let a calibrated judge take only the items where it matches human agreement, and to accept no free-text human data without behavioural telemetry.
This chapter's code is a small package, w1_ai, that adds the three AI roles to the platform built in earlier chapters. Each module has tests that assert the running-example numbers, and all of them were run (13 tests, Python 3, pytest).
w1_ai/
assist.py # r-ai-assist: Suggestion, AssistPolicy, assign_arm(), anchoring_report(), n_per_arm()
router.py # r-ai-judge: judge_confidence(), wilson_lcb(), calibrate_threshold(), route(), campaign_cost()
provenance.py # r-ai-boundary: Provenance, summarize_events(), max_overlap(), assess()
w1_ai_policy.yaml # campaign-level AI policy, versioned with the campaign spec
tests/
test_assist.py # arm shares, sample size 138, follow-wrong detection
test_router.py # single-rater accuracy 0.832, calibration, cost $36,569, policy file
test_provenance.py # typed rubric passes, pasted LLM rubric flagged, paste alone not flagged
The interfaces are deliberately narrow. The assistance layer only produces Suggestion records and an arm per (rater, item); the rater UI decides how to render them. The router only consumes a confidence and a calibrated threshold; it does not know which model produced them. The provenance module only consumes editor events and text; it never deletes data, it raises flags for review. Keeping them separate is what lets each be tested, versioned and rolled back on its own.
In production, AI components fail differently from human workforces. A human pool degrades gradually: fatigue, drift, a few bad actors. An AI component changes discontinuously when someone bumps a model version, and the change propagates to every item at once. The operational stance this chapter builds toward is therefore: pin every model that touches a label, treat a version change as a new experiment arm, and keep a permanent human-labelled stream that can detect a change within a day.
The three sections each end with a worked incident on the reference workloads: a critique-model upgrade that silently raised anchoring in W1, a judge whose agreement collapsed when the candidate checkpoint began writing longer answers, and a cohort of W3 rubric drafts that turned out to be LLM-written. Each incident is detected by a metric defined in this chapter (follow-wrong rate on decoys, rolling audit lower bound, two-family provenance flags), and each remedy has a cost computed in the same units as the rest of the book: dollars, rater-hours and days of request-to-mix latency.
Model-Assisted Annotation
Model-assisted annotation means showing a human annotator something a model produced, while the human still makes the final call. It exists because unassisted human review stops scaling once model outputs become long, technical or subtly wrong. A rater comparing two 80-line Python answers can read both, but may not notice that one silently mishandles an empty list. A model can point at that line in a second.
There are three kinds of assistance, and they differ in how much of the decision they hand to the model.
- Pre-labels (verdicts). The model proposes the answer to the very question being labelled: "B is better", or "this span is a person's name". Annotation tools support this directly; Label Studio imports model predictions with a model version and a score, and Argilla attaches suggestions with a value, a confidence score and the producing agent. Pre-labels save the most time on mechanical tasks such as entity spans, and they anchor the most on judgement tasks.
- Critique assistance. The model writes evidence rather than a verdict: "line 14 dereferences a possibly-null pointer", "the summary omits the second finding". The human checks each claim and decides. Saunders et al. (2022) found that labellers given model-written critiques found 50% more flaws in summaries than an unassisted group. McAleese et al. (2024) trained CriticGPT, a GPT-4-based model fine-tuned with RLHF to write critiques of code; contractor critiques written with CriticGPT's help were preferred over unassisted contractor critiques about 60% of the time.
- Retrieval of context. The model or the platform fetches material the rater needs but would not look up: the result of running the code's tests, the API documentation for a function, the statute a legal answer cites. This informs without telling the rater what to conclude.
End to end, the mechanism runs like this. When the platform pre-generates a sample for annotation (the buffer described in earlier chapters), it also calls the assistance models and stores their outputs as separate records, each tagged with the model version. When a rater opens the item, the platform decides by a deterministic hash whether this item is shown with assistance or without; most items get assistance, a fixed share does not. The rater UI renders critiques as highlights on the response and retrieval results in a side panel. The rater labels as usual. The stored label records which assistance was shown. A monitor then compares the two arms.
The risk is anchoring: people adjust insufficiently away from a starting point they were given. In annotation this shows up as raters agreeing with the model more than they would have on their own, including when the model is wrong. It has been measured. In a pre-registered study with 410 crowd annotators, Schroeder et al. (2025) found that showing GPT-4 label suggestions raised how often the LLM's label matched the human majority from 40% to between 81% and 87%, and raised unanimous agreement among five annotators from 8% to 38% when suggestions were pre-highlighted. Assistance did not speed annotation in that study, and an LLM evaluated against the assisted labels looked far better than against unassisted ones. Critiques have their own failure mode: McAleese et al. (2024) report that critic models still produce hallucinated bugs and nitpicks at rates the authors call quite high, and a rater who trusts them penalises correct code.
W1 collects 20,000 pairwise comparisons of coding answers from 150 vendor raters at a mean 4.5 minutes per label. Three assistance options are on the table. A verdict pre-label ("judge prefers B, 0.78") would be fastest but directly anchors the preference being collected. A CriticGPT-style critique highlights suspected bugs in each response. Retrieval runs each response's code against the prompt's unit tests and shows pass/fail. W1 adopts critique plus retrieval, withholds the verdict, keeps 20% of regular items unassisted as a permanent control, and splits gold items 50/50 so anchoring can be measured on items with known answers.
Compared with its predecessor, unassisted review with a written guideline, assisted review moves the bottleneck from finding problems to verifying claims about problems. That is usually a good trade on technical content, where finding is hard and verifying is easy. What it costs is independence: two assisted raters are no longer independent measurements, because they saw the same critique, so inter-rater agreement rises without accuracy necessarily rising.
What you would actually do. Default to evidence-type assistance (critique and retrieval) and withhold verdicts on the label being collected. Deviate, and show pre-labels, only for mechanical tasks where the label is checkable and anchoring is cheap to measure, such as span boundaries. Always keep an unassisted arm, because without it anchoring is invisible.
Assistance is worth adding when it reduces cost per useful label or raises accuracy, without introducing a bias the reward model will learn. Each of those three effects needs its own measurement, and the design choice is which assistance to show, to whom, and how to keep the measurement possible.
Design options.
| Option | What the rater sees | Expected gain | Anchoring risk | When to choose |
|---|---|---|---|---|
| Verdict pre-label | Model's answer to the label question, with score | Large on mechanical tasks | Highest: directly on the target label | Spans, classification with a checkable answer |
| Critique | Claimed flaws, located in the response | More flaws found (Saunders et al. 2022: +50%) | Medium: false claims shift preferences | Code, math, long-form factual answers |
| Retrieval / execution | Test results, docs, sources | Fewer missed facts | Low, if results are correct | Whenever ground facts are fetchable |
| None | Response only | Baseline | None | Control arm; tasks measuring raw human preference |
Table. Assistance options. The critique gain is from Saunders et al. (2022) on summaries; other entries are qualitative design guidance.
Measuring anchoring. Define, for each item \(i\), the gold label \(g_i\), the label the assistance points to \(s_i\) (for a critique, the response it implies is worse), and the human label \(h_i\). The quantity that matters is the follow-wrong rate, the probability that a rater picks the assistance's answer on items where that answer is wrong:
\[ F_{\text{arm}} = \Pr\left(h_i = s_i \mid s_i \neq g_i,\ \text{arm}\right). \]In the control arm the assistance is computed but not shown, so \(F_{\text{control}}\) is simply the rate at which raters, unaided, make the same mistake the model makes. Anchoring is the difference \(\Delta F = F_{\text{assisted}} - F_{\text{control}}\). Plain agreement with the model is not a valid measure: it rises both when raters are anchored and when the model is right, which is exactly the confusion that made the LLM look better in the study by Schroeder et al. (2025).
Items where the model is wrong are rare if the model is good, so a platform plants them: a decoy is a gold item whose critique has been edited to contain one false claim. Decoys guarantee a supply of \(s_i \neq g_i\) items with known answers.
Sample size. To detect a rise from \(p_1\) to \(p_2\) with a two-sided test at significance \(\alpha\) and power \(1-\beta\), each arm needs about
\[ n = \frac{\left(z_{1-\alpha/2}\sqrt{2\bar p(1-\bar p)} + z_{1-\beta}\sqrt{p_1(1-p_1)+p_2(1-p_2)}\right)^2}{(p_2-p_1)^2},\qquad \bar p = \tfrac{p_1+p_2}{2}, \]where \(z\) are standard normal quantiles (1.96 for \(\alpha = 0.05\), 0.84 for 80% power).
W1 wants to detect a follow-wrong rise from \(p_1 = 0.20\) to \(p_2 = 0.35\). Then \(\bar p = 0.275\), the numerator is \((1.96 \times 0.631 + 0.84 \times 0.623)^2 \approx 3.10\), and \(n \approx 3.10 / 0.0225 \approx 138\) AI-wrong gold items per arm. W1 has 5% gold, about 1,263 gold assignments. With the regular 20/80 split only about 253 gold items reach the control arm, too few once restricted to AI-wrong ones. Splitting gold 50/50 gives about 632 per arm; with 30% of gold items carrying a decoy, that is about 190 decoys per arm, enough on decoys alone.
Cost. Assistance pays when the time saved exceeds the model cost and any accuracy loss. With rater cost \(r\) per hour, time per label \(t\), and model cost \(m\) per item, the per-label change is \(\Delta c = r\,\Delta t + m\). Time savings are not guaranteed: in the Schroeder et al. study, assisted annotation took longer (54.3 s unassisted versus 66 to 91 s assisted, depending on condition).
At $40/h and 4.5 min mean, a W1 label costs $3.00 in rater time. If critique assistance cut mean time to 3.6 min (an assumption the pilot must test), the saving is $0.60 per label, about $15,000 across 25,260 assignments, against perhaps a few cents per item of critic inference. If instead time rose to 5.0 min, as in the slower conditions above, the cost rises by about $0.33 per label and the case rests entirely on accuracy: more bugs caught per comparison.
Randomization unit. Assigning arms per item within a rater gives the most statistical power, since each rater serves as their own control, but raters learn from critiques, so the control arm is contaminated over time. Assigning per rater avoids that but leaves 30 control raters out of 150 and inflates variance by rater effects. The recommended default is per item, with a periodic per-rater check (a week where a random 20% of raters see no assistance) to bound the learning spillover.
Friction and error type. How the interface handles disagreement with a suggestion changes acceptance. In a 2,784-annotator experiment on AI-suggested values in report tables, Beck et al. (2025) found that requiring annotators to type the correct value after rejecting a suggestion reduced engagement and increased acceptance of incorrect suggestions; annotators caught 82% of spelling errors but only 31% of errors that needed conceptual knowledge of the rules. Rejecting a critique claim should therefore cost one click, and decoys should include conceptual errors, not only surface ones, or they will overstate rater vigilance.
What you would actually do. Default to critique plus retrieval, withheld verdicts, an unassisted arm on regular items, a 50/50 split on gold, and decoys on about 30% of gold. Decide in advance the tolerated \(\Delta F\) (for example 0.05) and treat a larger value as a defect in the assistance, not in the raters.
The assistance layer has four responsibilities: store each suggestion as a versioned record separate from labels; assign each (rater, item) to an arm deterministically, so a page refresh or a retry never changes what the rater sees; record the arm with the label; and compute the follow-wrong rate per arm. The module below does exactly that and nothing else.
Data shapes: a Suggestion is one model output for one item (kind is verdict, critique or retrieval; payload holds the rendered content). A label row for analysis is a dict {arm, gold, ai_implied, human} where ai_implied is the answer the assistance points to, computed even for control items. Arms come from a SHA-256 hash of salt, rater and item, so they are stable across restarts and reproducible in analysis.
"""Model-assisted annotation: suggestion records, arm assignment, anchoring analysis (W1)."""
from dataclasses import dataclass, field
from math import sqrt, erf
import hashlib
@dataclass(frozen=True)
class Suggestion:
item_id: str
kind: str # "verdict" | "critique" | "retrieval"
model_version: str # pinned, e.g. "critic-2026-10-01"
payload: dict # verdict: {"prefer": "A", "p": 0.78}; critique: {"highlights": [...]}
decoy: bool = False # True only on gold items with a deliberately wrong claim
@dataclass
class AssistPolicy:
arms: dict = field(default_factory=lambda: {"control": 0.2, "critique": 0.8})
gold_arms: dict = field(default_factory=lambda: {"control": 0.5, "critique": 0.5}) # power where it is measured
show_verdict: bool = False # never show the AI's preference on the label being collected
decoy_rate_on_gold: float = 0.3 # share of gold items whose critique carries a planted false claim
unit: str = "item" # "item" (within-rater) or "rater" (between-rater)
salt: str = "w1-2026-11"
def _u(*parts) -> float:
"""Deterministic uniform [0,1) from a hash; same inputs -> same arm, across restarts."""
h = hashlib.sha256("|".join(parts).encode()).hexdigest()
return int(h[:15], 16) / 16**15
def assign_arm(policy: AssistPolicy, rater_id: str, item_id: str, is_gold: bool = False) -> str:
key = (policy.salt, rater_id) if policy.unit == "rater" else (policy.salt, rater_id, item_id)
arms = policy.gold_arms if is_gold else policy.arms
u, acc = _u(*key), 0.0
for arm, share in arms.items():
acc += share
if u < acc:
return arm
return list(arms)[-1]
def _phi(z): return 0.5 * (1 + erf(z / sqrt(2)))
def two_prop_z(k1, n1, k2, n2):
"""Two-sided z-test for p2 - p1. Returns (diff, z, p_value)."""
p1, p2, p = k1 / n1, k2 / n2, (k1 + k2) / (n1 + n2)
se = sqrt(p * (1 - p) * (1 / n1 + 1 / n2))
z = (p2 - p1) / se
return p2 - p1, z, 2 * (1 - _phi(abs(z)))
def n_per_arm(p1, p2, z_a=1.96, z_b=0.8416):
"""Items per arm to detect p1 -> p2 (two-sided alpha .05, power .80)."""
pb = (p1 + p2) / 2
num = (z_a * sqrt(2 * pb * (1 - pb)) + z_b * sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2
return int(-(-num // (p2 - p1) ** 2))
def anchoring_report(rows):
"""rows: dicts with arm, gold, ai_implied, human. ai_implied = label the assistance points to.
Follow-wrong rate = P(human == ai_implied | ai_implied != gold), per arm."""
out = {}
for arm in sorted({r["arm"] for r in rows}):
rs = [r for r in rows if r["arm"] == arm]
wrong = [r for r in rs if r["ai_implied"] != r["gold"]]
out[arm] = {
"n": len(rs),
"accuracy": sum(r["human"] == r["gold"] for r in rs) / len(rs),
"agree_with_ai": sum(r["human"] == r["ai_implied"] for r in rs) / len(rs),
"n_ai_wrong": len(wrong),
"follow_wrong": (sum(r["human"] == r["ai_implied"] for r in wrong) / len(wrong)) if wrong else None,
"k_follow_wrong": sum(r["human"] == r["ai_implied"] for r in wrong),
}
return out
The policy lives in the campaign spec, so changing the critic is a reviewed config change rather than a deploy:
# Campaign-level AI policy for W1 (illustrative). Versioned with the campaign spec.
campaign: w1_coding_pref
assist:
arms: {control: 0.2, critique: 0.8} # 20% permanent holdout on regular items
gold_arms: {control: 0.5, critique: 0.5} # 50/50 on gold: anchoring is measured there
show_verdict: false # never show the AI preference on the label being collected
critique_model: critic-2026-10-01 # pinned; a change is a new arm, not an in-place swap
retrieval: [unit_tests, api_docs] # executed tests and doc lookups shown as evidence
decoy_rate_on_gold: 0.3 # planted false claims on gold items
judge:
model: judge-2026-09-15 # pinned
calls: {orders: [AB, BA], samples_per_order: 3}
cost_per_item_usd: 0.06 # assumption; re-measure from billing
router:
target_agreement_with_one_human: 0.72 # W1 human-human pairwise agreement
lcb_z: 1.645 # one-sided 95%
calibration_items: 1000 # half of W1's 2,000 triple-labelled overlap items
audit_rate: 0.05
recalibrate_when:
audit_lcb_below_target: true
candidate_checkpoint_changes: true
provenance:
record: [arm, assist_model_version, judge_model_version, route, telemetry_summary]
export_filter_default: human_or_audited # training export can choose ai, human, or both
Tests assert the arm shares, the W1 sample size of 138 and that the analysis detects a 20% → 35% follow-wrong rise:
import random, sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from assist import AssistPolicy, assign_arm, n_per_arm, two_prop_z, anchoring_report
def test_arm_shares_and_stability():
pol = AssistPolicy()
arms = [assign_arm(pol, f"r{i % 150}", f"w1_item_{i}") for i in range(25_260)]
share = arms.count("control") / len(arms)
assert 0.19 < share < 0.21
assert assign_arm(pol, "r7", "w1_item_42") == assign_arm(pol, "r7", "w1_item_42")
gold = [assign_arm(pol, f"r{i % 150}", f"w1_gold_{i}", is_gold=True) for i in range(1_263)]
assert 0.46 < gold.count("control") / len(gold) < 0.54 # ~632 gold items per arm
def test_sample_size_for_anchoring():
n = n_per_arm(0.20, 0.35)
assert 130 <= n <= 145, n # ~138 AI-wrong gold items per arm
def test_anchoring_report_detects_follow_wrong():
rows = []
# 150 AI-wrong gold items per arm; control follows the wrong pointer 20%, assisted 35%
for arm, k in (("control", 30), ("critique", 53)):
for i in range(150):
rows.append({"arm": arm, "gold": "A", "ai_implied": "B", "human": "B" if i < k else "A"})
rep = anchoring_report(rows)
assert rep["control"]["follow_wrong"] == 0.20
d, z, p = two_prop_z(rep["control"]["k_follow_wrong"], 150, rep["critique"]["k_follow_wrong"], 150)
assert d > 0.15 and p < 0.01
Over 25,260 synthetic W1 assignment keys the control share is between 19% and 21%; over the 1,263 gold keys it is between 46% and 54%. With 150 AI-wrong gold items per arm and follow-wrong counts of 30 (control) and 53 (assisted), the test reports \(\Delta F \approx 0.15\) with \(p < 0.01\).
Rendering rules for the UI. Critique highlights should be visually distinct from the response itself, each with an "agree / disagree / can't tell" control so the rater must engage with every claim rather than skim. Retrieval results should show provenance (which test ran, which document version). The verdict field, if a campaign ever enables it, should appear only after the rater has submitted a first answer, which turns it into a second-look prompt rather than an anchor.
Debugging tips. If arm shares drift from the policy, check that the salt did not change between deploys; a new salt reshuffles every item. If follow_wrong is None for an arm, no AI-wrong items reached it, usually because decoys are injected after arm assignment instead of before. If the control arm's agreement with the AI is unexpectedly high, confirm the UI is not leaking assistance (cached critique panels are a common cause).
In production, the assistance layer is a dependency of every assisted label, so it needs its own availability and latency budget and its own quality signals. The availability requirement is that suggestions are ready before the item is shown: they are generated with the sample into the pre-generation buffer, never on demand while the rater waits. The quality requirement is that the follow-wrong gap between arms stays inside the tolerance set at launch.
| SLO / metric | Target (W1, illustrative) | Formula / source | Action on breach |
|---|---|---|---|
| Suggestion readiness | ≥ 99.5% of buffered items have critique + retrieval | items_with_all_suggestions / items_served | Serve unassisted and tag arm assist_missing; do not block the rater |
| Anchoring gap \(\Delta F\) (decoys) | ≤ 0.05, daily, gold 50/50 | follow_wrong[critique] − follow_wrong[control] | Page owner; freeze critic version; open incident |
| Claim agreement rate | Track; alert on ± 10 points day over day | share of critique claims marked "agree" | Check critic version, prompt and response length mix |
| Time per label by arm | Track median and p10 | from UI telemetry | p10 collapse in assisted arm suggests rubber-stamping |
| Gold accuracy by arm | ≥ 80% in each arm | gold correct / gold seen | Rater feedback if one arm only; assistance review if both |
Table. Assistance SLOs and dashboard panels. Gold threshold matches the W1 campaign spec; other targets are illustrative defaults.
Symptom. On collection day 3 the critic was upgraded in place to a newer version that writes longer, more confident critiques. Over the next two days the dashboard showed the claim agreement rate rising from 74% to 91% and median time per label in the assisted arm falling from 4.0 to 2.6 minutes. Gold accuracy stayed at 84% in both arms, so the gold alarm did not fire. The decoy panel did: follow-wrong in the assisted arm rose from 18% to 41% while the control arm stayed at 17%, so \(\Delta F\) went from 0.01 to 0.24.
Diagnosis. Three causes were possible: a rater-pool change, a UI change, or the critic. Rater-pool change was ruled out because the control arm, drawn from the same raters, did not move. The UI had not been deployed. The critic version in the provenance records changed exactly at the inflection. Gold items missed it because ordinary gold items are easy and the new critic was right on them; decoys exposed it because they are built to be wrong.
Remedy. (1) Pin the critic back to the previous version. (2) Quarantine the affected labels: W1 collects roughly 4,200 assignments a day (25,260 over 6 collection days), so about 8,400 labels over two days, of which 80% (about 6,700) were assisted. (3) Relabel a stratified 10% sample, about 670 items, in the control arm at $3.00 each, about $2,000, to measure how far the affected labels diverge from unassisted ones. (4) If divergence on the sample exceeds the agreement tolerance, relabel the affected set in full, about $20,000, or drop it and extend collection by about 1.6 days.
Cost and trade-off. The sample-first approach spends $2,000 to decide whether to spend $20,000. Dropping instead of relabelling is cheaper in dollars but adds request-to-mix latency to a campaign whose target is 7 days.
Validation. W1 sees about 210 gold assignments a day, 105 per arm, so at the normal 30% decoy rate only about 32 decoys per arm arrive daily. For the check, the decoy rate is raised to 60% (about 63 per arm per day), so the 138 needed arrive in a little over two days. The fix is supported if \(\Delta F\) on those decoys returns below 0.05 and claim agreement returns to its prior band. It is weakened if \(\Delta F\) stays high after rollback, which would point at raters having learned to rubber-stamp critiques; that calls for a rater-level control week.
Runbook: changing an assistance model.
- Never upgrade in place. Add the new version as a third arm at 10% of regular items and 1/3 of gold.
- Run until each arm has at least 138 AI-wrong gold items (decoys included).
- Compare \(\Delta F\), claim agreement, time per label and gold accuracy against the current arm.
- Decision point: promote if \(\Delta F\) is not worse by more than 0.03 and time or accuracy improves; otherwise retire the arm.
- On promotion, update the pinned version in the campaign spec and record the change in the dataset changelog so downstream consumers can stratify by assistance version.
The broader lesson for operations is that assistance turns label quality into a property of a model version. The same discipline that governs model releases, pinned versions, staged arms and a holdout, now governs the annotation interface.
AI Judges and RLAIF as First Pass
An AI judge is a language model prompted (and sometimes fine-tuned) to produce the same kind of label a human would: which of two responses is better, whether a response meets a rubric item, what score it deserves. RLAIF, reinforcement learning from AI feedback, is the practice of training on such labels instead of, or alongside, human ones. The idea entered the mainstream with Constitutional AI, in which Bai et al. (2022) had a model compare pairs of its own samples against a list of written principles, trained a preference model on those AI comparisons, and used it as the RL reward for harmlessness, with no human labels identifying harmful outputs.
It exists because human labels are slow and expensive and AI labels are neither. Lee et al. (2023) compared RLAIF and RLHF head to head on summarization and helpful dialogue and found human evaluators preferred them about equally (50% and 52%), and estimated AI labelling at about $0.06 per preference example against about $0.67 for human labelling, more than ten times cheaper. Zheng et al. (2023) found a GPT-4 judge agreed with human preferences over 80% of the time, the same level at which humans agreed with each other. UltraFeedback (Cui et al. 2023) built a public dataset of over a million GPT-4 feedback annotations. For simple classification, Gilardi et al. (2023) found zero-shot ChatGPT beat Mechanical Turk workers in accuracy by about 25 percentage points at roughly one thirtieth of the cost.
Judges are also biased in known, systematic ways. Zheng et al. documented position bias (preferring whichever answer comes first or second), verbosity bias (preferring longer answers) and self-enhancement bias (preferring outputs that resemble the judge's own). Lee et al. measured how often their judges kept preferring the same position after the two answers were swapped: 18% for the largest model and 56% for the smallest. A reward model trained on a biased judge's labels learns the bias, and the policy then exploits it.
The practical answer is not "AI or humans" but routing: let the judge label everything first, keep its label where it is reliable, and send the rest to humans. The mechanism, end to end:
- For each item, the judge is called several times with the two responses in both orders. Its confidence is how consistently it gives the same answer; an answer that flips when the order flips gets no confidence at all.
- A calibration set of items that humans have already labelled is used to pick a threshold: the loosest confidence level at which the judge's kept labels still agree with humans at least as often as humans agree with each other, with a statistical safety margin.
- In production, items above the threshold keep the AI label; items below go to the human queue, usually with the assistance described in the previous section.
- A small random audit sample of kept items also goes to humans, so the threshold can be re-checked continuously as models and prompts change.
- Every label records whether it came from the judge, a human, or both, so training can weight or filter by source.
This design has published support. Jung, Brahman and Choi (2024), in Trust or Escalate (ICLR 2025), built a cascade that starts with a cheap judge, escalates to stronger judges only when needed, and abstains otherwise, choosing thresholds so that agreement with humans meets a user-set level; with Mistral-7B as the first judge they report over 80% human agreement guaranteed at almost 80% coverage on a Chatbot Arena subset where GPT-4 alone almost never reached 80%. Miranda et al. (2024) learned which preference instances to route to humans and which to an LM, and found the routed hybrid improved reward-model performance on RewardBench by 7 to 13% over either all-human or all-LM labels. Wang et al. (2024) proposed the same shape for classification labels: an LLM labels and explains, a verifier scores each label, and humans re-annotate the low-scoring ones.
W1 has 2,000 items labelled by three raters each, with 72% pairwise agreement. Half of them become the judge's calibration set. On the illustrative calibration curve, the loosest threshold that keeps agreement with a single human at or above 72% (with a 95% lower bound) lets the judge keep 56% of items. Humans label the other 44% plus a 5% audit of kept items, so total human volume falls to about 47% of the all-human plan, and cost per useful comparison falls from $4.12 to about $1.99.
W3 is already routed by design. Experts write a rubric for each of 3,000 legal-drafting prompts; an AI grader then applies those rubrics as the RL reward. The 400 hours of human grading (four responses per prompt, about 2 minutes each) are the calibration set: the AI grader is accepted only if its item-level scores agree with the human graders at 0.8 or better, and rubric items where it falls short are sent back for rewording or kept on human grading.
Compared with all-human labelling, routing concentrates human effort where the judge is unreliable, which is usually where the label is most informative. Compared with pure RLAIF, it keeps a human measurement attached to every AI label. What it costs is complexity: a calibration set to maintain, a threshold that goes stale whenever the judge, the prompt or the policy changes, and an audit stream that must never be switched off to save money.
What you would actually do. Start every new campaign with a human-only pilot that doubles as the calibration set, add the judge as a first pass only once it clears the human–human bar on that set, and set coverage from the lower confidence bound, not the point estimate. Deviate toward more AI coverage only for labels with a cheap trusted check (tests, exact answers); deviate toward zero coverage for new domains, safety-critical content and anything where the judge model shares a lineage with the policy being trained.
Routing turns two questions into numbers: what quality bar must a kept AI label meet, and how much coverage does that bar allow at what cost.
The quality bar. The natural bar is "no worse than the single human label it replaces". Single human accuracy is not observed directly, but it can be inferred from agreement. Under a simple model where each rater independently gets a binary preference right with probability \(p\), two raters agree when both are right or both are wrong:
\[ a_{hh} = p^2 + (1-p)^2 \quad\Longrightarrow\quad p = \frac{1+\sqrt{2a_{hh}-1}}{2}. \]If the judge is right with probability \(q\) independently of the human, its agreement with one human is \(a_{jh} = qp + (1-q)(1-p)\). Setting \(a_{jh} = a_{hh}\) gives \(q = p\). So the bar can be stated in observable terms: the judge's agreement with one randomly chosen human must be at least the human–human agreement. The model ignores ties and correlated errors (raters and judges both fooled by the same plausible-looking bug), so it is a floor, not a guarantee.
W1's pairwise agreement on its overlap items is \(a_{hh} = 0.72\), so \(p = (1+\sqrt{0.44})/2 \approx 0.832\). A judge kept at the bar must agree with one random rater at least 72% of the time, which in this model means it is right about 83% of the time on the items it keeps. For reference, majority-of-three human labels would be right about \(p^3 + 3p^2(1-p) \approx 0.925\) of the time, which is why the overlap items make a good calibration reference.
Coverage and its lower bound. Sort calibration items by judge confidence. Keeping the top fraction \(\kappa\) (the coverage) gives an observed agreement \(\hat a(\kappa)\) on \(n\kappa\) items. Because \(\hat a\) is an estimate, the threshold is set on its one-sided lower confidence bound: keep the largest \(\kappa\) for which
\[ \mathrm{LCB}_{95}\big(\hat a(\kappa),\ n\kappa\big) \ \ge\ a_{hh}. \]The Wilson bound is a standard choice for a binomial proportion. Scanning thresholds from strictest to loosest and stopping at the first failure (fixed-sequence testing) avoids the inflated error rate that comes from testing many thresholds and picking the best-looking one; Jung et al. (2024) base their guarantee on the same family of argument.
Cost. Let \(N\) be the useful labels needed, \(c_j\) the judge cost per item (all calls), \(c_h\) the all-in human cost per useful label, and \(r\) the audit rate on kept items. Every item gets a judge call; the uncovered share and the audited share of the covered items get humans:
\[ C(\kappa) = N\left[c_j + \big((1-\kappa) + \kappa r\big)\,c_h\right]. \]For W1, \(N = 18{,}400\) useful comparisons and \(c_h = \$75{,}780 / 18{,}400 \approx \$4.12\). The judge is called in both orders with three samples each; the example assumes \(c_j = \$0.06\), the order of magnitude Lee et al. (2023) estimated for AI labels (to be replaced by measured billing). The illustrative calibration curve in the figure gives \(\kappa = 0.56\) as the loosest coverage whose lower bound clears 0.72. With \(r = 0.05\): human share \(= 0.44 + 0.56 \times 0.05 = 0.468\); human cost \(= 0.468 \times \$75{,}780 \approx \$35{,}465\); judge cost \(= 18{,}400 \times \$0.06 = \$1{,}104\); total \(\approx \$36{,}569\), or about $1.99 per useful comparison against $4.12 all-human. Rater-hours fall from about 1,895 to about 887.
Where the residue lands. The items humans now see are, by construction, the ones the judge found hard, and humans are probably less accurate on them too. The quality of the final dataset is a mix: kept AI labels at about the bar, plus human labels on a harder-than-average residue. Raising overlap on the residue (two raters instead of one) is often a better use of the savings than raising coverage.
Design choices.
| Router | How it decides | Strength | Weakness |
|---|---|---|---|
| Confidence threshold | Order-swapped self-consistency ≥ \(\tau\) | Simple, auditable, one calibration set | Confidence is only as calibrated as the judge |
| Cascade (cheap → strong → human) | Escalate when each judge abstains | Lower judge cost; published guarantee (Jung et al. 2024) | Several thresholds to recalibrate |
| Learned router | Predict where human labels help the reward model most (Miranda et al. 2024) | Optimises downstream RM quality, not label agreement | Needs a dataset with both human and AI labels to train |
| Verifier-scored | Second model scores each AI label (Wang et al. 2024) | Uses explanations as evidence | Verifier shares biases with the judge |
Table. Routing designs from the literature.
For W3, the AI grader scores 3,000 prompts × 4 responses × about 10 rubric items = about 120,000 item-scores. Human graders score the same responses in 400 hours. Agreement is computed per rubric item, and the bar is the campaign's 0.8 item-level target. A rubric item whose lower bound falls below 0.8 is the signal that the item is ambiguous (two careful humans would also disagree) or that it requires judgement the grader lacks; the first is fixed by rewording, the second by keeping that item on human grading.
What you would actually do. Use the confidence-threshold router with order-swapped calls as the default; it is the easiest to audit. Set \(\kappa\) from the lower bound on at least 1,000 calibration items, audit 5% of kept items, and spend part of the savings on extra overlap for the human residue. Move to a cascade when judge cost becomes material, and to a learned router once a few thousand items carry both human and AI labels and a reward-model evaluation is available to optimise against.
The router module implements the four pieces from the design: judge confidence from order-swapped votes, a Wilson lower bound, threshold calibration by fixed-sequence scan, deterministic routing with an audit sample, and the campaign cost model. Shapes: a calibration set is a list of (confidence, agrees_with_human) pairs, one per item, comparing the judge to one randomly chosen rater per item so that rows are independent; the threshold result is (tau, coverage, point_agreement, lcb).
"""AI judge as first pass: confidence, threshold calibration, routing and cost (W1)."""
from dataclasses import dataclass
from math import sqrt
import hashlib
def single_rater_accuracy(pairwise_agreement: float) -> float:
"""Symmetric binary-error model: a = p^2 + (1-p)^2 => p = (1 + sqrt(2a - 1)) / 2."""
return (1 + sqrt(2 * pairwise_agreement - 1)) / 2
def judge_confidence(votes_ab, votes_ba):
"""votes_ab: verdicts with responses shown (A,B); votes_ba: shown swapped, already mapped back
to A/B. Returns (label, confidence). Order-inconsistent majorities -> confidence 0.5."""
def maj(v): return max(set(v), key=v.count), v.count(max(set(v), key=v.count)) / len(v)
(l1, s1), (l2, s2) = maj(votes_ab), maj(votes_ba)
if l1 != l2:
return l1, 0.5
return l1, (s1 + s2) / 2
def wilson_lcb(k: int, n: int, z: float = 1.645) -> float:
"""One-sided lower confidence bound (95% for z=1.645) on a binomial proportion."""
if n == 0:
return 0.0
p = k / n
c = p + z * z / (2 * n)
r = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n))
return (c - r) / (1 + z * z / n)
def wilson_ucb(k: int, n: int, z: float = 1.645) -> float:
"""One-sided upper bound. Monitoring pages when this falls below the bar: strong evidence
that agreement has dropped, rather than mere lack of evidence that it is high."""
return 1.0 - wilson_lcb(n - k, n, z)
def calibrate_threshold(cal, target: float, z: float = 1.645, min_n: int = 100):
"""cal: list of (confidence, agrees_with_human: bool), one row per calibration item.
Fixed-sequence scan from the strictest threshold downwards; stop at the first failure.
Returns (tau, coverage, point_agreement, lcb) for the loosest threshold that passed, or None."""
cal = sorted(cal, key=lambda r: -r[0])
best, k = None, 0
for i, (conf, ok) in enumerate(cal, 1):
k += ok
nxt = cal[i][0] if i < len(cal) else None
if nxt == conf: # only test at distinct thresholds
continue
if i < min_n:
continue
lcb = wilson_lcb(k, i, z)
if lcb < target:
break
best = (conf, i / len(cal), k / i, lcb)
return best
@dataclass
class RoutePolicy:
tau: float
audit_rate: float = 0.05
salt: str = "w1-router"
def route(policy: RoutePolicy, item_id: str, confidence: float) -> str:
if confidence < policy.tau:
return "human"
u = int(hashlib.sha256(f"{policy.salt}|{item_id}".encode()).hexdigest()[:12], 16) / 16**12
return "ai+audit" if u < policy.audit_rate else "ai"
def campaign_cost(n_useful, coverage, audit_rate, c_judge, c_human):
"""Every item gets a judge call; uncovered items and an audit sample of covered items go to humans."""
human_share = (1 - coverage) + coverage * audit_rate
return {"human_share": human_share,
"judge": n_useful * c_judge,
"human": n_useful * human_share * c_human,
"total": n_useful * (c_judge + human_share * c_human)}
The tests reproduce the W1 numbers. The calibration set is synthetic and labelled as such: judge accuracy falls linearly from 0.97 on the most confident items to 0.57 on the least, and agreement with one rater follows from the single-rater accuracy of 0.832.
import random, sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from router import (single_rater_accuracy, judge_confidence, wilson_lcb, wilson_ucb,
calibrate_threshold, RoutePolicy, route, campaign_cost)
W1_PAIRWISE_AGREEMENT = 0.72
W1_USEFUL, W1_LABOUR = 18_400, 75_780.0
W1_COST_PER_USEFUL = W1_LABOUR / W1_USEFUL # ~4.12
def test_single_rater_accuracy():
p = single_rater_accuracy(W1_PAIRWISE_AGREEMENT)
assert abs(p - 0.832) < 0.001
assert abs(p * p + (1 - p) ** 2 - 0.72) < 1e-9
def test_judge_confidence_order_swap():
assert judge_confidence(["A", "A", "A"], ["A", "A", "B"]) == ("A", (1 + 2 / 3) / 2)
assert judge_confidence(["A", "A", "A"], ["B", "B", "B"])[1] == 0.5 # position-driven
def synthetic_calibration(n=1000, seed=9):
"""Judge accuracy falls from 0.97 (most confident) to 0.57 (least); compared with ONE random
rater of accuracy 0.832 -> agreement g = 0.168 + 0.664 * acc. Illustrative, not published."""
rng, p = random.Random(seed), single_rater_accuracy(0.72)
rows = []
for i in range(n):
q = i / n
acc = 0.97 - 0.40 * q
g = acc * p + (1 - acc) * (1 - p)
rows.append((round(1 - q, 3), rng.random() < g))
return rows
def test_calibrated_threshold_meets_human_bar():
res = calibrate_threshold(synthetic_calibration(), target=0.72)
tau, cov, agree, lcb = res
print("calibration:", res)
assert lcb >= 0.72 and 0.5 <= cov <= 0.72
def test_routing_and_cost():
pol = RoutePolicy(tau=0.40, audit_rate=0.05)
r = [route(pol, f"w1_{i}", 0.9) for i in range(20_000)]
assert 0.045 < r.count("ai+audit") / len(r) < 0.055
assert route(pol, "w1_x", 0.2) == "human"
c = campaign_cost(W1_USEFUL, coverage=0.56, audit_rate=0.05, c_judge=0.06, c_human=W1_COST_PER_USEFUL)
print("cost:", {k: round(v, 3) for k, v in c.items()})
assert abs(c["human_share"] - 0.468) < 1e-9
assert abs(c["total"] - (1_104 + 0.468 * W1_LABOUR)) < 1
base = campaign_cost(W1_USEFUL, 0.0, 0.0, 0.0, W1_COST_PER_USEFUL)["total"]
assert abs(base - W1_LABOUR) < 1e-6
def test_wilson():
assert abs(wilson_lcb(890, 1000) - 0.872) < 0.003
def test_monitoring_uses_upper_bound():
# 3-day W1 audit window: ~258 audits. A healthy 0.75 cannot prove LCB >= 0.72 on so few items,
# so paging on LCB would fire constantly; page on UCB < bar instead.
assert wilson_lcb(194, 258) < 0.72 < wilson_ucb(194, 258) # 0.75: no page
assert wilson_ucb(170, 258) < 0.72 # 0.66: page
def test_policy_file_matches_code_defaults():
import yaml
cfg = yaml.safe_load(open(os.path.join(os.path.dirname(__file__), "..", "w1_ai_policy.yaml")))
assert cfg["router"]["target_agreement_with_one_human"] == W1_PAIRWISE_AGREEMENT
assert abs(sum(cfg["assist"]["arms"].values()) - 1.0) < 1e-9
assert cfg["assist"]["show_verdict"] is False
assert RoutePolicy(tau=0.5).audit_rate == cfg["router"]["audit_rate"]
Running the tests prints calibration: (0.441, 0.56, 0.752, 0.721): the loosest threshold that passes is a confidence of 0.441, which keeps 56% of the calibration items with a point agreement of 0.752 and a lower bound of 0.721, just above the 0.72 bar. The cost line prints human_share 0.468, judge 1104.0, human 35465.04, total 36569.04.
Judge call pattern. The judge prompt should ask for a short justification followed by a verdict, with the two responses labelled neutrally; the platform swaps order on the second call and maps the verdict back. Three samples per order at a non-zero temperature give the consistency signal; Lee et al. (2023) found sampling-based self-consistency lowered alignment compared with greedy decoding in their setup, so the samples here are used only for confidence, while the label is the majority.
Debugging tips. If calibration returns None, the judge fails the bar even on its most confident 100 items; check for order bias first (many items at confidence 0.5). If coverage is suspiciously high, check that calibration rows compare to one rater, not to the majority, which inflates agreement. If the audit rate in production differs from the configured rate, the item ids being hashed are probably not stable (for example, regenerated on retry).
Operating a router means operating a threshold that is only valid for the judge, prompt, policy checkpoint and data distribution it was calibrated on. Any of the four can change during a campaign. The audit stream is the instrument that detects it, so its size determines detection speed.
| Panel / SLO | Target (W1, illustrative) | Formula | Alert |
|---|---|---|---|
| Audited agreement, rolling 3 days | Point estimate ≥ 0.72 | agree(judge, one human) on ai+audit items | Page when the Wilson upper bound < 0.72 → auto-reduce coverage |
| Audited agreement, rolling 21 days | Wilson LCB ≥ 0.72 | same, about 1,800 audits | Below → recalibrate before the next campaign phase |
| Coverage | 0.56 ± 0.05 | kept / judged | Shift > 0.05 day over day → check confidence distribution |
| Order-flip rate | Track | share of items with confidence 0.5 | Rise > 5 points → position bias, check prompt |
| Length gap | Track | mean tokens of judge-preferred minus other response | Rise → verbosity bias suspected |
| Cost per useful label | ≤ $2.40 | (judge spend + human spend) / useful labels | Weekly review |
| Judge availability | ≥ 99.5% | successful judge calls / attempts | On outage, route all to humans; do not drop items |
Table. Router dashboard. Audit volume: about 3,070 useful comparisons a day in W1, 56% kept, 5% of those audited, so about 86 audits a day and about 258 over a rolling 3-day window.
The two agreement rows answer different questions. Calibration asks for proof that the judge is good enough, so it uses the lower bound. Monitoring asks for proof that it has become worse, so it pages on the upper bound. Using the lower bound for paging would fire constantly: with about 258 audits, a healthy agreement of 0.75 has a lower bound of only about 0.705. An alert rule in a Prometheus-style syntax, assuming the platform exports per-day audit counts:
# fires when even the 95% Wilson UPPER bound on 3-day audited agreement is below the human bar
- alert: RouterAuditBelowHumanBar
expr: router_audit_agree_ucb95_3d < 0.72 # gauge exported by the recording job
for: 12h
labels: {severity: page, campaign: w1_coding_pref}
annotations:
runbook: ref-play-runbook#router-drift
action: "set router.coverage_cap=0.0 (all human), open incident, start recalibration"
Prometheus has no Wilson function; the bound is computed by a recording job (for example wilson_ucb() in the Build code) and exported as a gauge.
Symptom. On collection day 4 the candidate checkpoint in W1 was refreshed. The new candidate's answers were about 35% longer. Over the next three days, audited agreement on kept items fell from 0.75 to 0.66 (about 258 audits; Wilson upper bound about 0.71, below the 0.72 bar, so the page fired), while coverage rose from 0.56 to 0.64: the judge was more confident, not less. The length-gap panel showed the judge preferring the longer response in 71% of kept items, up from 55%.
Diagnosis. Candidate causes were a judge change, a prompt change, or a data shift. The judge and prompt versions in provenance were unchanged. The shift coincided with the checkpoint refresh, and the length gap pointed at verbosity bias: the judge was confidently preferring longer answers that human raters, checking the code, did not prefer.
Remedy. (1) The alert set coverage to zero, routing everything to humans; this costs the difference between $4.12 and $1.99 per useful comparison, about $6,500 a day at 3,070 comparisons a day. (2) Labels kept by the judge since the refresh (about 3 days × 1,840 at an average coverage of 0.6, roughly 5,500) were flagged in provenance and excluded from the next export pending review. (3) The judge prompt was revised to instruct length-neutral comparison and to require citing a concrete defect, and a length-matched subset was added to calibration. (4) Recalibration used 300 newly triple-labelled items from the new checkpoint plus the existing set, at about 900 labels × $3.00 = $2,700.
Cost and trade-off. Three days at zero coverage cost about $19,600 extra, against the alternative of letting about 5,500 verbosity-biased labels into a reward model, which would teach the policy to write longer code answers. The new threshold gave coverage 0.48, lower than before, so steady-state cost rose to about $2.30 per useful comparison.
Validation. The fix is supported if the next 258 audits show a point agreement at or above 0.72 with no page, the 21-day lower bound recovers above 0.72 as audits accumulate, and the length gap returns near its pre-refresh 55%. It is weakened if agreement recovers only on length-matched items, which would mean the prompt fix masked rather than removed the bias; then the right move is a stronger or differently trained judge, not a tighter threshold.
Runbook: router drift.
- Confirm the alert on raw counts (agreeing audits / audits); rule out an audit-pipeline bug by checking a few audited items by hand.
- Set coverage cap to zero. Never drop items while investigating; humans absorb the load and the extra cost is bounded per day.
- Check provenance for judge, prompt and checkpoint versions at the inflection point.
- Decision point: version change found → roll back or recalibrate on new-version items; no version change → inspect bias panels (order flips, length gap) and the topic mix of audited disagreements.
- Recalibrate on at least 300 fresh items from the current distribution plus the prior set; restore coverage from the new lower bound only.
- Mark kept labels from the incident window and let the export filter exclude them until a review decides.
For W3 the same machinery runs at RL time rather than at labelling time: the AI grader's item-level agreement with a continuing trickle of human grading (for example 2% of graded responses) is the audit stream, and a fall below 0.8 on any rubric item suspends that item from the reward until it is reworded or re-validated.
Where Humans Remain Essential
If AI judges can take half of a preference campaign and AI critics make the other half faster, the obvious question is what is left for humans, and how a platform makes sure the human part is actually human. Both halves of that question have concrete answers.
Where humans remain essential. Five jobs resist automation, for reasons that are structural rather than temporary.
- Defining the target. A judge applies criteria; someone has to write them. Constitutional AI still starts from a human-written list of principles (Bai et al. 2022). HealthBench (OpenAI 2025) used 262 physicians to write 48,562 rubric criteria, and only then let a model grader apply them. W3's 1,250 expert-hours of rubric writing are the same pattern.
- Expert judgement where judges trail experts. Szymanski et al. (2024) compared an LLM judge with dietitians and clinical psychologists: subject-matter experts agreed with the judge 64 to 68% of the time in dietetics and 60 to 64% in mental health, against 72 to 75% agreement among experts, while lay users agreed with the same judge about 80% of the time. A judge that matches lay raters can still miss what experts see.
- Ground truth for every AI step. Each routing threshold, anchoring measurement and grader validation in this chapter is computed against human labels. Remove the human stream and the AI components lose their measuring stick, and the measurements go stale as models change.
- Novel and adversarial cases. A policy trained against a judge learns to exploit the judge's blind spots, and a judge cannot flag a failure mode it does not recognise. New failure types, red-team findings and the first examples of any new task have to come from people.
- Whose preferences. When the label is a value judgement, the population that gives it is part of the specification. A model's opinion is not a sample of any human population.
Keeping human data human. The opposite risk is that labels paid for and recorded as human are in fact written by a chatbot. This is common where the task is text production. Veselovsky et al. (2023) estimated that 33 to 46% of Mechanical Turk workers used LLMs on a summarisation task, using keystroke logging plus a synthetic-text classifier. In a follow-up, Veselovsky et al. (2023) estimated about 30% use without instructions, roughly halved by asking workers not to use LLMs and by making it harder (disabling paste), but not eliminated; they also found LLM-assisted responses were high quality but homogeneous. In a 2026 survey study, Xu and Malkin (2026) flagged about 8% of Prolific participants and 83.7% of MTurk participants (baseline samples of about 50 each) with copy-paste and self-report heuristics, so the platform and population matter a great deal.
Why it matters beyond cost: a reward model trained on LLM-written "human" labels learns an AI's preferences at human prices; an AI grader validated against LLM-written rubrics agrees with them for the wrong reason; and training repeatedly on generated data can erase the tails of the original distribution, which Shumailov et al. (2023) called model collapse.
The mechanism a platform uses has four layers, in order:
- Policy. Say which tools are sanctioned (spell-check, a platform-provided critic) and which are not, and record sanctioned assistance in the label's provenance, so the rule is about disclosure rather than purity.
- Task design. Ask for evidence that is hard to outsource: point to the failing line, cite the clause, mark the first failing step. A chatbot can write fluent text; it is much less convenient to paste into a structured, located answer.
- Detection. Combine two independent families of signals: behaviour in the editor (how much text was pasted versus typed, focus leaving the page), and text (overlap with answers that LLMs give to the same prompt). An Appen study reported that unaided writers' keypresses made up a median 0.918 of their text against 0.374 for AI-assisted writers (Appen 2023). Prolific (2026) reports 98.7% precision for its behaviour-based LLM check in internal testing, a vendor claim not independently verified.
- Review, not removal. A flag starts a human review with the worker's account of what happened. Each signal alone has false positives (experts paste from their own notes), and automated punishment on noisy signals damages a workforce that is hard to rebuild.
W3's rubric writing is the most exposed step in the reference workloads: it is long free text, done by experts working remotely, and an LLM can produce a plausible rubric in seconds. It is also the step whose integrity matters most, because the AI grader will turn those rubrics into RL reward. W3 therefore records editor telemetry for every rubric, generates three reference rubrics per prompt with available LLMs for overlap checks, and flags a rubric only when both a behaviour signal and a text signal fire. The W1 preference labels are much less exposed: a binary choice plus a located defect leaves little text to outsource.
Compared with the crowdsourcing era, when the integrity problem was low effort (random clicking, speeding), the 2026 problem is high-effort-looking output with no human judgement in it. Speed and gold checks still catch the first; they do not catch the second, because LLM output is fluent and often correct on easy gold.
What you would actually do. Keep humans on criteria writing, gold and calibration sets, expert-only judgements and novel cases, and give AI the application of validated criteria at scale. For every free-text human field, collect behavioural telemetry with the worker's informed consent, compare text with same-prompt LLM references, and require two signal families before a flag. Deviate toward stricter controls (paste disabled, proctored sessions) only for the highest-value text, such as rubrics and gold items, where the cost of contamination is multiplied downstream.
Two design questions need numbers: when is a task safe to hand to AI, and how good does a detector of LLM-written labels need to be before it helps rather than harms.
Deciding the boundary. For a candidate task, measure on a human-labelled sample three agreements: among the target experts (\(a_{ee}\)), between experts and the judge (\(a_{ej}\)), and between lay raters and the judge (\(a_{lj}\)). The judge may take over only where \(a_{ej} \ge a_{ee}\) with a lower confidence bound, as in the routing section. The gap \(a_{ee} - a_{ej}\) is the expertise gap; a large \(a_{lj}\) alongside a positive gap means the judge has learned lay preferences, not expert ones.
In Szymanski et al. (2024), dietetics: \(a_{ee} = 0.75\), \(a_{ej} = 0.64\) (general judge) or 0.68 (expert-persona judge), \(a_{lj} = 0.80\). Expertise gap 0.07 to 0.11. Mental health: \(a_{ee} = 0.72\), \(a_{ej} = 0.60\) to 0.64. On these numbers no coverage would be granted to that judge for expert-level labels, although it looks excellent against lay raters.
A second test is the cost of a wrong label times how much it is amplified downstream. A W1 preference label trains a reward model alongside 18,000 others, so a single error is diluted. A W3 rubric item becomes a reward term applied to every RL rollout on that prompt, so a single bad criterion is applied thousands of times. High amplification means human authorship and human validation even when an AI could draft.
Detector arithmetic. Let \(\pi\) be the prevalence of LLM-written labels, and a detector have true-positive rate \(\mathrm{TPR}\) and false-positive rate \(\mathrm{FPR}\). The share of flags that are correct (precision) is
\[ \text{precision} = \frac{\pi\,\mathrm{TPR}}{\pi\,\mathrm{TPR} + (1-\pi)\,\mathrm{FPR}}. \]At low prevalence, even a small \(\mathrm{FPR}\) makes most flags false. Requiring two signal families that err independently multiplies their rates: \(\mathrm{TPR} = t_b t_x\), \(\mathrm{FPR} = f_b f_x\), where \(b\) is behaviour and \(x\) is text. Independence is an assumption: an expert who pastes from a draft written with an LLM's help fires both.
Assume (illustratively) prevalence \(\pi = 0.08\), a behaviour signal with \(t_b = 0.85, f_b = 0.10\), and a text-overlap signal with \(t_x = 0.70, f_x = 0.08\). Behaviour alone: precision \(= 0.068 / (0.068 + 0.092) \approx 0.43\), so most flags would accuse honest experts. Both families: \(\mathrm{TPR} = 0.595\), \(\mathrm{FPR} = 0.008\), precision \(= 0.0476 / (0.0476 + 0.0074) \approx 0.87\). Across 3,000 rubrics that means about 240 LLM-written, about 143 caught, about 22 false flags, about 165 reviews; at 10 minutes per review by a senior expert at $120/h (the W2 expert rate, assumed for W3) the review costs about $3,300. About 97 LLM-written rubrics are missed, which is why prevention (policy, task design) carries as much weight as detection.
The value of the human core. W3 shows why the boundary is drawn at criteria rather than at application. Writing 3,000 rubrics takes about 1,250 expert-hours (about $150,000 at the assumed $120/h). Applying them is unbounded: an RL run that grades every rollout against its prompt's rubric may need millions of gradings, which only an AI grader can afford. Validating the grader needs the 400 human grading hours once, plus a small continuing audit. Human effort goes where it is irreplaceable and where its effect is multiplied.
| Control | Reduces | Cost to honest workers | Evidence |
|---|---|---|---|
| Ask not to use LLMs | Prevalence | None | About half, combined with paste friction (Veselovsky et al. 2023b) |
| Disable paste | Prevalence | Friction; can lower quality | At least 27.5% of MTurk participants may still have used LLMs, and quality declined (Xu and Malkin 2026) |
| Located-evidence task design | Usefulness of pasted text | Small | Design argument; not separately measured |
| Two-family detection + review | Contamination that gets through | Review time for false flags | Precision arithmetic above |
Table. Controls for keeping human data human, and the evidence for each.
What you would actually do. Grant AI coverage only where the expertise gap is zero within its confidence bound, keep criteria authorship and gold human for high-amplification labels, and size a detector by its precision at a realistic prevalence before acting on any flag. Prefer prevention through task design over stricter detection; detection catches about half to two thirds of cases at acceptable precision.
Keeping human data human is mostly bookkeeping: every label carries a provenance record, the editor sends a compact telemetry summary, the platform computes text overlap against same-prompt references, and a rule turns signals into review tickets. The module below implements those pieces. Shapes: editor events are (t_ms, kind, n) tuples, summarised into a dict with typed, pasted and final character counts, keypress and paste proportions, and time away from the page; overlap is a Jaccard score of word trigrams between the worker's text and the LLM reference texts.
"""Keeping human data human: provenance record, editor telemetry, LLM-text signals (W3 rubric writing)."""
from dataclasses import dataclass, field
import re
@dataclass
class Provenance:
label_id: str
worker_id: str
assist_mode: str # "none" | "critique" | "retrieval" | "verdict"
assist_model_version: str | None
sanctioned_tools: list = field(default_factory=list) # e.g. ["spellcheck"]
typed_chars: int = 0
pasted_chars: int = 0
final_chars: int = 0
blur_ms: int = 0
active_ms: int = 0
def summarize_events(events):
"""events: list of (t_ms, kind, n) with kind in {"key","paste","delete","blur","focus"}."""
typed = pasted = deleted = blur_ms = 0
blur_at = None
for t, kind, n in events:
if kind == "key": typed += n
elif kind == "paste": pasted += n
elif kind == "delete": deleted += n
elif kind == "blur": blur_at = t
elif kind == "focus" and blur_at is not None:
blur_ms += t - blur_at; blur_at = None
final = max(typed + pasted - deleted, 1)
span = events[-1][0] - events[0][0] if events else 0
return {"typed": typed, "pasted": pasted, "final": final, "keypress_prop": min(typed / final, 1.0),
"paste_prop": min(pasted / final, 1.0), "blur_ms": blur_ms, "active_ms": span - blur_ms}
def _ngrams(text, n=3):
w = re.findall(r"[a-z0-9]+", text.lower())
return {tuple(w[i:i + n]) for i in range(len(w) - n + 1)}
def max_overlap(text, references, n=3):
"""Max Jaccard overlap of word n-grams between a worker's text and LLM reference outputs
generated by the platform for the same prompt."""
a = _ngrams(text, n)
best = 0.0
for r in references:
b = _ngrams(r, n)
if a and b:
best = max(best, len(a & b) / len(a | b))
return best
@dataclass
class FlagRule:
paste_prop: float = 0.6 # most of the final text arrived by paste
keypress_prop: float = 0.4 # cf. median 0.374 AI-assisted vs 0.918 unaided (Appen 2023)
overlap: float = 0.30 # trigram Jaccard with a same-prompt LLM reference
min_chars: int = 200 # too short -> signals unreliable, never flag on text alone
def assess(tel, overlap, rule: FlagRule = FlagRule()):
"""Returns (flag, reasons). A flag routes to human review; it never removes data by itself."""
reasons = []
if tel["final"] >= rule.min_chars:
if tel["paste_prop"] >= rule.paste_prop: reasons.append("paste")
if tel["keypress_prop"] <= rule.keypress_prop: reasons.append("low_keypress")
if overlap >= rule.overlap: reasons.append("llm_overlap")
# require two independent signal families: behaviour AND text
behav = {"paste", "low_keypress"} & set(reasons)
return (bool(behav) and "llm_overlap" in reasons), reasons
The tests use a W3 rubric fragment. A typed rubric is not flagged even though its content resembles the LLM reference, because the behaviour family does not fire. A pasted rubric that overlaps the reference is flagged with both reasons. A large paste from the expert's own notes, with no overlap, is not flagged.
import random, sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from provenance import summarize_events, max_overlap, assess
RUBRIC_TYPED = ("1. Identifies governing law clause and states which jurisdiction applies (weight 3). "
"2. Flags the indemnity cap as below the contract value (weight 2). "
"3. Notes that the termination notice period conflicts with clause 14 (weight 2). ") * 2
LLM_REF = ("1. Identifies the governing law clause and specifies the applicable jurisdiction. "
"2. Flags that the indemnity cap is lower than the total contract value. "
"3. Notes the conflict between the termination notice period and clause 14.")
def test_typed_rubric_not_flagged():
ev = [(0, "focus", 0)] + [(1000 + 400 * i, "key", 1) for i in range(len(RUBRIC_TYPED))]
tel = summarize_events(ev)
flag, why = assess(tel, max_overlap(RUBRIC_TYPED, [LLM_REF]))
assert tel["keypress_prop"] > 0.9 and not flag, why
def test_pasted_llm_rubric_flagged():
ev = [(0, "focus", 0), (5_000, "blur", 0), (65_000, "focus", 0), (66_000, "paste", len(LLM_REF) + 120),
(70_000, "key", 30)]
tel = summarize_events(ev)
ov = max_overlap(LLM_REF + " 4. Checks defined terms are used consistently.", [LLM_REF])
flag, why = assess(tel, ov)
assert flag and "paste" in why and "llm_overlap" in why, (tel, ov, why)
def test_paste_alone_not_flagged():
own_notes = "x " * 300 # e.g. pasted from the expert's own drafting notes
ev = [(0, "focus", 0), (1_000, "paste", 600)]
flag, why = assess(summarize_events(ev), max_overlap(own_notes, [LLM_REF]))
assert not flag and "paste" in why
The editor sends a summary, not keystroke content, when the label is submitted. Minimising what is collected matters for privacy and for worker trust; the summary below is enough for every check in this section:
{
"label_id": "w3_rubric_01842",
"worker_id": "exp_117",
"assist_mode": "none",
"assist_model_version": null,
"sanctioned_tools": ["spellcheck"],
"telemetry": {"typed": 2140, "pasted": 0, "deleted": 312, "final": 1828,
"keypress_prop": 1.0, "paste_prop": 0.0, "blur_ms": 41000, "active_ms": 1386000},
"text_checks": {"ref_models": ["ref-a", "ref-b", "ref-c"], "max_trigram_jaccard": 0.07},
"flag": false, "reasons": []
}
Export filters. Downstream training should be able to ask for exactly the provenance it wants: all human, human plus audited AI, or everything. The filter reads assist_mode, the router's route field from the previous section, and flag; flagged labels are excluded by default until reviewed.
Debugging tips. If keypress proportion exceeds 1 for many labels, the editor double-counts IME composition events; count committed characters, not key events. If overlap is high for every worker on a prompt, the prompt itself forces formulaic text (statute names, defined terms); raise the n-gram size or strip prompt text before comparing. If flags cluster on one browser, check whether its extension ecosystem injects text (grammar tools) and whether that tool belongs on the sanctioned list.
In production the provenance system has to be complete (every label has telemetry), fast enough not to delay export, and fair enough that experts keep working on the platform. Its metrics therefore cover coverage, flag dynamics and review outcomes, sliced by worker cohort and task type.
| Panel / SLO | Target (W3, illustrative) | Formula | Action |
|---|---|---|---|
| Telemetry coverage | ≥ 99% of free-text labels | labels with telemetry / labels | Below → block export of uncovered labels as provenance_unknown |
| Flag rate | Expected about 5.5% (165 / 3,000) | flags / labels, daily | Above 2× expected → open incident |
| Review precision | ≥ 0.75 | confirmed / reviewed | Below → retune thresholds before more reviews |
| Review latency | p95 ≤ 2 business days | flag → decision | Backlog blocks the affected export only |
| Flags per worker | Distribution | flags per 100 labels | Concentration in a few workers → workforce conversation |
| Grader agreement by provenance | Track | AI-grader vs human agreement, flagged vs clean rubrics | Higher on flagged rubrics → circularity warning |
Table. Provenance dashboard for W3 rubric writing; expected flag rate from the detector arithmetic in Design & Numbers.
Symptom. After the first 600 rubrics, the flag rate was 9% (54 rubrics), against an expected 5.5%. A second panel showed something more worrying: on flagged rubrics the AI grader agreed with human graders at 0.91 item-level, against 0.84 on clean rubrics. (Both figures illustrative.)
Diagnosis. Review by two senior experts confirmed 41 of the 54 flags (precision 0.76), and 35 of the 41 came from three experts who said they had drafted rubrics with a chatbot and then edited them. The higher grader agreement had a simple explanation: criteria written by an LLM are phrased the way an LLM grader parses them, and they leave out the expert-specific checks (jurisdiction-specific clauses, defined-term consistency) that humans and graders disagree about. High agreement here was a symptom of missing expertise, not of a better rubric.
Remedy. (1) Quarantine the 41 rubrics and the 164 responses graded against them. (2) Have the original experts, or others, rewrite them unaided: 41 × 25 min ≈ 17 expert-hours, about $2,050 at the assumed $120/h. (3) Regrade: 41 × 4 × 2 min ≈ 5.5 hours, about $660. (4) Clarify policy: the three experts were working within what they believed was allowed, so the response was a written policy on sanctioned tools plus a platform-provided drafting aid whose use is logged as assist_mode, not removal. (5) Add a structural requirement to the rubric interface: each criterion must cite the prompt's clause it tests, which is located evidence that an LLM draft rarely supplies correctly.
Cost and trade-off. About $2,700 and roughly a day of request-to-mix latency on the affected prompts, against an RL reward built partly on criteria an LLM wrote. Allowing a logged drafting aid concedes that some rubrics will be AI-assisted; in return their provenance is known, and the anchoring machinery from the first section can measure what the aid does to rubric content.
Validation. The remedy is supported if the next 600 rubrics show a flag rate near the expected 5.5% with precision at or above 0.75, and if grader agreement on rewritten rubrics falls toward the clean-rubric level, which would indicate that the expert-specific criteria are back. It is weakened if the flag rate falls but grader agreement on the new rubrics stays high, which would suggest drafting moved to tools the telemetry does not see (a second device), and calls for task-design changes rather than more detection.
Runbook: suspected LLM-generated annotations.
- Confirm the flag rate rise is real: check telemetry coverage and any editor deploy that could change event counts.
- Sample 30 flags for two-reviewer review; compute precision before acting on the rest.
- Decision point: precision below 0.5 → retune thresholds and stop; at or above 0.5 → continue to step 4.
- Group confirmed cases by worker and by task; a few workers points to a policy conversation, broad spread points to task design or unclear policy.
- Quarantine confirmed labels and everything derived from them (grades, rewards, exports) using lineage.
- Rework or drop, sized by downstream amplification: rewrite high-amplification items (rubrics, gold), drop low-amplification ones when cheaper.
- Record the incident, threshold changes and policy changes in the dataset changelog.
The common thread across the chapter's three operational stories is that AI in the loop is safe only while a human measurement stream is attached to it. Assistance is measured against an unassisted arm, the judge against an audit stream, and the human data itself against provenance. Remove any one of them and the corresponding failure becomes invisible until it shows up in the trained model.
Workforce, Vendors and Welfare
Every earlier chapter described software: the campaign spec, the sampler, the router, the interfaces, the quality program and the export path. All of that software exists to put a model sample in front of a person and to carry that person's judgment back into training. The workforce is the set of people who do that work: crowd workers, trained vendor raters, credentialed domain experts and internal staff. Their availability, skill, pay and wellbeing set hard limits on what the platform can deliver, and the platform in turn shapes their working conditions through every queue, timer and quality score it applies to them.
Four questions organise the chapter:
- Who does the work, and how are they qualified? Populations, their trade-offs, and the staged path from applicant to trusted rater (Populations, qualification and onboarding).
- How does work reach people the platform does not employ? Vendor integration: task handoff, webhooks, service-level agreements and routing across several vendors (Integrating vendor platforms).
- What are people paid, and how much work can a pool do? Pay models, incentives and the arithmetic of throughput planning (Pay, incentives and throughput planning).
- What does the work cost the people who do it? Harmful-content exposure, labour practice, research ethics and wider social effects (Wellbeing, harmful content, ethics and societal impact).
The chapter treats welfare as an engineering requirement rather than an appendix. Exposure limits are enforced by the router; pay floors are checked against measured task times; vendor contracts carry wellbeing obligations next to latency obligations. The decision a platform builder faces here is whether these constraints live in code, where they are applied to every assignment, or in policy documents, where they depend on someone remembering them. The recommended default is code, with policy documents describing what the code enforces.
Human time is the scarce and expensive input of an RL data platform. Model sampling, storage and transformation are cheap by comparison; the binding constraints are worker-hours of the right skill, the latency of getting work to those workers and back, the price per hour, and the amount of difficult content a person can safely review. This chapter turns each of those into numbers a planner can work with.
The reference workloads make the scale concrete. W1, a pairwise coding-preference campaign, needs about 1,895 rater-hours from a pool of 150 vendor raters working 20 hours a week, which is 3,000 rater-hours a week. W2, an expert review of long agentic transcripts, needs about 1,167 expert-hours from 40 experts at 15 hours a week, which is 600 expert-hours a week. At $40 and $120 per hour, labour is about $75,780 and $140,000 respectively, and it is nearly the whole variable cost of each campaign.
| Lever | Moves | Typical quantity | Section |
|---|---|---|---|
| Population mix and qualification | quality, start-up latency, rate | 589 applicants for 150 active raters under assumed pass rates | Populations |
| Vendor integration | result latency, availability, lost work | callback retries up to 24 h at one public vendor | Vendors |
| Pay model and plan | cost, schedule, effort, retention | $4.12 per useful W1 comparison; $70 per W2 transcript | Pay |
| Exposure policy | worker harm, usable capacity | severity-weighted daily cap per worker | Welfare |
The design choice that recurs throughout is where to set a constraint so it holds automatically. The recommended default is to express each lever as a parameter the platform enforces (a qualification gate, an idempotency key, a pay floor, an exposure cap) and to report the measured value next to its target on the same dashboard as throughput and quality. Deviate from that only for decisions that genuinely need human judgment, such as accepting a new vendor.
In code, the workforce is a small set of entities that the router, the pay system and the welfare checks all read. Keeping them in one versioned configuration means that a change to an exposure cap or a pay floor is reviewed and deployed like any other change, and that an audit can reconstruct which policy applied to any past assignment.
# workforce/w1.yaml : one file per campaign, validated at launch
campaign: w1
populations:
vendor_rater:
vendors: [vendorA, vendorB] # routing candidates (vendor section)
qualification: w1_exam_v3 # gate config (qualification)
target_active: 150
hours_per_week: 20
pay:
model: hourly # hourly | piece | hybrid (pay section)
rate_usd_per_h: 40.0
floor_usd_per_h_effective: 40.0 # checked against measured times
paid_activities: [instructions, exam, calibration, tasks, feedback]
throughput:
mean_min_per_assignment: 4.5
gold_share: 0.05
overlap: {share: 0.10, k: 3}
welfare:
exposure_policy: default_v2 # caps, breaks, blur (welfare section)
sensitive_opt_in_required: true
support: [counselling, peer_channel, grievance_form]
Each later section ships the code that reads one block of this file: the qualification state machine, the vendor adapters and webhook receiver, the throughput and pay planner, and the exposure budget. Each module has a short test that asserts the W1 or W2 numbers from the example sheet, so a change that breaks the arithmetic fails before launch. A useful debugging habit is to log the configuration hash on every assignment record; when a number looks wrong later, the first question is which policy version produced it.
Operating the workforce side of the platform means watching a second set of service levels next to latency and data quality. The four that matter most are listed below; each section develops its own dashboard, alerts and a worked incident.
| Indicator | Definition | Target |
|---|---|---|
| Qualified capacity | active qualified worker-hours available next week ÷ planned hours | ≥ 1.3 |
| Result completeness | vendor-completed tasks recorded in the platform's ledger within 1 h | ≥ 99.5% |
| Effective pay | 10th-percentile measured earnings per paid hour ÷ policy floor | ≥ 1.0 |
| Exposure compliance | assignments that would have exceeded a worker's cap | 0 |
A typical failure crosses these lines. In the W1 campaign, if one of two vendors loses half its active raters mid-collection, qualified capacity falls from about 1.6 (3,000 available hours a week against roughly 1,895 needed in a 0.63-week window) to about 1.2 (about 2,250 available hours a week if the two vendors supply equal shares), below the 1.3 target; the router shifts tasks to the second vendor, whose raters then need qualification; and pressure to finish tempts managers to raise quotas, which shows up first as a fall in measured time per item and then as gold accuracy dropping. The sections that follow give the controls that stop each step of that chain.
Populations, qualification and onboarding
A population is a group of workers who share a recruitment channel, an employment relationship, a skill profile and a price. The platform needs to know the population of every worker because it decides which tasks the worker may see, what evidence of quality is required before their labels count, and which contract and pay rules apply. Four populations cover almost all RL human-data work.
- Open crowd. Workers recruited through an open marketplace or research-participant platform. The platform posts a task; anyone who meets basic filters can take it. Crowds are large and start quickly, but identity assurance is weak, churn is high, and skill must be established from scratch. They suit short, low-context judgments and population-representative preference studies.
- Managed vendor teams. Raters employed or contracted by a data vendor that trains them, supervises them with its own quality leads, and sells their time under a contract with service levels. They suit high-volume tasks that need consistent training, such as the W1 coding comparisons.
- Domain experts. People with verifiable credentials or professional experience (software engineers, lawyers, physicians, mathematicians), recruited directly or through expert networks. They are scarce and expensive, and are needed where a non-expert cannot tell a good answer from a fluent wrong one, as in W2 transcript review and W3 legal rubrics.
- Internal staff. Researchers and specialists inside the organisation. They write guidelines, author gold items, label pilot batches, adjudicate disagreements and audit vendor output. They are rarely the main labour source but they anchor the definition of a correct label.
Before a worker's labels enter training data, the worker passes qualification: a sequence of gates, each of which collects evidence that the worker understands the task and does it carefully. The sequence runs in time order. A screen checks identity, eligibility and any required credential. An exam presents items with known answers (gold items) and compares the worker's answers with them. A calibration round has the worker label real-looking items, then shows them the reference answers and the reasoning, so they can adjust to the guidelines. Probation lets the worker label live items with a higher share of hidden gold, so that their accuracy is measured on the real task. A worker who clears probation becomes active and stays under continuous monitoring (Chapter 6); a worker who fails a gate after a fair sample is re-trained or removed, with the reason recorded and an appeal route open. Onboarding is everything around those gates that lets a worker succeed: guidelines with worked examples, a practice environment, a channel to ask questions, and paid time to read and learn.
Published lab practice shows both ends of the design space. For InstructGPT, Ouyang et al. (2022) recruited about 40 contractors through Upwork and Scale AI and selected them with a screening test that measured sensitivity to the preferences of different demographic groups and the ability to identify potentially harmful outputs; trained labelers agreed with each other 72.6 ± 1.5% of the time. For the Anthropic helpful-and-harmless data, Bai et al. (2022) restricted Mechanical Turk to master-qualified US workers after finding lower quality in the general and international pools, did not filter on agreement, and kept roughly 20 prolific workers, who produced about 80% of the data, in a channel for direct communication; Upwork workers were paid hourly, which made very high-quality interactions easier to incentivise.
Compared with the older crowdsourcing model, in which any qualified marketplace worker could take any task, frontier RL data has moved toward managed teams and experts, because the tasks need long context, domain knowledge and consistency across thousands of items. The cost is higher rates, longer start-up and dependence on a few suppliers. The decision a builder faces is which population each task type needs. The recommended default is: internal staff for gold and adjudication, managed vendor raters for high-volume judgments that a trained generalist can make, experts wherever correctness needs credentials, and the open crowd only for short tasks or where demographic breadth is the point. Every population passes the same staged gates; only thresholds and evidence differ.
Qualification is a measurement problem with a budget. Each gate estimates a worker's true accuracy \(p\) from a finite number \(n\) of gold items, and each item costs paid worker time. Too few items let weak workers through by luck; too many waste money and delay start.
How many items an exam needs. If a worker answers each gold item correctly with probability \(p\), independently, the number correct \(K\) follows a binomial distribution, and the probability of passing with a mark of at least \(k\) out of \(n\) is
\[ P_{\text{pass}}(p) = \sum_{i=k}^{n} \binom{n}{i} p^{i} (1-p)^{n-i}. \]With \(n = 20\) and a pass mark of 16 (80%), a worker whose true accuracy is 70% passes with probability about 0.24, and a worker at 85% passes with probability about 0.83. With \(n = 40\) and a pass mark of 33, the 70% worker passes about 0.06 of the time. A cleaner way to set the mark is to require the lower end of a confidence interval on accuracy to clear a bar. The Wilson score lower bound for \(K\) correct out of \(n\) at about 95% confidence (\(z = 1.96\)) is
\[ L(K, n) = \frac{\hat p + \frac{z^2}{2n} - z\sqrt{\frac{\hat p(1-\hat p)}{n} + \frac{z^2}{4n^2}}}{1 + \frac{z^2}{n}}, \qquad \hat p = K/n. \]Requiring \(L \ge 0.66\) with \(n = 40\) means at least 33 correct (\(L = 0.680\)); 32 correct gives \(L = 0.652\) and does not pass. At probation, with 100 live gold items, requiring \(L \ge 0.72\) means at least 81 correct, which is consistent with the 80% policy line while allowing for sampling noise.
How many applicants a pool needs. If stage pass rates are \(r_1, r_2, \dots\), the number of applicants \(A\) required for \(N\) active workers is \(A = N / \prod_j r_j\). The pass rates below are assumptions for illustration, not published values.
| Population | Price signal | Start-up | Identity and skill evidence | Best use |
|---|---|---|---|---|
| Open crowd | Prolific minimum £6/h, recommended at least £9/h (Prolific) | hours | platform verification, short exam | short judgments, demographic breadth |
| Managed vendor | $40/h in W1 | days | vendor training plus platform gates | high-volume trained judgments |
| Domain expert | $120/h in W2 | days to weeks | credential check, expert exam | transcripts, rubrics, specialist domains |
| Internal staff | salary | immediate | known | gold, adjudication, pilots, audits |
The decision to make here is exam length and threshold per population. The recommended default is a Wilson-bound gate with 40 items for generalist raters and 15 to 20 items for experts (whose items are longer and costlier), each followed by a probation window with at least 100 live gold labels. Deviate toward longer exams when a single bad worker can do outsized damage, such as a rubric author whose rubric becomes an RL reward for thousands of rollouts.
The qualification system is a per-worker state machine. Each worker has a stage; each stage has a gate defined by a minimum number of gold items, a minimum Wilson lower bound on accuracy, and a maximum share of suspiciously fast answers. The machine holds a worker until there is enough evidence, advances them when the gate is met, and removes them only after they have had twice the minimum sample. The code below is self-contained and runs as a test.
"""Staged qualification for a rater population (W1 values).
Stages: screen -> exam -> calibration -> probation -> active. Each gate uses the
Wilson lower bound of gold accuracy so a lucky short exam cannot pass a weak rater."""
from dataclasses import dataclass, field
from math import sqrt
from enum import Enum
class Stage(str, Enum):
SCREEN = "screen"; EXAM = "exam"; CALIBRATION = "calibration"
PROBATION = "probation"; ACTIVE = "active"; REMOVED = "removed"
@dataclass(frozen=True)
class Gate:
min_items: int # gold items needed before the gate can decide
min_lower_bound: float # Wilson 95% lower bound on gold accuracy
max_fast_share: float # share of items answered faster than fast_s seconds
fast_s: float = 40.0
GATES = { # W1 policy: 80% gold threshold, < 40 s counts as a low-effort answer
Stage.EXAM: Gate(min_items=40, min_lower_bound=0.66, max_fast_share=0.10),
Stage.CALIBRATION: Gate(min_items=30, min_lower_bound=0.66, max_fast_share=0.10),
Stage.PROBATION: Gate(min_items=100, min_lower_bound=0.72, max_fast_share=0.05),
}
NEXT = {Stage.EXAM: Stage.CALIBRATION, Stage.CALIBRATION: Stage.PROBATION,
Stage.PROBATION: Stage.ACTIVE}
def wilson_lower(k: int, n: int, z: float = 1.96) -> float:
"""95% Wilson score lower bound for k successes out of n."""
if n == 0:
return 0.0
p = k / n
den = 1 + z * z / n
centre = p + z * z / (2 * n)
margin = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n))
return (centre - margin) / den
@dataclass
class Rater:
rater_id: str
stage: Stage = Stage.EXAM
gold: list = field(default_factory=list) # (correct: bool, seconds: float) in current stage
def record(self, correct: bool, seconds: float) -> None:
self.gold.append((correct, seconds))
def evaluate(self) -> Stage:
"""Advance, hold or remove; returns the (possibly new) stage."""
gate = GATES.get(self.stage)
if gate is None or len(self.gold) < gate.min_items:
return self.stage # not enough evidence yet: hold
k = sum(c for c, _ in self.gold)
n = len(self.gold)
fast = sum(s < gate.fast_s for _, s in self.gold) / n
if wilson_lower(k, n) >= gate.min_lower_bound and fast <= gate.max_fast_share:
self.stage, self.gold = NEXT[self.stage], []
elif n >= 2 * gate.min_items: # had a fair chance and still fails
self.stage = Stage.REMOVED
return self.stage
def funnel(target_active: int, rates: dict) -> int:
"""Applicants needed so that `target_active` survive every stage pass rate."""
need = target_active
for r in rates.values():
need /= r
return int(-(-need // 1)) # ceiling
if __name__ == "__main__":
# 1) Wilson bound: 34/40 = 85% observed, lower bound must clear 0.66
assert abs(wilson_lower(34, 40) - 0.709) < 0.002
# 2) A rater at 85% with normal speed passes the exam gate after 40 items
r = Rater("w1_r001")
for i in range(40):
r.record(correct=(i % 20) not in (0, 7, 13), seconds=210) # 34/40 correct
assert r.evaluate() == Stage.CALIBRATION
# 3) Same accuracy but 20% of answers under 40 s is held, then removed at 80 items
r2 = Rater("w1_r002")
for i in range(80):
r2.record(correct=(i % 20) not in (0, 7, 13), seconds=30 if i % 5 == 0 else 210)
assert r2.evaluate() == Stage.REMOVED
# 4) Funnel for 150 active raters (illustrative pass rates)
n = funnel(150, {"exam": 0.40, "calibration": 0.75, "probation": 0.85})
assert n == 589, n
print("qualify ok; applicants needed:", n)
Running python3 qualify.py prints qualify ok; applicants needed: 589. The four assertions check the arithmetic (34 of 40 correct gives a lower bound of 0.709), the happy path (an 85% worker advances to calibration), the effort rule (the same accuracy with 20% of answers under 40 seconds is removed once the worker has 80 items) and the funnel used in the W1 plan. The gate configuration that a campaign references lives in a separate versioned file:
# qualification/w1_exam_v3.yaml
id: w1_exam_v3
population: vendor_rater
item_bank: w1_gold_bank_v3 # 400 items; each worker draws 40 at random
draw_without_replacement: true
gates:
exam: {min_items: 40, min_wilson_lb: 0.66, max_fast_share: 0.10, fast_s: 40}
calibration: {min_items: 30, min_wilson_lb: 0.66, max_fast_share: 0.10, show_rationale: true}
probation: {min_items: 100, min_wilson_lb: 0.72, max_fast_share: 0.05, gold_share: 0.15}
paid: true # exam and calibration time paid at the campaign rate
appeal: {channel: grievance_form, sla_days: 5}
requalify_after_days_inactive: 30
Debugging tips. If pass rates look too high, compare the distribution of exam answer vectors: identical wrong answers across many workers indicate a leaked bank. If they look too low, check gold-item quality before blaming workers; a gold item that internal staff themselves disagree on should be retired. Always store which bank version and which items each worker saw, so an exam can be re-scored after a gold correction.
In production, qualification is a supply chain: if it slows, campaigns starve; if it leaks, bad labels flow into training. Both failures are measurable before they reach a reward model.
| Indicator | Formula | Target / alert |
|---|---|---|
| Time to qualify | p50 hours from screen pass to active | p50 ≤ 72 h; alert at 120 h |
| Exam pass rate by cohort | passed ÷ completed, per vendor per week | alert if outside the trailing 4-week band ± 15 points |
| Probation survival | reached active ÷ entered probation | alert below 70% |
| Exam-to-live gap | exam accuracy − probation gold accuracy, per cohort | alert above 10 points |
| Answer-vector similarity | share of exam pairs with ≥ 90% identical answers including wrong ones | alert above 2% |
Symptom: a new vendor cohort of 60 raters shows an exam pass rate of 78% against a trailing band around 40%. The capacity dashboard looks healthy, so nobody intervenes at first.
Measurements that separate causes: (1) answer-vector similarity for the cohort is 31%, against under 1% historically, and many shared vectors include the same wrong answers; (2) median exam time per item is 55 seconds against 3.8 minutes for earlier cohorts; (3) the exam-to-live gap is 17 points, with probation gold accuracy of 71% against 84% for the previous cohort. An easier exam would raise pass rates without raising similarity; a leaked bank raises all three. The evidence points to a leak.
Remedy, in order: freeze the cohort at probation so no new labels count; quarantine their labels already accepted (60 raters × about 10 hours × 13 labels per hour ≈ 7,800 labels, of which those not double-labelled are re-queued); rotate to a new bank version drawn from a 400-item pool with per-worker random draws; re-examine the cohort under supervision; notify the vendor under the contract's integrity clause. Cost: about 7,800 × 4.5 minutes ≈ 585 rater-hours of relabelling, roughly $23,400 at $40 per hour, plus the re-exam.
Validation: on the new bank the re-examined cohort's pass rate should fall back near the historical band, and the exam-to-live gap of those who pass should fall under 10 points. If the gap stays high after rotation, the problem is not the bank but the exam's fit to the live task, and the exam items need redesign.
Runbook for a suspected qualification leak:
- Confirm with two independent signals (similarity and exam-to-live gap). One signal alone triggers investigation, not action.
- Pause promotions for the affected cohort; do not remove workers yet, and keep paying for completed work.
- Quarantine labels by cohort tag; re-queue single-labelled items, keep overlapped items whose other labels agree.
- Rotate the bank and enable random per-worker draws; check the new bank against internal-staff agreement.
- Re-examine; remove only workers who fail the new gate after a full sample, with recorded reasons and an appeal route.
The trade-off is speed against fairness: quarantining by cohort penalises honest workers in that cohort for a short time. Keeping pay for completed work and re-examining rather than removing preserves trust while protecting the data, which is what the next section's vendor contracts need to make enforceable.
Integrating vendor platforms
A data vendor is a company that supplies human judgment as a service: it recruits, trains, supervises and pays workers, runs its own quality checks, and delivers labelled results under a contract. Platforms use vendors because they provide capacity that an organisation cannot staff quickly, specialist pools such as licensed professionals in many countries, and a legal employer or contracting entity in each worker's jurisdiction. The cost is that the people doing the work sit behind another company's systems, and the platform sees them only through an interface.
Vendor integration is the software that makes that interface reliable. It has five parts, which act in this order for every task.
- Routing. A router chooses which vendor receives a task, using the task's required population, each vendor's remaining contracted capacity, its recent health, and its cost per useful result.
- Task handoff. An adapter translates the platform's task into the vendor's API call and sends it. The handoff carries the platform's task id as an idempotency key: a value that makes repeated submissions of the same task create only one vendor task, so a network retry cannot double the work or the bill. There are two handoff styles. In the push style the platform sends the task content to the vendor, whose own tool shows it to workers. In the embedded style the vendor supplies people and the platform hosts the interface; the vendor task carries only a link and a token, and labels are written directly into the platform.
- Completion signal. When a worker finishes, the vendor calls a webhook: an HTTPS endpoint the platform exposes, to which the vendor posts an event. The receiver verifies that the event really comes from the vendor, records it, and acknowledges with a success status.
- Reconciliation. Webhooks can be lost, rejected or delayed. A reconciler periodically asks the vendor's API about tasks whose result is overdue and records any it finds. The ledger, not the webhook, is the source of truth.
- Service levels. A service-level agreement (SLA) is the contract term that says how quickly and how reliably the vendor returns results, how quality is measured, and what happens when targets are missed. The platform measures each term itself rather than relying on vendor reports.
Public vendor documentation shows what these mechanisms look like in practice. Scale AI's API lets a task carry a callback_url; when the task completes, errors, changes audit status or is recalled, Scale posts a JSON body containing the task id, status, response and full task object, sets a scale-callback-auth header equal to the customer's callback key, and, if it does not receive a 2xx response, retries up to 20 times over the next 24 hours; a separate endpoint resends a callback on demand (Scale AI, callbacks). Prolific's webhooks sign each request with HMAC-SHA256 over the timestamp and body, base64-encoded, in an X-Prolific-Request-Signature header with an X-Prolific-Request-Timestamp, and publish event types such as submission.status.change, study.status.change and study.has_high_return_rate (Prolific, verifying webhooks; receiving). The two schemes differ: a shared secret proves the sender knows a key, while an HMAC signature also proves the body was not altered.
Compared with a single vendor, several vendors give resilience and price competition but add calibration work, because each vendor's raters drift toward their own interpretation of the guidelines. Compared with the push style, the embedded style keeps data, instrumentation and quality logic in one place at the cost of running an interface that external workers must reach. The recommended default is embedded handoff, at least two vendors for any population that a campaign depends on, signed webhooks plus reconciliation, and SLA terms measured by the platform. Deviate toward the push style when a vendor's specialised tooling is the reason for using that vendor, for example a medical vendor with regulated infrastructure.
Three quantities govern vendor design: how long results take to arrive, how often they fail to arrive, and what each useful result costs. Each has a simple model.
Work in flight. Little's law states that the average number of items in a system \(L\) equals the arrival rate \(\lambda\) times the average time each spends inside, \(W\): \(L = \lambda W\). It holds for any stable queue and needs no distributional assumption. Applied to a vendor, \(L\) is the number of tasks handed off but not yet returned.
Lost and late results. Suppose a fraction \(f\) of webhook deliveries fails on the first attempt and the vendor retries over a window of \(T_r\). Results are permanently missing only if every retry fails and nobody polls. With reconciliation every \(\Delta\) minutes for tasks older than a grace period \(g\), the worst-case delay for a result whose callback was lost is about \(g + \Delta\), independent of the vendor's retry policy. A design with \(g = 60\) minutes and \(\Delta = 15\) minutes bounds that delay at about 75 minutes; relying on retries alone can stretch it to the vendor's full window, which is 24 hours in Scale's published policy.
Availability with several vendors. If vendor \(i\) is available a fraction \(a_i\) of the time and outages are independent, the probability that at least one of two is available is \(1 - (1 - a_1)(1 - a_2)\). Two vendors at 0.98 each give 0.9996. The independence assumption is optimistic: vendors may share workers, payment processors or cloud regions, so the benefit is real but smaller than the formula suggests.
Cost per useful result. A vendor's price per hour \(c\), mean minutes per item \(m\) and QA rejection rate \(q\) give a cost per accepted item of \(u = c \cdot m / 60 / (1 - q)\). This excludes gold and overlap overhead, which apply equally to every vendor and so do not change the ranking.
| Decision | Option A | Option B | Default |
|---|---|---|---|
| Handoff style | push content to vendor tool | embed platform interface, pass link | embed, unless vendor tooling is the reason to buy |
| Completion signal | webhook only | webhook plus reconciliation poll | both; the ledger is truth |
| Webhook authentication | shared secret header | HMAC of timestamp and body | HMAC where offered; reject stale timestamps |
| Vendor count per population | one | two or more | two, with a share floor so the second stays calibrated |
| Routing objective | lowest hourly rate | lowest cost per useful item, subject to capacity and health | cost per useful item |
The decision a builder faces is how much of the vendor relationship to encode. The recommended default is to encode capacity, health, cost per useful item and SLA measurement in the router and the ledger, and to keep a minimum share (for example 20%) on each qualified vendor so a failover does not land work on raters who have not seen the current guidelines.
The integration core has four pieces: an adapter interface each vendor implements, webhook verifiers, an idempotent ledger, and a router plus reconciler. The module below is runnable and its test mirrors the W1 routing numbers. The two verifiers implement the schemes from the public documentation cited above; the timestamp freshness check in verify_hmac is an addition of this book, since replay protection is not described on the vendor's page.
"""Vendor integration core: idempotent handoff, signed webhooks, dedupe, routing, reconciliation.
The two verifiers mirror public vendor docs: a shared-secret header (Scale-style
`scale-callback-auth`) and an HMAC-SHA256 over timestamp+body, base64 (Prolific-style)."""
import base64, hashlib, hmac, json, time
from dataclasses import dataclass, field
from typing import Protocol
# ---------- outbound: the adapter contract every vendor implements ----------
@dataclass(frozen=True)
class TaskSpec:
task_id: str # our id; doubles as the vendor idempotency key
campaign: str
payload: dict # prompt, two responses, rubric version...
deadline_s: int # SLA for a result
population: str # "vendor_rater" | "domain_expert"
class VendorAdapter(Protocol):
name: str
def submit(self, task: TaskSpec) -> str: ... # returns vendor task id
def fetch(self, vendor_task_id: str) -> dict: ... # for reconciliation polls
def cancel(self, vendor_task_id: str) -> None: ...
class FakeVendor:
"""In-memory adapter used in tests; idempotent on task_id like a real API should be."""
def __init__(self, name):
self.name, self.by_key, self.results = name, {}, {}
def submit(self, task):
return self.by_key.setdefault(task.task_id, f"{self.name}-{len(self.by_key) + 1}")
def fetch(self, vid):
return self.results.get(vid, {"status": "pending"})
def cancel(self, vid):
self.results[vid] = {"status": "canceled"}
# ---------- inbound: webhook verification ----------
def verify_shared_secret(headers: dict, expected: str, header="scale-callback-auth") -> bool:
return hmac.compare_digest(headers.get(header, ""), expected)
def verify_hmac(headers: dict, raw_body: bytes, secret: bytes, max_skew_s=300, now=None) -> bool:
ts = headers.get("X-Prolific-Request-Timestamp", "")
sig = headers.get("X-Prolific-Request-Signature", "")
now = time.time() if now is None else now
if not ts.isdigit() or abs(now - int(ts)) > max_skew_s: # replay window (our addition)
return False
mac = hmac.new(secret, ts.encode() + raw_body, hashlib.sha256).digest()
return hmac.compare_digest(base64.b64encode(mac).decode(), sig)
# ---------- inbound: idempotent result ingestion ----------
@dataclass
class Ledger:
"""Stand-in for a table with UNIQUE(vendor, event_key)."""
seen: set = field(default_factory=set)
results: dict = field(default_factory=dict)
def ingest(self, vendor: str, event: dict) -> str:
key = (vendor, event["task_id"], event["status"], event.get("revision", 0))
if key in self.seen:
return "duplicate" # retries and re-sends land here
self.seen.add(key)
if event["status"] == "completed":
self.results[event["task_id"]] = event["response"]
return "stored"
# ---------- routing across vendors ----------
@dataclass
class VendorState:
name: str
rate_per_h: float # $ per worker-hour billed
minutes_per_item: float
reject_rate: float # share of results failing the QA
free_hours: float # contracted capacity left this week
healthy: bool = True # circuit breaker state from handoff/callback errors
def cost_per_useful(self) -> float:
return self.rate_per_h * self.minutes_per_item / 60 / (1 - self.reject_rate)
def route(task: TaskSpec, vendors: list, allowed: dict) -> VendorState:
"""Cheapest cost per *useful* item among healthy vendors allowed for the population
with capacity left; raises if none (caller pauses intake instead of overcommitting)."""
ok = [v for v in vendors if v.healthy and v.name in allowed[task.population]
and v.free_hours >= v.minutes_per_item / 60]
if not ok:
raise RuntimeError("no vendor capacity: pause intake")
best = min(ok, key=VendorState.cost_per_useful)
best.free_hours -= best.minutes_per_item / 60
return best
# ---------- reconciliation: catch lost callbacks ----------
def reconcile(outstanding: dict, adapter, ledger: Ledger, now: float, grace_s: float):
"""outstanding: task_id -> (vendor_task_id, submitted_at). Poll anything older than grace."""
recovered = []
for tid, (vid, t0) in list(outstanding.items()):
if now - t0 < grace_s or tid in ledger.results:
continue
r = adapter.fetch(vid)
if r["status"] == "completed":
ledger.ingest(adapter.name, {"task_id": tid, "status": "completed", "response": r["response"]})
recovered.append(tid)
for tid in recovered:
outstanding.pop(tid)
return recovered
if __name__ == "__main__":
t = TaskSpec("w1_cmp_000123", "w1", {"prompt": "..."}, deadline_s=86400, population="vendor_rater")
a = FakeVendor("vendorA")
assert a.submit(t) == a.submit(t) # idempotent handoff
# signed webhook, Prolific-style
secret, body, ts = b"s3cr3t", b'{"event_type":"submission.status.change"}', "1762700000"
sig = base64.b64encode(hmac.new(secret, ts.encode() + body, hashlib.sha256).digest()).decode()
h = {"X-Prolific-Request-Timestamp": ts, "X-Prolific-Request-Signature": sig}
assert verify_hmac(h, body, secret, now=1762700100)
assert not verify_hmac(h, body + b" ", secret, now=1762700100) # tampered body
assert not verify_hmac(h, body, secret, now=1762700000 + 3600) # stale replay
assert verify_shared_secret({"scale-callback-auth": "k"}, "k")
# duplicate deliveries are absorbed
L = Ledger(); ev = {"task_id": t.task_id, "status": "completed", "response": {"choice": "B"}}
assert [L.ingest("vendorA", ev) for _ in range(3)] == ["stored", "duplicate", "duplicate"]
# routing on cost per useful comparison (W1: $40/h, 4.5 min, 8% reject -> $3.26)
A = VendorState("vendorA", 40, 4.5, 0.08, free_hours=1000)
B = VendorState("vendorB", 32, 5.0, 0.20, free_hours=1000)
assert round(A.cost_per_useful(), 2) == 3.26 and round(B.cost_per_useful(), 2) == 3.33
assert route(t, [A, B], {"vendor_rater": {"vendorA", "vendorB"}}).name == "vendorA"
A.healthy = False
assert route(t, [A, B], {"vendor_rater": {"vendorA", "vendorB"}}).name == "vendorB"
# reconciliation recovers a result whose callback never arrived
vid = a.submit(t); a.results[vid] = {"status": "completed", "response": {"choice": "A"}}
L2, out = Ledger(), {t.task_id: (vid, 0.0)}
assert reconcile(out, a, L2, now=7200, grace_s=3600) == [t.task_id] and not out
print("vendor ok")
Running python3 vendor.py prints vendor ok. The handoff payload is a versioned schema, so every vendor adapter maps from the same structure:
{
"$id": "handoff/v2",
"type": "object",
"required": ["task_id", "campaign", "population", "deadline_s", "mode"],
"properties": {
"task_id": {"type": "string", "description": "our id; sent as vendor idempotency key / unique id"},
"campaign": {"type": "string"},
"population": {"enum": ["vendor_rater", "domain_expert"]},
"deadline_s": {"type": "integer", "minimum": 600},
"mode": {"enum": ["embedded", "push"]},
"embed_url": {"type": "string", "description": "embedded mode: signed, single-use link to our UI"},
"content": {"type": "object", "description": "push mode only: prompt, responses, rubric version"},
"sensitivity":{"type": "integer", "minimum": 0, "maximum": 3, "description": "drives opt-in and blur (welfare section)"},
"est_minutes":{"type": "number"}
}
}
The receiver itself is thin: read the raw body bytes before any JSON parsing (re-serialising changes the bytes and breaks the signature), verify, write the event to the inbox table with a unique constraint, return 200, and process asynchronously. Returning 200 only after downstream processing couples vendor retries to the platform's slowest dependency. Debugging tips: log the vendor event id and the computed signature prefix on rejection; keep two active secrets during rotation; and alert on the ratio of duplicate to stored events, since a sudden rise means acknowledgements are failing even though processing succeeds.
Vendor integration fails quietly. A vendor can complete work that the platform never records, and every dashboard downstream of the ledger looks merely slow. The service levels below make the gap visible.
| Indicator | Definition | SLO | Page when |
|---|---|---|---|
| Handoff success | tasks accepted by vendor ÷ tasks submitted, 1 h window | ≥ 99.9% | < 99% for 15 min |
| Callback lag | recorded_at − vendor completed_at, p95 | ≤ 10 min | > 60 min for 30 min |
| Reconciliation gap | vendor-completed − ledger-recorded, tasks older than 1 h | ≤ 0.5% of in-flight | > 200 tasks |
| Webhook rejects | signature failures ÷ deliveries, 15 min | ≈ 0 | > 1% |
| Vendor SLA attainment | results within contracted deadline, per vendor per week | per contract (e.g. 95% within 24 h) | weekly review |
Symptom: during collection, the W1 ledger's recorded-results curve goes flat for one vendor while that vendor's own console shows raters completing work at the normal rate of about 238 assignments an hour across the pool.
Measurements: webhook rejects for that vendor jump from 0% to 100% at the moment a scheduled secret rotation ran; handoff success is unchanged; the reconciler is enabled but its grace period had been set to 24 hours during an earlier debugging session. Callback lag p95 crosses 2 hours three hours after the rotation and pages on-call.
Diagnosis: the platform rotated its secret but the vendor still signs with the old one, so every callback fails verification and the vendor keeps retrying. Because labels in the embedded mode are written straight into the platform, no labels are lost; what is lost is the completion state, so tasks look unfinished, the router re-offers some of them, and the vendor's invoice and the platform's ledger disagree.
Remedy: accept both secrets for a rotation window; reduce the reconciler grace back to 60 minutes; call the vendor's resend endpoint for the backlog; cancel duplicate re-offers. About 1,200 completions were unrecorded at peak, five hours after rotation. Cost: about 90 duplicate assignments were issued before cancellation, roughly 7 rater-hours or $270, plus on-call time.
Validation: the reconciliation gap returns to under 0.5% of in-flight work within an hour, and the vendor's weekly invoice count matches the ledger within the duplicate count. If the gap does not close after the secret fix, something other than authentication is failing, and the next check is the receiver's own error logs.
Runbook for a vendor result gap:
- Compare the vendor's completed count with the ledger's recorded count for the last 6 hours. If they match, the problem is upstream (raters, interface); go to the throughput runbook.
- If they differ, check webhook rejects. Rejects near 100% point to authentication (rotation, key mismatch, header change); rejects near 0 with a gap point to delivery (DNS, TLS, firewall, receiver down).
- Restore acceptance (dual secrets or rollback); never disable verification.
- Shorten the reconciler grace and drain the backlog; use the vendor's resend endpoint where one exists.
- Deduplicate re-offered tasks by task id; reconcile the invoice before payment.
- Add a test for the failure (here, a rotation test in staging that sends a signed event with the old and new secret).
Multi-vendor failover has its own cost. If one W1 vendor goes down entirely, routing its share to the second vendor works only if that vendor has spare qualified capacity and current calibration. The share floor in the router keeps both calibrated; the price of that resilience is paying the slightly more expensive vendor for a fixed fraction of work at all times, about $0.07 per useful comparison on the 20% of work it carries in the W1 numbers above.
Pay, incentives and throughput planning
Pay design decides three things at once: what the work costs, how people do it, and whether they stay. A pay model is the rule that turns work into money. The main models are:
- Hourly pay. The worker is paid for logged time. It rewards care and suits long, variable tasks such as transcript review, but it needs time tracking and quality monitoring so that slow, low-effort work is visible.
- Piece rate. A fixed price per completed item. It is simple to budget and rewards speed, which is exactly the problem on tasks where speed trades against care: a rater who rushes a comparison earns more per hour.
- Hybrid. An hourly or per-item base plus a quality bonus paid when measured quality (for example gold accuracy over a window) clears a bar. The bonus must be tied to quality signals the worker cannot game cheaply, and its criteria must be published.
Several published guidelines set floors for any model. The Partnership on AI's data enrichment guidelines ask for at least the local living wage, computed over all task time including reading instructions, training and review; for per-task pay they derive the price from the hourly living wage and an adjusted number of tasks per hour; and they ask that completed work be paid unless there is obvious abuse or fraud, with completion times tracked so targets and pay can be adjusted (Partnership on AI). Google DeepMind described adopting a five-step process developed with PAI whose first step is a payment model that pays all workers above the local living wage (Google DeepMind, 2022). Prolific sets a platform minimum of £6 per hour and recommends at least £9 (Prolific). The reason these rules mention unpaid time is empirical: an analysis of 3.8 million Mechanical Turk tasks by 2,676 workers estimated median earnings of about $2 per hour, with only about 4% earning more than $7.25, and showed that the estimate depends heavily on unpaid time spent searching for tasks and on rejected or abandoned work (Hara et al., 2018).
Throughput planning is the arithmetic that connects the campaign spec to people and money. It runs as a chain. The number of unique items, multiplied up by overlap (items labelled more than once) gives labels; gold items add assignments; mean minutes per assignment give worker-hours; the pool's weekly hours give the duration; the hourly rate gives the cost; and the share of items that survive quality review gives the cost per useful item.
Published lab practice illustrates the incentive effects. Bai et al. (2022) found hourly pay on Upwork made very high-quality interactions easier to incentivise than per-task pay, and raised pay for slower interactions after workers flagged that the slower models made tasks take longer. Compared with per-task pricing set once at launch, hourly pay with measured time removes the incentive to rush, at the cost of needing effort monitoring (Chapter 6). The recommended default is hourly pay at or above the living-wage floor for all paid activities, a published quality bonus for long-running pools, and piece rates only when the price is derived from measured mean time plus overhead and re-checked weekly.
The planning model needs a handful of symbols. Let \(N\) be unique items, \(s\) the share overlapped, \(k\) the labels per overlapped item, \(g\) the gold share of assignments, \(\bar t\) the mean minutes per assignment, \(c\) the hourly rate, \(q\) the share of items rejected by QA, \(P\) workers, \(h\) paid hours per worker per week and \(\eta\) the utilisation (share of paid hours spent on assignments).
\[ \text{labels} = N(1-s) + N s k, \qquad A = \frac{\text{labels}}{1-g}, \qquad H = \frac{A\,\bar t}{60}, \] \[ \text{weeks} = \frac{H}{P\,h\,\eta}, \qquad \text{cost} = H c, \qquad \text{cost per useful item} = \frac{H c}{N (1 - q)}. \]Effective hourly pay under a piece rate. If the price per item is \(\pi\) and a worker takes \(t\) minutes per item plus \(o\) minutes of unpaid overhead per item (loading, reading, waiting for samples), their effective rate is
\[ e = \frac{60\,\pi}{t + o}. \]A price derived from the median time underpays the typical worker, because task times are right-skewed and the mean exceeds the median.
Staffing for a deadline. To finish \(H\) hours in \(D\) working days with each worker contributing \(d\) productive hours a day, the pool needs \(\lceil H / (D\,d) \rceil\) workers. The W1 request-to-mix baseline spends 6 days in collection; the plan of record for the 7-day target (Chapter 8) collects in about 4 days by scheduling about 10.5% more rater-hours from the same pool. A tighter window shows where the pool runs out: if collection must shrink to 2 days at 6 productive hours per worker-day, W1 needs \(\lceil 1{,}895 / 12 \rceil = 158\) concurrently available raters, slightly more than the 150 in the pool, and all of them must be available on the same two days. The cost does not change; the constraint is concentration of availability, which is usually bought with scheduling commitments and a premium rather than with more raters.
Bonus cost. A bonus of fraction \(b\) of base pay, earned by a share \(\phi\) of workers, adds \(b\phi\) to labour cost. A 10% bonus earned by 60% of W1 raters adds 6%, about $4,550. Whether it pays for itself depends on whether it reduces the 8% rejection rate; each percentage point of rejects removed saves about $760 of wasted labour in W1 (1% of $75,780). Evidence on how much pay level alone improves annotation quality is mixed, so the bonus should be tested as an experiment, not assumed.
The decision a builder faces is the pay model per population. The recommended default is hourly for experts and for any task with high time variance, hybrid for large trained pools, and piece rates only with the mean-plus-overhead price and a measured effective-rate floor. Deviate when a vendor's contract fixes the model; then compute and monitor \(e\) from the platform's own timing data anyway.
The planner is a pure function from a campaign description and a pool to hours, weeks, cost and cost per useful item, plus helpers for piece pricing, effective pay and staffing. Keeping it pure makes it usable in three places: the campaign launcher (Chapter 3) shows the plan before launch, the cost dashboard (Chapter 11) compares plan with actuals, and tests pin the example-sheet numbers.
"""Throughput, cost and pay planning for a labelling campaign (W1 and W2 values)."""
from dataclasses import dataclass
@dataclass(frozen=True)
class Campaign:
name: str
items: int # unique items (comparisons, transcripts)
overlap_share: float # share of items labelled by more than one worker
overlap_k: int # labels per overlapped item
gold_share: float # gold assignments as a share of all assignments
mean_min: float # mean minutes per assignment
rate_per_h: float # $ per worker-hour
reject_share: float # share of items lost to QA
@dataclass(frozen=True)
class Pool:
workers: int
hours_per_week: float
utilisation: float = 1.0 # share of paid hours spent on assignments
def plan(c: Campaign, p: Pool) -> dict:
labels = c.items * (1 - c.overlap_share) + c.items * c.overlap_share * c.overlap_k
assignments = labels / (1 - c.gold_share)
hours = assignments * c.mean_min / 60
cap = p.workers * p.hours_per_week * p.utilisation
labour = hours * c.rate_per_h
useful = c.items * (1 - c.reject_share)
return {"labels": round(labels), "assignments": round(assignments), "hours": round(hours, 1),
"weeks": round(hours / cap, 2), "labour_usd": round(labour),
"usd_per_useful": round(labour / useful, 2)}
def piece_rate(target_hourly: float, planning_min: float) -> float:
"""Per-item price that pays target_hourly at the planning time per item."""
return target_hourly * planning_min / 60
def effective_hourly(price: float, minutes: float, unpaid_min_per_item: float = 0.0) -> float:
"""What a worker actually earns per hour given their own pace and unpaid overhead."""
return price * 60 / (minutes + unpaid_min_per_item)
def workers_needed(hours: float, days: float, h_per_worker_day: float, util: float = 1.0) -> int:
return int(-(-hours // (days * h_per_worker_day * util)))
W1 = Campaign("w1", 20_000, 0.10, 3, 0.05, 4.5, 40.0, 0.08)
W1_POOL = Pool(150, 20)
W2 = Campaign("w2", 2_000, 0.0, 1, 0.0, 35.0, 120.0, 0.0)
W2_POOL = Pool(40, 15)
if __name__ == "__main__":
r1 = plan(W1, W1_POOL)
assert r1["labels"] == 24_000 and r1["assignments"] == 25_263, r1 # sheet rounds to 25,260
assert abs(r1["hours"] - 1895) < 1 and r1["weeks"] == 0.63
assert abs(r1["labour_usd"] - 75_790) < 15 and r1["usd_per_useful"] == 4.12
r2 = plan(W2, W2_POOL)
assert round(r2["hours"]) == 1167 and r2["weeks"] == 1.94 and r2["labour_usd"] == 140_000
assert r2["labour_usd"] / W2.items == 70.0
# piece rate priced at the MEDIAN (4.0 min) underpays the average worker
price = piece_rate(40.0, 4.0)
assert round(price, 4) == 2.6667
assert round(effective_hourly(price, 4.5), 2) == 35.56
assert round(effective_hourly(price, 4.5, unpaid_min_per_item=0.5), 2) == 32.0
# priced at the mean plus paid overhead it meets the $40/h target
assert round(effective_hourly(piece_rate(40.0, 5.0), 4.5, 0.5), 2) == 40.0
# staffing W1 collection into 2 working days at 6 productive h/day
assert workers_needed(1895, 2, 6) == 158
print("plan ok", r1, r2)
Running python3 plan.py prints the W1 and W2 plans: 24,000 labels, 25,263 assignments, 1,894.7 hours, 0.63 weeks and $4.12 per useful comparison for W1; 1,166.7 hours, 1.94 weeks, $140,000 and $70 per transcript for W2. The tests also pin the piece-rate pitfall (pricing at the median yields $35.56 per hour for a mean-pace worker, $32.00 with overhead) and the staffing result of 158 raters for a two-day collection window. The policy that the pay system enforces is a separate file:
# pay/w2_expert_v1.yaml
population: domain_expert
model: hourly
rate_usd_per_h: 120.0
paid_activities: [onboarding, exam, calibration, review, double_review, guideline_feedback]
time_source: platform_active_time # not self-reported; idle > 10 min pauses the clock
idle_pause_min: 10
max_billable_min_per_transcript: 120 # above this, flag for review, still pay
bonus:
enabled: false # enable only as an A/B test with a stated metric
floor_check:
metric: p10_effective_usd_per_h
floor: 120.0
window_days: 7
action_below_floor: reprice_or_split_tasks
Debugging tips. When plan and actual hours diverge, check first whether \(\bar t\) was taken from the pilot's median rather than its mean, then whether the pilot population matches the production population (pilots run by internal staff are often faster). Store per-assignment active time, not only submit time minus open time, because the latter includes breaks and makes effective pay look worse than it is.
In production the planner's assumptions are measured every day: actual minutes per item, active pool size, rejection rate and effective pay. Divergence on any of them changes cost or schedule, and divergence on effective pay also changes who stays in the pool.
| Panel | Formula | Alert |
|---|---|---|
| Plan vs actual hours | cumulative active hours ÷ planned hours at same completion % | > 1.15 |
| Time per item | mean and median active minutes, daily, by population | mean > plan × 1.2 |
| Effective pay floor | p10 of earnings ÷ paid active hours, 7-day | < policy floor |
| Active pool | workers with ≥ 1 h in last 7 days | < 85% of planned |
| Rush share | workers with median time < 40 s (W1) | > 5% |
| Projected finish | remaining hours ÷ trailing 3-day hours per day | later than stage deadline |
Assume, for this scenario, that a vendor contract fixed W2 pay per transcript at $70, derived from the planned 35-minute mean at $120 per hour.
Symptom: after the first week, the active expert pool falls from 40 to 31, and projected completion moves from 1.94 weeks to more than 3.
Measurements: mean active time per transcript is 48 minutes, not 35; the pilot used shorter transcripts than the production sample. Effective pay at the mean is \(60 \times 70 / 48 = \$87.50\) per hour, 27% under the $120 floor; for the slowest decile it is under $70. Exit survey responses cite time per transcript. Required hours become \(2{,}000 \times 48 / 60 = 1{,}600\); with 31 experts at 15 hours, capacity is 465 hours a week, so the campaign needs about 3.4 weeks.
Options: (a) reprice to \(48 \times 120 / 60 = \$96\) per transcript, which raises labour from $140,000 to $192,000; (b) tier the price by transcript length (for example under 40 steps, 40 to 80, over 80), which pays the same total but pays fairly per transcript; (c) move to hourly pay with active-time tracking, which pays the true $192,000 and removes the incentive to hurry through long transcripts; (d) cut scope. Option (d) does not fix the underpayment of the work already done.
Chosen remedy: (c) for the remaining work, with back-pay for completed transcripts at the hourly rate. The extra cost is about $52,000 over plan. Validation: the active pool should recover toward 40 within a week and the p10 effective rate should sit at the floor; if the pool does not recover, pay was not the main cause of attrition and the next check is task design (for example transcript render latency, Chapter 5).
Runbook when effective pay falls below the floor:
- Confirm with active-time data (not wall-clock) over at least 100 completed items or 7 days.
- Find the cause: wrong time estimate, slower production items than pilot items, interface latency, or new guideline steps.
- Fix the price going forward and back-pay completed work to the floor; do not wait for the campaign to end.
- Update the planner's \(\bar t\), and re-project cost and finish date for the researcher who owns the campaign.
- Record the corrected time in the pilot template so the next campaign's estimate starts from the measured mean.
The trade-off is visible budget overrun against hidden cost: underpaying drives attrition, re-qualification of replacements (see Populations, qualification and onboarding), and rushing that shows up later as rejected labels. Paying to the floor is cheaper than it looks once those costs are counted, and it is the precondition for the welfare obligations in the next section.
Wellbeing, harmful content, ethics and societal impact
Harmful-content exposure is the repeated viewing, reading or writing of material that can injure the person handling it: graphic violence, sexual abuse, self-harm, hate, and detailed instructions for serious harm. RL data work produces this exposure in predictable places. Safety preference data asks raters to compare responses to harmful requests; red-teaming asks people to write attacks and read the results; refusal and policy data needs examples of what must be refused; and agentic transcripts can contain whatever a browsing or file tool returned. The exposure is part of the job design, so the platform that designs the job is responsible for limiting it.
The harm is documented. A 2023 investigation reported that workers in Kenya labelling text for a toxicity classifier through the outsourcing firm Sama took home about $1.32 to $2 per hour, while the contracts set a rate of $12.50 per hour paid to Sama; workers described nine-hour shifts and wellness sessions they found rare and unhelpful, which Sama disputed (Perrigo, TIME, 2023). In content moderation, Facebook agreed in 2020 to a $52 million settlement covering more than 11,000 current and former moderators (TechCrunch, 2020), and medical reports filed with Nairobi's employment and labour relations court in December 2024 stated that, of 185 former Facebook moderators in a legal claim who had worked for the outsourcing firm Samasource Kenya (now Sama), 144 were assessed by the head of mental health services at Kenyatta National Hospital, who classed 81% of them as having severe PTSD (Stockwell, CNN, 2024). In January 2025 contract workers filed a proposed class action against Scale AI and its Outlier platform alleging psychological harm from AI-training work involving violent content; Scale disputed the claims and pointed to advance notice of sensitive work, the option to opt out at any time, wellness programmes, and a refusal to take projects involving child sexual abuse material (The Register, 2025). These are reports and allegations, not adjudicated findings, but together they show the failure mode the platform must design against.
Protection works in layers, a structure taken from the review of moderator wellbeing by Steiger et al. (2021):
- Prevent exposure. Automated filters and hash-matching remove known material before a person sees it; the router sends sensitive items only to workers who have opted in after informed disclosure.
- Reduce impact while working. The interface blurs, greys out, shrinks or mutes severe content by default; the platform caps daily and weekly exposure, forces breaks, and mixes sensitive with benign tasks. In an experiment with crowd moderators, interactive blurring that the worker could reveal reduced emotional impact while keeping accuracy and speed (Das et al., 2020).
- Support. Counselling paid for by the employer, peer support, and a penalty-free opt-out that does not reduce access to benign work. Steiger et al. also recommend disclosing risks before a worker accepts the job and continuing care after employment ends.
Lab publications show the basic version of these practices. Bai et al. (2022) warned crowdworkers that they might see upsetting content and often invited them to stop red-teaming and switch to the helpfulness task. Ouyang et al. (2022) told labelers to skip items where they lacked the required expertise or where the task was very unclear.
Labour and ethics extend beyond content. Reported problems in the data-work supply chain include very low and delayed pay: a 2023 report described workers on Scale AI's Remotasks platform in the Philippines, at least 10,000 by former employees' account, facing low rates and payments that were routinely delayed or withheld, with little recourse (Tan and Cabato, Washington Post, 2023). Employment status is contested: a California class action alleging that Scale AI misclassified its contributors as independent contractors reached a $12.5 million settlement that the San Francisco Superior Court preliminarily approved, with the defendants denying the claims; the final approval hearing was set for 30 October 2026, and its outcome had not been confirmed at the time of writing (McKinney v. Scale AI, settlement administrator). Workers have organised: the Data Labelers Association in Kenya reported 339 members in its first week and asks for fair pay, mental-health support, legal help and collective agreements with intermediary firms (Computer Weekly, 2025); a 2026 survey of 57 of its members found six in ten describing the job as mentally exhausting and only about one in five women and one in four men saying their earnings covered living expenses (Tijdens and Bhattacharya, WageIndicator, 2026). For research use, Shmueli et al. (2021) argue that crowdworkers doing labelling and data production can be exposed to harm that human-subjects rules did not anticipate, and recommend assessing it with the Belmont principles.
Societal impact follows from the same facts. The workers who shape model behaviour are often far from the users and the profits; their preferences, and the guidelines they are trained on, become the model's notion of a good answer, which is why InstructGPT's authors studied how their labelers were selected and how far labeler preferences generalise. Regulation is arriving: the EU Platform Work Directive 2024/2831 creates a presumption of employment where platforms direct work, bans automated processing of workers' emotional or psychological state, requires human review of automated decisions that affect workers, and must be transposed by 2 December 2026 (CMS legal update). Expert data also has a displacement dimension: professionals are paid to produce the judgments that may later substitute for parts of their own work.
The decision a builder faces is whether welfare controls are enforced in the platform or delegated to vendors. The recommended default is both: the platform enforces opt-in, exposure caps, default blurring and pay floors in code for every assignment, and vendor contracts require counselling, disclosure, after-care and the right to audit. Deviate only upward.
Exposure is a quantity the platform can budget, like hours or dollars. The model needs a severity scale, a way to weight time by severity, caps, and an estimate of what the caps cost in capacity.
Severity-weighted exposure. Give each item a severity level \(\sigma \in \{0,1,2,3\}\) from an automated classifier, confirmed by sampled human review, and a weight \(w_\sigma\) (here 0, 0.25, 1 and 3). A worker's exposure over a period is \(E = \sum_j w_{\sigma_j} t_j\), summed over the items \(j\) they handled with \(t_j\) minutes each. The policy sets a daily cap \(E_d\), a weekly cap \(E_w\), and a continuous block \(E_b\) after which a break is forced. The weights and caps are organisational choices, not clinical thresholds; the literature reviewed by Steiger et al. recommends limits and alternation but does not supply validated numeric caps.
Who receives the client's money. A useful ratio for vendor review is the worker share \(\rho = \text{worker pay per hour} / \text{client price per hour}\). In the reported Sama contract, \(\rho\) was between \(1.32/12.50 \approx 0.11\) and \(2/12.50 = 0.16\). A vendor's overhead (management, QA, facilities, benefits, margin) is legitimate, so \(\rho\) is never 1, but a low \(\rho\) combined with pay below the local living wage is a red flag that the platform can detect only if contracts require pay disclosure. The Partnership on AI has published a vendor engagement transparency template for this kind of disclosure.
Measuring wellbeing. Anonymous pulse surveys estimate the share \(\hat\pi\) of workers reporting distress. With \(n\) responses, the standard error is about \(\sqrt{\hat\pi(1-\hat\pi)/n}\). With 150 W1 raters and a 60% response rate, \(n = 90\); at \(\hat\pi = 0.2\), the standard error is about 0.042, so only a change of roughly 12 percentage points between two surveys is clearly distinguishable from noise. Small pools therefore need validated instruments, more frequent short surveys, and behavioural signals such as skip and opt-out rates, rather than a single annual survey. Steiger et al. list instruments such as the General Health Questionnaire, Perceived Stress Scale and Oldenburg Burnout Inventory, alongside absenteeism and turnover.
| Control | Protects against | Cost | Default |
|---|---|---|---|
| Opt-in for severity ≥ 2 | unconsented exposure | smaller eligible pool | on |
| Severity-weighted caps and breaks | cumulative exposure | capacity on sensitive slices | on; caps visible in plan |
| Default blur, greyscale, mute for severity 3 | acute impact | a click per reveal | on |
| Paid counselling and after-care | lasting harm | per-worker cost | contract requirement |
| Pay disclosure and audit rights | wage exploitation | negotiation effort | contract requirement |
The decision here is where to set caps and how to show their cost. The recommended default is conservative caps enforced by the router, with the planner reporting the sensitive slice's critical path so that researchers trade schedule, not worker exposure. Deviate by raising caps only with the workers' informed agreement and clinical advice, never to meet a deadline.
The exposure budget is a check the router calls before it leases an item to a worker, plus bookkeeping after completion. It must be cheap (it runs on every assignment) and it must fail closed: if the severity of an item is unknown, treat it as the highest level. The module below implements opt-in, severity-weighted daily and weekly caps, forced breaks, render flags for the interface and a penalty-free opt-out.
"""Exposure budgeting for harmful content: severity-weighted daily and weekly caps,
forced breaks, penalty-free opt-out, and default blur for severe items.
Caps are an organisational policy choice (illustrative values), not clinical thresholds."""
from dataclasses import dataclass, field
SEVERITY_WEIGHT = {0: 0.0, 1: 0.25, 2: 1.0, 3: 3.0} # 0 benign .. 3 graphic/violent/sexual
@dataclass(frozen=True)
class Policy:
daily_units: float = 20.0 # severity-weighted minutes per day
weekly_units: float = 75.0
break_after_units: float = 10.0 # continuous units before a forced break
break_min: int = 10
blur_from_severity: int = 3 # severe items render blurred, click to reveal
@dataclass
class Worker:
worker_id: str
opted_in_sensitive: bool # explicit, informed, revocable
day_units: float = 0.0
week_units: float = 0.0
since_break: float = 0.0
log: list = field(default_factory=list)
def cost(severity: int, minutes: float) -> float:
return SEVERITY_WEIGHT[severity] * minutes
def can_assign(w: Worker, severity: int, est_min: float, p: Policy) -> tuple:
"""Return (ok, reason). Called by the router BEFORE an item is leased."""
if severity >= 2 and not w.opted_in_sensitive:
return False, "not_opted_in"
c = cost(severity, est_min)
if w.since_break + c > p.break_after_units and severity >= 2:
return False, "break_due"
if w.day_units + c > p.daily_units:
return False, "daily_cap"
if w.week_units + c > p.weekly_units:
return False, "weekly_cap"
return True, "ok"
def render_flags(severity: int, p: Policy) -> dict:
return {"blur": severity >= p.blur_from_severity, "grayscale": severity >= 2,
"audio_muted": severity >= 2, "content_warning": severity >= 1}
def complete(w: Worker, severity: int, minutes: float) -> None:
c = cost(severity, minutes)
w.day_units += c; w.week_units += c; w.since_break += c
w.log.append((severity, minutes))
def take_break(w: Worker) -> None:
w.since_break = 0.0
def opt_out(w: Worker) -> None:
"""Penalty-free: no effect on quality score, pay rate, or benign-work eligibility."""
w.opted_in_sensitive = False
if __name__ == "__main__":
p = Policy()
w = Worker("w1_r017", opted_in_sensitive=True)
# four severity-2 items of 2.5 min fill the 10-unit block; the fifth needs a break
for _ in range(4):
assert can_assign(w, 2, 2.5, p)[0]; complete(w, 2, 2.5)
assert can_assign(w, 2, 2.5, p) == (False, "break_due")
assert can_assign(w, 0, 4.5, p)[0] # benign coding items still flow
take_break(w)
for _ in range(4):
complete(w, 2, 2.5)
take_break(w)
assert w.day_units == 20.0 and can_assign(w, 1, 4.0, p) == (False, "daily_cap")
assert render_flags(3, p)["blur"] and not render_flags(2, p)["blur"]
v = Worker("w1_r044", opted_in_sensitive=True); opt_out(v)
assert can_assign(v, 2, 2.5, p) == (False, "not_opted_in") and can_assign(v, 0, 4.5, p)[0]
print("exposure ok")
Running python3 exposure.py prints exposure ok. The test shows a worker reaching the break threshold after four severity-2 items of 2.5 minutes, benign W1 coding items still flowing during the break, the daily cap stopping all further sensitive and borderline work, severe items rendering blurred, and an opted-out worker keeping access to benign work. The supplier side of welfare is a checklist that procurement and the platform both read; keeping it as data lets the platform refuse to route a sensitive campaign to a vendor whose record is incomplete:
{
"vendor": "vendorA",
"reviewed": "2026-10-01",
"pay": {"disclosed_worker_rate": true, "meets_local_living_wage": true,
"paid_activities": ["training", "exam", "tasks", "breaks"], "payment_terms_days": 14},
"content": {"advance_disclosure": true, "opt_out_without_penalty": true,
"csam_excluded": true, "exposure_caps_enforced": "platform"},
"support": {"counselling": "employer_paid", "after_care_months": 6, "peer_support": true},
"voice": {"grievance_channel": true, "anonymous_survey": "monthly", "retaliation_policy": true},
"eligible_for_sensitivity_max": 3
}
Debugging tips. If workers hit caps far sooner than planned, check whether severity labels drifted upward after a classifier update; compare the severity distribution of the current week with the pilot. If no worker ever hits a cap on a red-team campaign, check that completion events reach the budget at all. Never expose individual exposure totals to managers' performance views; they belong to the router and to aggregated welfare reporting.
Welfare in production means running the controls as service levels, watching leading indicators, and having a runbook for the day content goes wrong. The targets below are illustrative defaults; several are zero-tolerance.
| Indicator | Definition | Target |
|---|---|---|
| Cap compliance | assignments leased that exceed a worker's daily or weekly cap | 0 |
| Consent compliance | severity ≥ 2 items shown to non-opted-in workers | 0 |
| Opt-out latency | assignments a worker receives after opting out that need opt-in | 0 |
| Unclassified severity | items reaching a worker with severity unknown, not defaulted to max | 0 |
| Grievance response | first response to a worker complaint | ≤ 2 business days |
| Support access | share of sensitive-campaign workers with active counselling access | 100% |
Scenario assumptions beyond the example sheet: W2 transcripts are classified for severity only on the agent's messages, not on the raw tool outputs embedded in the transcript.
Symptom: on one day, the W2 skip rate rises from a typical 1% to 9% for a batch of 300 transcripts, and two experts use the grievance form to report graphic images inside browser screenshots.
Measurements: sampling the batch shows that 30 transcripts (1.5% of the 2,000) include browser screenshots of violent imagery from a web-research task; none were flagged because the classifier never saw tool outputs; 11 experts who had not opted in to sensitive work opened at least one of them.
Remedy, in order: pause the batch; route remaining flagged transcripts only to opted-in experts with blur on; extend the classifier to tool outputs and default unknown-severity outputs to the maximum level; contact the 11 experts directly, offer paid counselling and paid time off for the rest of the day, and confirm their benign work is unaffected; pay for all time spent on the batch including skipped items; add the 30 transcripts' tool outputs to the filter test set. Cost: about 30 transcripts × 35 minutes re-routed (17.5 expert-hours, $2,100) plus counselling and lost capacity, small against the campaign's $140,000.
Validation: the skip rate returns to about 1%, consent compliance returns to zero violations over the next 2,000 assignments, and the next pulse survey's distress items for those 11 experts do not rise; if skips stay high on transcripts without flagged outputs, the classifier is still missing a content type.
Runbook for a harmful-content incident:
- Stop exposure first: pause the affected batch or campaign; do not wait for root cause.
- Identify affected workers from assignment logs; contact them, offer support and paid time off; keep their pay whole.
- If illegal content is suspected, follow the legal and reporting procedure of the jurisdiction with counsel and the trust-and-safety team; restrict access and preserve evidence as instructed; do not ask workers to examine it further.
- Fix the classification gap; make unknown severity fail closed; add regression cases.
- Report the incident to the researcher, the vendor and the welfare review with numbers: items, workers, exposure units.
- Review the vendor's support delivery within a week; it is part of the incident, not a follow-up.
The same discipline extends to labour practice. A quarterly vendor review should compare disclosed worker pay against the local living wage, check payment timeliness, review grievances and their outcomes, and confirm the opt-out and counselling terms are used, not merely written. The trade-off is cost and some loss of speed; the alternative, documented in the reports above, is harm to workers, legal exposure, and data produced under conditions that undermine its quality. These controls connect back to the rest of the platform: qualification decides who may see sensitive work, vendor contracts carry the obligations, pay floors make opt-out affordable, and the router enforces all of them on every assignment.
Operating the Platform
The earlier chapters describe the parts of an RL data platform one at a time: how a research need becomes a campaign, how samples are generated from live models and routed to people, what the feedback interfaces look like, how quality is measured, and how accepted feedback becomes training data. This chapter is about running all of those parts together as one production system, every day, for many campaigns at once. Running a platform means owning five things that no single feature owns: the service architecture that connects the parts, the reliability of the path that fetches samples from live model endpoints, the inspection tools that let researchers answer their own questions, the governance rules that decide who may see which data and for how long, and the cost accounting that turns a campaign into a price per useful label.
An RL data platform has an unusual operating profile. Its request volume is small by web standards: in the W1 reference workload (20,000 pairwise coding comparisons from 150 vendor raters) the whole rater pool submits about one label every two seconds at peak. Yet each request is expensive and hard to replace, because behind it sits several minutes of paid, trained human attention. When the platform stalls, it does not lose cheap clicks; it pays people to wait. When it silently corrupts a label, the corruption may reach a reward model and shape a frontier model's behaviour. The operating discipline in this chapter follows from that asymmetry: the platform is optimised for correctness, low latency to the person in front of the task, and traceability, not for raw throughput.
The chapter has five sections. Service architecture draws the full platform and names the contract on every edge, including the two contracts with systems the platform does not own: model serving and training. Reliability explains how the platform keeps raters supplied with samples when the endpoints it depends on are rate-limited, slow or down. Dashboards and inspection describes the panels and drill-down tools that let a researcher check a campaign without filing a ticket. Governance covers security, privacy, access and retention. Cost accounting builds unit economics for the three reference workloads. The mental model to carry through: the platform is a factory whose most expensive machine is a person's time, so every operating decision is judged by how much paid human attention it protects or wastes.
Operating decisions in this chapter are made with a small set of quantities. The table lists them with their values for the reference workloads; each is derived in the section named in the last column. All W1, W2 and W3 figures are illustrative workload numbers defined in the front matter, not published measurements; numbers attributed to vendors or papers are cited where they appear.
| Quantity | Symbol | Reference value (illustrative) | Why it matters | Section |
|---|---|---|---|---|
| Peak label rate | \(\lambda_\ell\) | W1: 150 raters / 4.5 min = 33.3 labels/min ≈ 0.56/s | Sizes every service; shows the platform is not throughput-bound | Architecture |
| Buffer runway | \(T_B = B/\lambda_\ell\) | W1: 2,000 pairs / 33.3 per min = 60 min | How long an endpoint outage can last before raters starve | Reliability |
| Generation concurrency | \(L = \lambda_g W_g\) | W1: 1.11 responses/s × 14 s ≈ 16 in flight (assumed 50 tok/s) | Endpoint capacity and rate-limit headroom | Reliability |
| Gold items per rater | \(n_g\) | W1: 168 assignments × 5% ≈ 8.4 | Too few to judge one rater; sets dashboard design | Observe |
| Human exposures of sensitive data | \(E\) | W2: 2,000 transcripts × 1.1 reviews = 2,200 | Size of the blast radius when a transcript leaks a secret | Governance |
| Cost per useful unit | \(C_u\) | W1 $4.12 per comparison · W2 $77 per transcript · W3 $66 per prompt (W3 rate assumed) | The number a researcher budgets with | Cost |
Table. The operating quantities of the chapter. W-values are illustrative reference-workload figures.
One relationship ties the table together. Model generation for W1 costs a few hundred dollars, labour costs about $75,780, and a single 45-minute stall with 150 raters idle costs $4,500. The cost of unreliability is therefore measured in idle paid human time, not in compute, and the design choices below (pre-generated buffers, brownout queues, idempotent submits, early quality flags) are all ways of converting a small amount of engineering and compute into a large saving of human time. The decision a platform builder faces at chapter level is where to set the reliability bar; the recommended default is to set service-level objectives on the human-facing path (time to first sample, submit durability) and to accept looser objectives on everything behind the buffer.
This chapter's build artefacts form one small Python package, rdp, plus configuration files. Everything is standard library except PyYAML for the config files, and every test below was run as printed (24 tests, all passing). The package is a teaching model: each service is a class in one process so the flow is testable, but each class talks to the others only through the typed contracts, so the same boundaries can later become network calls.
rdp/
contracts.py # r-ops-arch: GenerateRequest, Sample, Item, Assignment, Feedback, DatasetManifest
platform.py # r-ops-arch: Sampler, AssignmentService, FeedbackStore, QualityService, Pipeline, DatasetRegistry
services.yaml # r-ops-arch: service catalog, owners, tiers, edges and their contracts
reliability.py # r-ops-rel: TokenBucket, AdaptiveThrottle, Breaker, backoff, BufferController
endpoints.yaml # r-ops-rel: per-model client limits, retry layer, fallbacks, brownout
alerts.yaml # r-ops-rel / r-ops-observe: Prometheus-style SLO burn and runway alerts
panels.sql # r-ops-observe: named panel queries
observe.py # r-ops-observe: panel runner, quantiles, Wilson intervals
policy.yaml # r-ops-gov: data classes, retention, ABAC rules
gov.py # r-ops-gov: decide(), pseudonym(), expired(), propagate_delete()
cost.py # r-ops-cost: unit economics for W1, W2, W3
test_contracts.py test_catalog.py test_reliability.py test_observe.py test_gov.py test_cost.py
$ python3 -m pytest -q
........................ [100%]
24 passed
Two conventions run through the code. First, every message that crosses a service boundary carries a schema version (rdp.v3) and, where it can be retried, an idempotency key, so that a retry can never create a duplicate label or a duplicate charge. Second, every test asserts a reference-workload number (60 minutes of buffer runway, $75,780 of W1 labour, 600 overlap pairs), so a change that breaks the arithmetic of the book breaks the build. Debugging tip: when a test about the flow fails, print the DatasetManifest; its row count and hash localise most errors to either the quality filter or the sampler.
In production the platform is judged by a short list of service-level objectives (SLOs), each a target on a service-level indicator (SLI). Following the Google SRE workbook, an SLI is best expressed as good events divided by total events, and the error budget is one minus the SLO; a written error-budget policy says what the team stops doing when the budget is spent (Google SRE, "Implementing SLOs"). The platform-level SLOs below are the defaults this chapter recommends; each section refines its own.
| SLI (good / total) | SLO, 28-day window | Why this level | Owner |
|---|---|---|---|
| First samples served ≤ 5 s / all first-sample requests | 95% (and p50 ≤ 2 s) | W1 time-to-first-sample target; a rater waiting is paid idle time | Platform |
| Submits durably acknowledged / submits attempted | 99.95% | A lost label is several minutes of paid work that cannot be regenerated | Platform + data |
| Accepted labels lost after acknowledgement | 0 (page on any) | Durability is not budgeted; any loss is an incident | Data |
| Transcript renders ≤ 1.5 s / transcript opens | 95% | W2 interface target for 25,000-token transcripts | UI |
| Dashboard panels with data ≤ 15 min old / panel loads | 99% | Researchers act on fresh data; older is labelled stale | Platform |
| Exports reproducible from manifest / exports | 100% (release gate) | Training must be able to rebuild any pinned dataset version | Data |
Table. Platform SLOs. Targets are recommended defaults for the reference workloads, not published industry figures.
Each section's Operate block works one incident or scaling scenario in full: an assignment lease storm at shift start, a degraded candidate-checkpoint endpoint that drains the W1 buffer, an agreement drop traced with the inspection tools, credentials found in W2 transcripts, and a W1 cost overrun caught by an estimate-at-completion panel. The common thread is that each incident is detected on the human-facing path, diagnosed with a metric that separates its candidate causes, and fixed in a way whose effect is checked on that same metric. The incident runbooks are collected in the runbook playbook.
Service architecture
A service architecture is the map of the separately running programs that make up a system, what each one owns, and the agreements (contracts) on the messages that pass between them. For an RL data platform it answers a practical question: when a rater clicks "next", which programs are involved, which one is allowed to say no, and where does the label end up?
Why it exists. Early human-feedback projects were run with a general annotation tool, a spreadsheet of prompts, and scripts. A researcher generated responses offline, uploaded them as a batch, waited for the vendor to finish, downloaded a file and converted it for training. That works for one dataset. It breaks when many campaigns run at once, when samples must come from a model checkpoint that changed yesterday, when a quality problem must stop a rater within minutes rather than at the end, and when a training run six months later must know exactly which labels it used. Each of those needs is a responsibility, and the architecture gives each responsibility one owner.
The parts, in the order a label travels.
- Researcher console (a frontend). Receives a campaign definition from a researcher (task, rubric, population, overlap, gold rate, budget, stopping rule; see the campaign spec). Produces a validated spec and later shows progress and lets the researcher inspect items and export.
- API gateway. The single door for every frontend. It checks who is calling (authentication) and what they may do (authorisation), enforces per-user quotas, and makes submits idempotent: a submit carries a key, and a repeated key returns the first result instead of writing twice. It does no business logic.
- Campaign service. Owns the campaign's state machine: draft, validated, piloting, running, paused, complete. When a campaign starts it emits an event that tells the sampler to begin.
- Sampler. Receives prompts and the campaign's model references (for W1, the current checkpoint and the candidate). Calls model serving with a generation request and receives samples. Packs samples into items, the unit of human work (a pair for W1, a transcript for W2, a prompt plus four responses for W3), and writes them to the item store.
- Item store. Holds ready items, including the pre-generated buffer, so that a rater never waits for a model to generate.
- Assignment service. Receives "next item for this rater" and returns a lease: the right to work on one item for a fixed time, after which the item returns to the pool. It mixes in gold items (items with a known answer), schedules overlap (the same item to several raters), and never gives a rater the same item twice.
- Rater and expert UIs. Show the item and record the feedback and interaction timings (see interface design).
- Feedback store. An append-only record of every submitted label. Nothing is updated in place; corrections are new rows. It is the platform's source of truth.
- Quality service. Reads labels as they arrive, scores gold items, measures agreement and effort, writes verdicts (accept, reject, needs review), and can ask the assignment service to pause a rater.
- Pipeline. Reads accepted labels, converts them to training examples (preference pairs, corrections, rubric scores; see transformation), validates them, and writes a dataset version.
- Dataset registry. Stores immutable dataset versions, each described by a manifest: id, version, row count, content hash, source campaigns and the quality filter that admitted the rows.
- Warehouse and dashboards. A read-only copy of events, labels, verdicts and costs, queried by the dashboards and the item inspector, so that analysis never slows the live path.
The two external contracts. The platform depends on two systems it does not run. With model serving the contract is a generation request (which pinned checkpoint, which sampling settings, a deadline after which the answer is useless, a priority, an idempotency key) and a sample (text, token counts, the checkpoint that actually answered). With training the contract is the dataset manifest: training pins an exact (dataset, version, hash) triple and must be able to rebuild it. Keeping these contracts narrow is what lets the inference team change its fleet and the training team change its trainer without coordinating a release with the data platform.
w1_coding_pref from the console: 10,000 coding prompts, two models (current checkpoint and candidate), 10% overlap at three raters, 5% gold. The campaign service validates the spec and emits "launched". The sampler requests 2,000 pairs from model serving and fills the item store. At 09:00 the 150 vendor raters open the UI; each "next" goes API → assignment → item store and returns a leased pair in well under two seconds because the pair was generated earlier. A submitted label goes API → feedback store; the quality service scores it within seconds; after six collection days the pipeline exports the accepted rows as dataset version 1 with a manifest, and the reward-model training job pins that version.Compare and contrast. A general annotation tool such as Label Studio covers the UI, task storage, export and webhooks (HumanSignal, Label Studio integrations guide). An RL data platform adds three things a general tool lacks: a sampler that talks to live, frequently changing model endpoints; an assignment service that enforces overlap, gold and population rules while people work; and a registry whose manifests training can pin. The price is more moving parts to operate, which is why the rest of this chapter exists.
What you would actually do. Start with the boundaries in the figure even if all services run in one deployable program at first (a "modular monolith"). Keep the two external contracts and the append-only feedback store from day one, because those are the expensive things to change later. Split a module into its own service only when it needs a different scaling or failure profile; the sampler, which waits on slow endpoints, is usually the first to split. The next section takes the most fragile edge, sampler to model serving, and makes it reliable.
The architecture of an RL data platform is decided less by load than by three other forces: the latency budget on the human-facing path, the reliability of dependencies the platform does not control, and the need to reproduce any dataset exactly. A back-of-envelope sizing makes the first point concrete.
Load. Let \(N_r\) be the number of raters working concurrently and \(\bar t\) the mean time per label. The peak label rate is \(\lambda_\ell = N_r/\bar t\). Each label produces a handful of events (item served, item rendered, interactions, submit, verdict); call that number \(e\). The event rate is \(e\lambda_\ell\).
Availability composes. If a request must pass through \(k\) services in series, each available with probability \(a_i\), the path's availability is \(\prod_i a_i\). The "next item" path crosses the API, the assignment service and the item store; if each is 99.95% available, the path is \(0.9995^3 \approx 99.85\%\), about 60 minutes of unavailability in a 28-day window. Every service added to the synchronous path costs availability, which is why generation is kept off this path: if the sampler and model serving (each, say, 99% available) were in series with every "next", the path would fall to about 97.9%, more than 14 hours a month.
Durability and idempotency. A rater's submit can be retried by the browser, the API client or a load balancer. If each of these three layers retries once on timeout, the retries multiply and the same label can arrive up to \(2^3 = 8\) times. Without an idempotency key, the feedback store would hold four labels and the overlap statistics would be wrong. With a key \(k = \text{hash}(\text{assignment\_id})\), the store accepts the first write and returns the stored result for the rest, so the number of stored rows per submit is exactly one regardless of retries.
Design decisions.
| Decision | Options | Numbers that decide it | Default |
|---|---|---|---|
| Deployables | Modular monolith · microservices | Peak 0.56 labels/s and ~6 events/s do not need independent scaling; the sampler's minutes-long waits on endpoints do | Monolith for API, campaign, assignment, quality; separate sampler workers |
| Work queue for leases | Database rows with SKIP LOCKED · message broker | Hundreds of leases per minute; leases need expiry, overlap rules and per-rater exclusion, which are queries, not FIFO pops | Database rows; PostgreSQL has supported SKIP LOCKED since 9.5 (Paquier 2014) |
| Campaign lifecycle | Cron plus state column · durable workflow engine | Campaigns live days to weeks, pause and resume, and call slow external systems | Durable workflow engine (Temporal-style) once more than a handful of campaigns run; its default activity retry is 1 s initial interval, coefficient 2, 100 s cap (Temporal docs) |
| Feedback storage | Mutable rows · append-only log | Audits and reproducibility need history; label volume is small | Append-only table plus object storage for large payloads |
| Dataset storage | Files in buckets · table format with snapshots | Training must pin an exact version; deletion must be able to rebuild versions | Immutable manifests over files, or a table format such as Apache Iceberg whose snapshots record table state at a point in time (Iceberg spec) |
| Analytics | Query the primary · replica/warehouse | One heavy self-serve query can hold locks or saturate I/O on the primary | Read replica or warehouse, with a freshness SLO |
Table. Architecture decisions and the numbers behind them. W1 rates are illustrative.
What you would actually do. Keep the synchronous human path to three hops, put generation behind a buffer, make every submit idempotent, and store feedback append-only. Deviate toward more services when teams, not load, force it: a separate quality team that ships daily is a good reason to give quality its own deployable. The binding constraint on this architecture is the edge to model serving, which the next section treats quantitatively.
The build artefact for this section is the set of typed contracts every service speaks, a one-process model of the service graph that exercises the whole flow, and a service catalog with a test that keeps the dependency graph honest. Prerequisites in brief: an item is one unit of human work; a lease is a time-limited claim on an item; a manifest is the immutable description of a dataset version that training pins.
Contracts. Frozen dataclasses make messages immutable; the schema string lets a consumer reject a message it does not understand rather than misread it.
"""Service contracts for the RL data platform (r-ops-arch).
Every message that crosses a service boundary is a frozen dataclass with a schema version.
Stdlib only: python3 -m pytest test_contracts.py"""
from __future__ import annotations
from dataclasses import dataclass, field, asdict
import hashlib, json, time, uuid
SCHEMA = "rdp.v3"
def _id(prefix: str) -> str:
return f"{prefix}_{uuid.uuid4().hex[:12]}"
# ---- contract with model serving (platform -> serving) -------------------
@dataclass(frozen=True)
class GenerateRequest:
campaign_id: str
prompt_id: str
model_ref: str # pinned checkpoint, e.g. "ckpt:cand-2026-11-03"
sampling: dict # temperature, max_tokens, seed
deadline_ms: int # absolute epoch ms; serving drops work past it
priority: str = "SHEDDABLE_PLUS" # pre-generation is sheddable; live sessions are CRITICAL
idempotency_key: str = "" # same key -> same cached sample, never a double charge
@dataclass(frozen=True)
class Sample:
sample_id: str
prompt_id: str
model_ref: str
text: str
input_tokens: int
output_tokens: int
generated_at: float
# ---- internal platform messages ----------------------------------------
@dataclass(frozen=True)
class Item: # one unit of human work: a pair for W1, a transcript for W2
item_id: str
campaign_id: str
sample_ids: tuple
is_gold: bool = False
gold_answer: str | None = None
@dataclass(frozen=True)
class Assignment:
assignment_id: str
item_id: str
rater_pseudo_id: str # never the vendor's real worker id (see r-ops-gov)
leased_at: float
lease_s: int = 900 # lease expires -> item returns to the pool
@dataclass(frozen=True)
class Feedback:
feedback_id: str
assignment_id: str
item_id: str
campaign_id: str
rater_pseudo_id: str
payload: dict # typed by campaign.feedback_type, e.g. {"choice":"A","tie":False}
active_ms: int # focused time on task, from the frontend
submitted_at: float
schema: str = SCHEMA
# ---- contract with training (platform -> training) ----------------------
@dataclass(frozen=True)
class DatasetManifest:
dataset_id: str
version: int
feedback_type: str # "pairwise_pref" | "transcript_critique" | "rubric_score"
row_count: int
content_sha256: str # hash of the canonical rows -> reproducible
source_campaigns: tuple
quality_filter: str # name+version of the filter that admitted rows
retention_class: str # governs deletion (r-ops-gov)
schema: str = SCHEMA
def canonical_hash(rows: list[dict]) -> str:
h = hashlib.sha256()
for r in sorted(rows, key=lambda r: r["feedback_id"]):
h.update(json.dumps(r, sort_keys=True, separators=(",", ":")).encode())
return h.hexdigest()
def to_json(obj) -> str:
return json.dumps(asdict(obj), sort_keys=True)
The service graph. Each class owns one responsibility from the figure. The assignment service mixes gold at 5% and sends 10% of fresh items to two further raters, which reproduces W1's overlap; it returns None when the buffer is empty, which is exactly the event that becomes a time-to-first-sample miss in production.
"""A single-process model of the platform's service graph (r-ops-arch).
Each class is one service; they talk only through the contracts in contracts.py.
In production each is a separate deployment; here they share a process so the flow is testable."""
from __future__ import annotations
import time, random
from collections import deque
from .contracts import (GenerateRequest, Sample, Item, Assignment, Feedback,
DatasetManifest, canonical_hash, _id)
class FakeServing: # stands in for the model-serving fleet
def generate(self, req: GenerateRequest) -> Sample:
return Sample(_id("smp"), req.prompt_id, req.model_ref,
f"<response of {req.model_ref} to {req.prompt_id}>", 800, 700, time.time())
class Sampler: # prompts -> samples -> items, into a bounded buffer
def __init__(self, serving, campaign, buffer_cap):
self.serving, self.c, self.cap = serving, campaign, buffer_cap
self.buffer: deque[Item] = deque()
def refill(self, prompts):
while len(self.buffer) < self.cap and prompts:
p = prompts.pop()
reqs = [GenerateRequest(self.c["id"], p, m, {"temperature": 0.8, "max_tokens": 1024},
int(time.time()*1000) + 60_000, idempotency_key=f"{p}:{m}")
for m in self.c["models"]]
smp = tuple(self.serving.generate(r).sample_id for r in reqs)
self.buffer.append(Item(_id("itm"), self.c["id"], smp))
class AssignmentService: # items -> leased assignments; overlap and gold mixing
def __init__(self, sampler, gold_items, gold_rate, overlap_rate, overlap_k, seed=0):
self.s, self.gold, self.gr = sampler, gold_items, gold_rate
self.orate, self.k = overlap_rate, overlap_k
self.rng = random.Random(seed)
self.pending_repeats: deque[Item] = deque()
self.seen: dict[str, set] = {}
def next_for(self, rater):
if self.rng.random() < self.gr:
item = self.rng.choice(self.gold)
elif self.pending_repeats and rater not in self.seen.get(self.pending_repeats[0].item_id, set()):
item = self.pending_repeats.popleft()
else:
if not self.s.buffer:
return None # starvation: surfaced as a TTFS miss
item = self.s.buffer.popleft()
if self.rng.random() < self.orate:
self.pending_repeats.extend([item] * (self.k - 1))
self.seen.setdefault(item.item_id, set()).add(rater)
return Assignment(_id("asg"), item.item_id, rater, time.time())
class FeedbackStore: # append-only; the source of truth for human labels
def __init__(self): self.rows: list[Feedback] = []
def append(self, fb: Feedback): self.rows.append(fb)
class QualityService: # gold checks + low-effort flags -> per-row verdict
def __init__(self, gold_answers, min_active_ms=40_000):
self.gold, self.min_ms = gold_answers, min_active_ms
def verdict(self, fb: Feedback) -> str:
if fb.active_ms < self.min_ms: return "reject:low_effort"
if fb.item_id in self.gold and fb.payload.get("choice") != self.gold[fb.item_id]:
return "gold_miss"
return "accept"
class Pipeline: # accepted feedback -> versioned dataset
def __init__(self, registry): self.reg = registry
def export(self, store, quality, campaign_id, ftype):
rows = [dict(feedback_id=f.feedback_id, item_id=f.item_id, **f.payload)
for f in store.rows if f.campaign_id == campaign_id
and quality.verdict(f) == "accept" and f.item_id not in quality.gold]
return self.reg.register(rows, ftype, (campaign_id,), "qf-gold80-mintime40s@2")
class DatasetRegistry: # immutable versions; training pins (id, version, hash)
def __init__(self): self.versions: dict[str, list[DatasetManifest]] = {}
def register(self, rows, ftype, campaigns, qfilter):
ds = f"ds_{campaigns[0]}"
v = len(self.versions.get(ds, [])) + 1
m = DatasetManifest(ds, v, ftype, len(rows), canonical_hash(rows), campaigns, qfilter, "rc-standard")
self.versions.setdefault(ds, []).append(m)
return m, rows
Flow test on a W1 slice. Two thousand labels from 150 raters with log-normal active time (median about 4 minutes) go through the whole graph. The tests check that the export is a versioned, hashed dataset smaller than the raw label set (gold and low-effort labels removed), that the gold share is near 5%, that the content hash does not depend on row order, and that overlap never sends an item to the same rater twice.
import random
from rdp.contracts import Feedback, _id, canonical_hash
from rdp.platform import (FakeServing, Sampler, AssignmentService, FeedbackStore,
QualityService, Pipeline, DatasetRegistry)
W1 = {"id": "w1_coding_pref", "models": ["ckpt:current", "ckpt:candidate"]}
def run_w1_slice(n_labels=2000, seed=7):
rng = random.Random(seed)
sampler = Sampler(FakeServing(), W1, buffer_cap=2000) # W1: 2,000-pair pre-generated buffer
sampler.refill([f"p{i}" for i in range(3000)])
gold = {f"gold{i}": "A" for i in range(50)}
from rdp.contracts import Item
gold_items = [Item(g, W1["id"], (), True, "A") for g in gold]
asg = AssignmentService(sampler, gold_items, gold_rate=0.05, overlap_rate=0.10, overlap_k=3, seed=seed)
store, q = FeedbackStore(), QualityService(gold)
raters = [f"r{i:03d}" for i in range(150)] # W1: 150 raters
for _ in range(n_labels):
a = asg.next_for(rng.choice(raters))
if a is None: break
store.append(Feedback(_id("fb"), a.assignment_id, a.item_id, W1["id"], a.rater_pseudo_id,
{"choice": rng.choice("AB"), "tie": False},
active_ms=int(rng.lognormvariate(12.4, 0.5)), submitted_at=0.0))
return store, q, Pipeline(DatasetRegistry()).export(store, q, W1["id"], "pairwise_pref")
def test_flow_produces_versioned_dataset():
store, q, (manifest, rows) = run_w1_slice()
assert manifest.version == 1 and manifest.row_count == len(rows)
assert 0 < manifest.row_count < len(store.rows) # gold and rejects are filtered out
assert manifest.content_sha256 == canonical_hash(rows)
def test_gold_share_near_5_percent():
store, q, _ = run_w1_slice()
share = sum(f.item_id in q.gold for f in store.rows) / len(store.rows)
assert 0.03 < share < 0.07
def test_hash_is_order_independent():
rows = [{"feedback_id": "b", "x": 1}, {"feedback_id": "a", "x": 2}]
assert canonical_hash(rows) == canonical_hash(list(reversed(rows)))
def test_overlap_never_repeats_rater():
store, _, _ = run_w1_slice()
pairs = [(f.item_id, f.rater_pseudo_id) for f in store.rows if not f.item_id.startswith("gold")]
assert len(pairs) == len(set(pairs))
Service catalog. The catalog is the machine-readable version of the architecture figure: one entry per deployable, its owning team, its tier, and every outgoing edge with the contract it carries. The tests fail the build if an edge points to an unknown service, if the graph acquires a cycle (a cycle between services usually means a hidden synchronous dependency), or if a critical-tier service starts depending on a standard-tier one such as the warehouse.
# Service catalog (r-ops-arch). One entry per deployable; edges name the contract they carry.
services:
frontend: {owner: ui, tier: critical, calls: {api: "REST rdp.v3"}}
api: {owner: platform, tier: critical, calls: {assignment: "rpc NextItem/Submit", campaign: "rpc GetCampaign", feedback_store: "rpc Append"}}
campaign: {owner: platform, tier: high, calls: {sampler: "event CampaignLaunched"}}
sampler: {owner: platform, tier: high, calls: {model_serving: "GenerateRequest/Sample", item_store: "rpc PutItem"}}
assignment: {owner: platform, tier: critical, calls: {item_store: "rpc Lease"}}
feedback_store: {owner: data, tier: critical, calls: {}}
item_store: {owner: data, tier: critical, calls: {}}
quality: {owner: quality, tier: high, calls: {feedback_store: "stream Feedback", assignment: "rpc PauseRater"}}
pipeline: {owner: data, tier: high, calls: {feedback_store: "batch read", quality: "rpc Verdicts", registry: "DatasetManifest"}}
registry: {owner: data, tier: high, calls: {}}
dashboards: {owner: platform, tier: standard, calls: {warehouse: "SQL read-only"}}
warehouse: {owner: data, tier: standard, calls: {}}
model_serving: {owner: external-inference, tier: external, calls: {}}
training: {owner: external-training, tier: external, calls: {registry: "DatasetManifest (pinned id, version, sha256)"}}
import yaml, pathlib
CAT = yaml.safe_load(pathlib.Path("rdp/services.yaml").read_text())["services"]
def test_every_edge_targets_a_known_service_and_names_a_contract():
for s, spec in CAT.items():
for dst, contract in spec["calls"].items():
assert dst in CAT, (s, dst)
assert contract.strip(), (s, dst)
def test_graph_is_acyclic():
seen, stack = set(), set()
def visit(n):
assert n not in stack, f"cycle through {n}"
if n in seen: return
stack.add(n); [visit(m) for m in CAT[n]["calls"]]; stack.discard(n); seen.add(n)
for n in CAT: visit(n)
def test_critical_path_does_not_depend_on_standard_tier():
rank = {"critical": 0, "high": 1, "standard": 2, "external": 1}
for s, spec in CAT.items():
if spec["tier"] == "critical":
assert all(rank[CAT[d]["tier"]] <= 1 for d in spec["calls"]), s
$ python3 -m pytest -q test_contracts.py test_catalog.py
....... [100%]
7 passed
Debugging tips. If the flow test's dataset is empty, check the quality threshold against the active-time distribution first (a 40-second floor applied to milliseconds versus seconds is a classic unit bug). If the overlap test fails, the assignment service is popping a repeat for a rater who already saw the item; the fix is to skip, not discard, that repeat. If the catalog test reports a cycle, look for a "callback" edge (quality → assignment) that should be an event rather than a synchronous call.
Operating the architecture means giving each service an SLO that matches its position: services on the human path get tight latency objectives; services behind the buffer get throughput and freshness objectives; the feedback store gets a durability objective that is not budgeted at all.
| Service | SLI | SLO (28 d) | Primary dashboard panel |
|---|---|---|---|
| API gateway | Non-5xx responses / requests | 99.95% | Error ratio by route |
| Assignment | NextItem ≤ 300 ms / NextItem calls | 99% | Lease latency p50/p95/p99; lock waits |
| Feedback store | Acknowledged submits later readable / acknowledged | 100% | Append errors; replication lag |
| Quality | Labels with a verdict ≤ 10 min after submit / labels | 99% | Verdict lag |
| Sampler | Buffer runway ≥ 20 min, sampled each minute | 99% | Runway; generation success by model_ref |
| Pipeline + registry | Exports finished ≤ 2 h after request / exports | 95% | Export duration; validation failures |
Table. Per-service SLOs (recommended defaults, illustrative).
Symptom. On the first collection day the vendor's shift starts at 09:00 and 150 raters log in within about two minutes. The time-to-first-sample panel shows p95 of 9.2 s for the first ten minutes, against a 5 s objective, and then recovers. The buffer runway panel shows 60 minutes of ready pairs throughout, so supply is not the problem.
Separating causes. Three candidate causes fit "slow first sample with a full buffer": the API is saturated, the UI is slow to render, or the assignment service is slow to lease. The API error ratio and the frontend render timings are flat. The assignment service's lease-latency panel shows p95 of 8.7 s, and the database lock-wait metric spikes to 140 concurrent waiters. The lease query selected the oldest unleased item FOR UPDATE; with 150 near-simultaneous requests, every transaction tried to lock the same row and queued behind the one that held it.
Remedy, in order. (1) Change the lease query to SELECT … FOR UPDATE SKIP LOCKED LIMIT 1, so each transaction takes the first row nobody else has locked rather than waiting for the head of the queue. (2) Lease a small batch per rater (the current item plus two prefetched items, each with its own 15-minute lease), which turns 150 bursts of one into 150 claims of three that are then served from the client. (3) Spread the shift start: ask the vendor to stagger logins over ten minutes. Step 1 is a one-line change; step 2 adds the risk that prefetched leases expire unused when a rater leaves, so the lease sweeper must return them to the pool.
Cost of the incident. Ten minutes at a mean 9 s extra wait on each of roughly 330 first-sample requests is about 50 rater-minutes, about $33 at $40/h. Small, but it recurs every shift start and on every campaign.
Validation. The next shift start is the test: the fix is supported if lease p95 stays under 300 ms and lock waiters stay under 5 while 150 raters log in; it is weakened if p95 improves but lock waits remain high, which would point at a second hot row (for example the per-rater counter used for gold mixing).
Runbook: a human-path latency SLO burns.
- Open the time-to-first-sample panel split by hop (API, assignment, item fetch, render). Identify the hop whose latency moved.
- If it is the item fetch and buffer runway is below 20 minutes, switch to the reliability runbook in the next section.
- If it is assignment, check lock waits and the slow-query log; look for a hot row, a missing index on
(campaign_id, state, created_at), or a lease sweeper holding long transactions. - If it is render, check the payload size distribution (W2 transcripts are about 25,000 tokens) and whether the UI is fetching the whole transcript before first paint.
- Record the incident with the idle rater-minutes it caused, because that number is what the cost section charges against reliability work.
The architecture's SLOs assume that the sampler keeps the buffer full. The next section deals with what happens when the endpoints behind it do not cooperate.
Reliability, latency and capacity against live model endpoints
The problem. An RL data platform depends on model endpoints it does not run. Those endpoints have rate limits, they slow down under load, and research deployments of a candidate checkpoint are often small and restarted while evaluations run. Meanwhile, the people doing the labelling are paid by the hour and expect the next item in about two seconds. Reliability here means one thing above all: keep raters supplied with valid items while the endpoints behind them misbehave, and never let the platform's own retries make the endpoints' problems worse.
Why generation cannot sit on the rater's path. Generating a 700-token coding answer at an assumed 50 tokens per second takes about 14 seconds, far longer than the two-second target for the first sample. So the platform generates ahead of demand into a pre-generated buffer, and the rater's "next" only reads from it. The buffer converts a latency problem into a capacity problem: as long as the sampler refills faster than raters drain, nobody waits. It also converts an outage into a countdown: when generation stops, the buffer's runway (ready items divided by the rate raters consume them) is how long the platform has before people sit idle.
The protective mechanisms, in the order a request meets them.
- Watermarks and backpressure. The buffer has a high watermark (stop requesting), a low watermark (refill quickly) and a floor (stop serving fresh items and switch mode). Backpressure means the consumer's state controls the producer's rate: a full buffer tells the sampler to stop; a draining buffer tells it to speed up, within limits. Without backpressure the sampler either over-generates stale samples or falls behind.
- Client-side rate limiter. Providers publish limits as requests per minute and tokens per minute. Anthropic's API, for example, limits requests, input tokens and output tokens per minute using a token-bucket algorithm in which capacity is replenished continuously, and returns HTTP 429 with a
retry-afterheader when a limit is exceeded (Anthropic rate-limit docs). A token bucket is a counter that refills at a fixed rate up to a capacity; each request spends from it, and a request that finds it empty waits. Running the same bucket on the client, set a little below the provider's limit, means the platform throttles itself smoothly instead of being throttled abruptly. - Retries with backoff and jitter. A failed call is retried after a wait that grows exponentially, with a random spread ("jitter") so that many clients do not retry in lockstep; jittered backoff "should be considered a standard approach for remote clients" (Brooker 2015). If the server says how long to wait, the client obeys it. Only one layer retries; retries stacked in several layers multiply load exactly when the endpoint is weakest. The SRE book gives the same rule: retry only at the layer immediately above the one that is rejecting (Google SRE book, "Handling Overload").
- Adaptive throttling. When the endpoint starts refusing a large share of requests, the client begins rejecting some locally, before sending them. The Google SRE book's version tracks requests and accepts over two minutes and rejects with growing probability once requests exceed a multiple K of accepts, with K = 2 preferred (Google SRE book, "Handling Overload").
- Circuit breaker and router. A breaker counts consecutive failures per model reference; after a threshold it "opens" and stops sending traffic for a cool-down, then lets one probe through. The router then picks a fallback: another replica or region serving the same checkpoint, or, for pre-generation that can wait, an asynchronous batch interface. OpenAI's Batch API, for example, offers a 50% discount, a 24-hour completion window and a separate rate-limit pool (OpenAI Batch guide).
- Brownout. When no fallback can produce the needed samples (a candidate checkpoint usually has exactly one deployment), the platform degrades gracefully: it serves work that needs no new generation, such as pending overlap repeats, gold items or second reviews, and tells the vendor before the queue runs dry so that paid time can be redirected or paused.
- Isolation between campaigns. Several campaigns share the sampler and often the same endpoints. Each campaign gets its own generation queue and its own share of the client-side limit, so one campaign's refill burst cannot starve another's raters. The Amazon Builders' Library recommends the same pattern for multi-tenant queues, together with dropping messages that are too old to be useful (Yanacek, "Avoiding insurmountable queue backlogs"); for a sampler, "too old" means generated by a checkpoint the campaign no longer uses.
- Priorities and deadlines. Every generation request carries a priority (pre-generation is sheddable; a live multi-turn session with an expert is critical) and a deadline. Serving can shed sheddable work first, and drop work whose deadline has passed, because a sample nobody can use is wasted compute. AWS's Builders' Library makes the same point about server-side queues: work done after the client has given up is throughput but not goodput (Yanacek, "Using load shedding to avoid overload").
Compare and contrast. A web service usually protects itself from too many users. An RL data platform mostly protects a dependency from itself, and protects its users from that dependency. The mechanisms are the standard ones from distributed-systems practice; what changes is the objective. The quantity to maximise is useful rater-minutes, so a fallback that changes the data (serving an older checkpoint in place of the candidate) is worse than idling, while a fallback that changes only the order of work (overlap first, fresh pairs later) is nearly free.
What you would actually do. Size the buffer for the longest endpoint outage the campaign should absorb without intervention (one hour is a reasonable default), put exactly one retrying layer in the sampler, honour retry-after, set client limits at about 80% of provider limits, define a brownout queue for every campaign before launch, and alert on runway in minutes rather than on buffer depth in items. The next section shows the dashboards on which those runway and quality signals live.
Four calculations size the path to the endpoints: how many generations are in flight, how large the buffer must be, how much rate-limit headroom is needed, and how much extra load retries create.
Concurrency (Little's law). For any stable system the mean number of items inside equals the arrival rate times the mean time each spends inside, \(L = \lambda W\) (Little 1961). Here \(\lambda_g\) is the generation rate the sampler must sustain and \(W_g\) the time one generation takes.
Buffer size. Let \(T_o\) be the endpoint outage the buffer must absorb and \(\lambda_\ell\) the drain rate. The buffer must hold \(B \ge \lambda_\ell T_o\). Its cost is staleness: an item generated now and served in \(B/\lambda_\ell\) minutes was produced by whatever checkpoint was current then. For W1, \(B = 2{,}000\) gives \(T_o = 60\) min and items at most about an hour old at full drain, which is acceptable because both checkpoints are pinned by reference and do not change mid-campaign. For on-policy campaigns whose checkpoint advances during collection, \(B/\lambda_\ell\) must stay below the checkpoint refresh interval.
Retry amplification. If \(m\) layers each retry up to \(r\) times on failure, one logical request can become up to \((1+r)^m\) attempts. With the sampler retrying 3 times and a client library retrying 2 times by default, a failing request costs up to \(4 \times 3 = 12\) attempts, against 4 with the sampler alone. If the endpoint refused each attempt independently with probability \(f\), a single layer that retries until success or exhaustion would make \(\sum_{i=0}^{r} f^i = (1-f^{r+1})/(1-f)\) attempts on average: \(1.52\) at \(f = 0.35\) and \(r = 3\). Under that assumption nesting changes little, because the outer layer retries only when all three inner attempts fail (probability \(f^3 \approx 0.04\)), so the nested pair (\(r=3\) over \(r=2\)) makes about \(1.54\) attempts. Overload refusals are not independent, however: a retry sent milliseconds after a 429 meets the same saturated queue, so the inner layer's attempts tend to fail together and the effective \(f\) climbs as offered load grows. As \(f\) rises the two configurations separate quickly: at \(f = 0.8\) one layer makes \(2.95\) attempts per logical request and the nested pair \(4.66\), and as \(f \to 1\) they approach the worst cases of 4 and 12. Offered load therefore grows fastest exactly when the endpoint loses capacity. Setting \(m = 1\) is the single most effective reliability change.
Adaptive throttling. With \(R\) requests attempted and \(A\) accepted over a two-minute window, the client rejects locally with probability \(p = \max\!\left(0, \frac{R - K A}{R + 1}\right)\), the form described in the SRE book's "Handling Overload" chapter with \(K = 2\) preferred. If the endpoint can accept only 25% of the offered load, the client's offered load settles where \(R \approx K A\): roughly twice what is accepted rather than four times.
Runway as the alert unit. Runway \(T_B = B/\lambda_\ell\) in minutes is what an operator can act on; depth in items is not, because the same depth means different things at 09:00 (150 raters) and at 18:00 (20 raters). An alert at \(T_B < 20\) min leaves time to start the brownout and notify the vendor before anyone idles.
| Decision | Options | Default and the number behind it |
|---|---|---|
| Where generation happens | On demand · buffered | Buffered: 14 s generation versus 2 s TTFS target |
| Buffer size | Minutes of drain | 60 min (2,000 pairs for W1); shorter for on-policy campaigns |
| Retry layers | Every layer · one layer | One: removes the \((1+r)^m\) blow-up |
| Client limit | At provider limit · below | ≈ 80% of provider limit; leaves room for other tenants and avoids acceleration limits on sudden ramps |
| Pre-generation channel | Synchronous · batch | Batch when the campaign starts more than a day ahead (50% cheaper on providers that offer it); synchronous for refills |
| Fallback when the checkpoint has one deployment | Older checkpoint · brownout · pause | Brownout, then pause: substituting a checkpoint changes the data |
Table. Reliability design decisions. Token and speed figures are stated assumptions.
Anthropic's documentation also notes that a sharp increase in an organisation's usage can trigger 429s from acceleration limits and recommends ramping traffic gradually (Anthropic rate-limit docs); a campaign launch that fills a 2,000-pair buffer in one burst is exactly such a ramp, which is a second reason to pace the initial fill. The same page states that input tokens read from the prompt cache do not count toward the input-token-per-minute limit (cache writes still do), so campaigns with a long shared system prompt gain headroom from prompt caching.
The build artefacts are five small components and the configuration that wires them per model reference. Each is a pure function of time and observed outcomes, which makes them testable without a network.
TokenBucket: refill rate and capacity;try_take(now, cost)spends tokens or refuses. Use one bucket for requests and one for output tokens per model reference.AdaptiveThrottle: keeps (time, accepted) events for a two-minute window and rejects locally with probability \(\max(0, (R-KA)/(R+1))\).Breaker: CLOSED, OPEN after consecutive failures, HALF_OPEN after a cool-down; one probe decides.backoff_full_jitter: honoursretry-afterwhen present, otherwise sleeps uniformly in \([0, \min(\text{cap}, \text{base} \cdot 2^{n})]\).BufferController: maps (depth, drain rate, endpoint health) to a refill request and a serving mode: normal, brownout or pause.
"""Client-side protection for calls to live model endpoints (r-ops-rel).
TokenBucket - stay under the provider's RPM/OTPM limits before the provider says 429.
AdaptiveThrottle - reject locally when the backend is refusing (SRE book, K = 2).
Breaker - stop calling a failing model_ref; route to a fallback.
backoff_full_jitter - retry spacing (Brooker 2015).
BufferController - watermarks on the pre-generated buffer -> refill rate and admission (backpressure)."""
from __future__ import annotations
import random
class TokenBucket:
def __init__(self, rate_per_s: float, capacity: float):
self.rate, self.cap, self.tokens, self.t = rate_per_s, capacity, capacity, 0.0
def try_take(self, now: float, cost: float = 1.0) -> bool:
self.tokens = min(self.cap, self.tokens + (now - self.t) * self.rate); self.t = now
if self.tokens >= cost:
self.tokens -= cost; return True
return False
class AdaptiveThrottle:
"""p_reject = max(0, (requests - K*accepts) / (requests + 1)) over a sliding window."""
def __init__(self, k: float = 2.0, window_s: float = 120.0, rng=None):
self.k, self.w, self.ev, self.rng = k, window_s, [], rng or random.Random(0)
def _trim(self, now):
self.ev = [e for e in self.ev if now - e[0] <= self.w]
def p_reject(self, now) -> float:
self._trim(now)
req = len(self.ev); acc = sum(1 for _, ok in self.ev if ok)
return max(0.0, (req - self.k * acc) / (req + 1))
def allow(self, now) -> bool:
return self.rng.random() >= self.p_reject(now)
def record(self, now, accepted: bool):
self.ev.append((now, accepted))
class Breaker:
"""CLOSED -> OPEN after `fails` consecutive errors; OPEN -> HALF_OPEN after cool_s; one probe decides."""
def __init__(self, fails=5, cool_s=30.0):
self.max, self.cool, self.n, self.state, self.opened = fails, cool_s, 0, "CLOSED", 0.0
def allow(self, now) -> bool:
if self.state == "OPEN" and now - self.opened >= self.cool:
self.state = "HALF_OPEN"
return self.state != "OPEN"
def record(self, now, ok: bool):
if ok:
self.n, self.state = 0, "CLOSED"
else:
self.n += 1
if self.state == "HALF_OPEN" or self.n >= self.max:
self.state, self.opened = "OPEN", now
def backoff_full_jitter(attempt: int, base=0.5, cap=30.0, retry_after: float | None = None, rng=random):
"""Honour the server's retry-after when present; otherwise sleep U(0, min(cap, base*2^attempt))."""
if retry_after is not None:
return retry_after + rng.uniform(0, base)
return rng.uniform(0, min(cap, base * 2 ** attempt))
class BufferController:
"""Decides, every tick, how many pairs to request and whether to admit raters.
depth: ready pairs in the buffer; drain: pairs/min consumed by raters."""
def __init__(self, low=500, high=2000, admit_floor=100):
self.low, self.high, self.floor = low, high, admit_floor
def plan(self, depth: int, drain_per_min: float, healthy: bool) -> dict:
minutes_left = depth / drain_per_min if drain_per_min else float("inf")
if not healthy:
mode = "brownout" if depth > self.floor else "pause_supply"
return {"request": 0, "mode": mode, "minutes_left": round(minutes_left, 1)}
want = self.high - depth if depth < self.low else max(0, int(drain_per_min * 5))
return {"request": want, "mode": "normal", "minutes_left": round(minutes_left, 1)}
Configuration. Endpoint profiles set client limits below the provider's, allow exactly one retrying layer, and say what to do when a model reference has no fallback.
# Endpoint profiles used by the sampler (r-ops-rel). Limits are set BELOW the provider's
# published limits so the client, not the provider, does the throttling.
defaults:
retries: {max_attempts: 4, base_s: 0.5, cap_s: 30, honour_retry_after: true}
sdk_retries: 0 # exactly one retrying layer: the sampler
adaptive_throttle_k: 2.0
breaker: {fails: 5, cool_s: 30}
deadline_s: 120 # a pre-generation sample older than this is not worth waiting for
model_refs:
"ckpt:current":
primary: {endpoint: serving-prod, rpm: 600, otpm: 400000, priority: SHEDDABLE_PLUS}
fallbacks: [{endpoint: serving-prod-region-b, rpm: 300, otpm: 200000}]
"ckpt:candidate": # research deployment: fewer replicas, restarts during evals
primary: {endpoint: serving-research, rpm: 150, otpm: 110000, priority: SHEDDABLE_PLUS}
fallbacks: [] # no second copy: same checkpoint is required for the comparison
on_exhausted: brownout # serve overlap repeats / gold while it recovers
buffer: {high: 2000, low: 500, floor: 100, runway_alert_min: 20}
Tests. The bucket test offers 10 requests per second for 60 seconds to a 2-per-second bucket and checks that about 120 (plus the initial burst) get through. The throttle test simulates an endpoint that accepts 25% of what reaches it and checks that the client stops sending most of the doomed traffic. The last two tests are W1 arithmetic: 2,000 pairs at 33.3 per minute is 60 minutes of runway, and the candidate profile has at least three times the steady-state request and token needs.
import random
from rdp.reliability import TokenBucket, AdaptiveThrottle, Breaker, backoff_full_jitter, BufferController
def test_token_bucket_enforces_rate():
b = TokenBucket(rate_per_s=2.0, capacity=4) # 120 RPM with a burst of 4
granted = sum(b.try_take(t / 10) for t in range(600)) # 60 s, offered 10 req/s
assert 120 <= granted <= 124 # 2/s * 60 s + initial burst
def test_adaptive_throttle_converges_to_k_times_accepts():
th, rng = AdaptiveThrottle(k=2.0, rng=random.Random(1)), random.Random(2)
sent = 0
for i in range(6000): # backend accepts only 25% of what reaches it
now = i * 0.02
if th.allow(now):
sent += 1; th.record(now, rng.random() < 0.25)
else:
th.record(now, False) # local rejects still count as requests
# without throttling the backend would see 6000; with it, roughly 2x what it accepts
assert sent < 4000
def test_breaker_opens_and_probes():
br = Breaker(fails=3, cool_s=10)
for t in range(3): br.record(t, False)
assert not br.allow(5) and br.allow(13) # open, then half-open after cool-down
br.record(13, False); assert br.state == "OPEN"
assert br.allow(24); br.record(24, True); assert br.state == "CLOSED"
def test_backoff_respects_retry_after_and_cap():
rng = random.Random(0)
assert 7.0 <= backoff_full_jitter(1, retry_after=7.0, rng=rng) <= 7.5
assert all(0 <= backoff_full_jitter(20, rng=rng) <= 30 for _ in range(100))
def test_w1_buffer_lasts_60_minutes_at_full_pool():
drain = 150 / 4.5 # 150 raters, 4.5 min mean -> 33.3 pairs/min
plan = BufferController().plan(depth=2000, drain_per_min=drain, healthy=False)
assert plan["mode"] == "brownout" and plan["minutes_left"] == 60.0
assert BufferController().plan(400, drain, True)["request"] == 1600 # refill to high watermark
def test_endpoint_profiles_have_headroom_for_w1():
import yaml, pathlib
cfg = yaml.safe_load(pathlib.Path("rdp/endpoints.yaml").read_text())
need_rpm = 150 / 4.5 # one candidate response per pair, 33.3 per minute at peak
need_otpm = need_rpm * 700 # ASSUMED 700 output tokens per response
cand = cfg["model_refs"]["ckpt:candidate"]["primary"]
assert cand["rpm"] >= 3 * need_rpm and cand["otpm"] >= 3 * need_otpm # 3x headroom for refill bursts
assert cfg["defaults"]["sdk_retries"] == 0
$ python3 -m pytest -q test_reliability.py
...... [100%]
6 passed
Debugging tips. If the bucket admits far more than expected, the clock passed in is probably wall time in milliseconds rather than seconds. If the throttle never rejects, local rejections are not being recorded as requests, so \(R\) never exceeds \(KA\). If the breaker flaps between OPEN and CLOSED every cool-down, the probe is succeeding on a cached response; send probes with a fresh idempotency key.
SLOs and alerts. The human-facing SLO is time to first sample (95% within 5 s, p50 within 2 s, 28-day window). The leading indicator is buffer runway, which falls well before the SLO burns. Burn-rate alerting follows the multiwindow pattern from the Google SRE workbook: page when the error budget is burning 14.4 times faster than sustainable over one hour and still burning over the last five minutes; page also at 6 times over six hours (30-minute short window); and raise a ticket at 1 times over three days (6-hour short window) (Google SRE workbook, "Alerting on SLOs"; implementation in Grafana Labs 2025). Over a 30-day window, a 14.4× burn for one hour consumes about 2% of the budget, and a 6× burn for six hours about 5%. The alert file below implements the fast-burn page; the slower tiers follow the same pattern.
groups:
- name: rdp-slo
rules:
- alert: TTFSBudgetBurnFast # W1 SLO: 95% of first samples <= 5 s, 28-day window
expr: |
(1 - sum(rate(rdp_first_sample_seconds_bucket{le="5"}[1h])) / sum(rate(rdp_first_sample_seconds_count[1h]))) > 14.4 * 0.05
and
(1 - sum(rate(rdp_first_sample_seconds_bucket{le="5"}[5m])) / sum(rate(rdp_first_sample_seconds_count[5m]))) > 14.4 * 0.05
labels: {severity: page}
- alert: BufferRunwayLow # minutes of work left in the pre-generated buffer
expr: rdp_buffer_ready_items / clamp_min(rate(rdp_items_leased_total[10m]) * 60, 1) < 20
for: 5m
labels: {severity: page}
- alert: EndpointThrottled
expr: sum by (model_ref) (rate(rdp_generate_responses_total{code="429"}[5m])) / sum by (model_ref) (rate(rdp_generate_responses_total[5m])) > 0.10
for: 10m
labels: {severity: ticket}
- alert: FeedbackWriteErrors # labels are irreplaceable paid human work: page on any loss risk
expr: sum(rate(rdp_feedback_append_errors_total[5m])) > 0
for: 2m
labels: {severity: page}
The serving side exposes its own signals; vLLM, for example, exports vllm:num_requests_waiting, vllm:num_requests_running, vllm:gpu_cache_usage_perc, vllm:time_to_first_token_seconds and vllm:num_preemptions_total (vLLM production metrics). Putting the endpoint's waiting-queue length next to the platform's 429 ratio and runway on one panel is what separates "the endpoint is overloaded" from "the endpoint is down" from "our client is misbehaving".
Symptom. Day 3 of collection, 09:00. The research deployment serving the candidate checkpoint is redeployed for an evaluation; one of its two replicas fails its health check, halving capacity. The 429 ratio for ckpt:candidate rises to 35%. At 09:00 the buffer holds 1,400 pairs (refill had lagged overnight), a runway of 42 minutes at 33.3 pairs per minute.
Amplification. The sampler retried three times and the client library retried twice underneath it. The endpoint's request log shows offered load at 2.3 times the logical request rate, well above the 1.54 that independent refusals at \(f = 0.35\) would predict: the client library retried within milliseconds of each 429 and met the same saturated queue, so refusals were correlated, as the design level warns; the extra load pushed the surviving replica's waiting queue (vllm:num_requests_waiting) from about 10 to over 200 and its time to first token past the sampler's 120 s deadline, so successful generations fell further.
Detection. BufferRunwayLow (runway < 20 min for 5 min) fired at 09:27. The on-call engineer followed the runbook but the campaign had no brownout queue configured, so at 09:42 the buffer reached zero and the TTFS p95 rose to 38 s. The TTFS fast-burn page fired at 09:44.
Remedy, in order. (1) Disable client-library retries so only the sampler retries, and honour retry-after; offered load fell to about 1.5 times logical within minutes. (2) Enable adaptive throttling with K = 2 on the candidate route. (3) At 10:27 enable the brownout queue: the 4,000 pending overlap repeats need no generation, enough for two hours at full drain. (4) After the second replica recovered at about 10:40, pace refill to 100 extra pairs per minute rather than a single burst, to avoid tripping acceleration limits on a shared endpoint.
Cost. 45 minutes of starvation (09:42 to 10:27) for 150 raters is 112.5 rater-hours, $4,500 at $40/h, more than ten times the entire W1 generation bill computed in cost accounting. An automatic brownout at 20 minutes of runway would have reduced the idle time to near zero.
Validation. The fix is supported if, in the next candidate redeploy, offered/logical stays under 1.6, runway never crosses the 100-pair floor while brownout work remains, and idle rater-minutes stay under 1% of paid minutes for the day. It is weakened if runway still collapses with retries reduced, which would mean the refill rate itself is too low for the candidate's capacity and the buffer must be filled earlier (for example overnight through a batch channel).
Runbook: buffer runway low.
- Read runway, 429 ratio and generation success by
model_ref. If only one model reference is failing, the problem is that endpoint; otherwise check the sampler itself (deploy, credentials, spend cap; a spend-cap 429 has noretry-afterand will not clear by retrying, per the Anthropic rate-limit docs). - Compute offered/logical request ratio. If above 1.6, remove nested retries before anything else.
- If a fallback exists for the failing reference, open the breaker manually and route to it; confirm the fallback serves the same checkpoint hash.
- If no fallback exists and runway < 20 min, enable brownout for the campaign and notify the vendor with the expected duration of brownout work.
- If brownout work will run out before the endpoint returns, ask the vendor to pause the paid clock or move raters to another campaign with the same qualification.
- After recovery, pace refill, record idle rater-minutes, and add the campaign's missing brownout queue to its spec template.
The panels used in this incident (runway, 429 ratio, offered/logical, idle minutes) are platform-operator views. The next section turns to the views researchers use to judge the data itself.
Dashboards and inspection tools for researcher self-serve
What self-serve means. A researcher who launches a campaign has questions every day: is data arriving, is it good, are the raters disagreeing about something specific, which items are behind a strange number, when will the dataset be ready, what has it cost so far? On a platform without self-serve tools, each question becomes a request to the platform team, who run a query and reply. Researcher self-serve means the researcher can answer these questions directly, with tools that are correct by default and safe to use. The share of such questions answered without a ticket is one of the platform's north-star metrics (see north-star metrics).
Why it matters. The request-to-mix clock in W1 is 21 days, and a large part of the waiting is between people: noticing a problem, asking, waiting for an answer, deciding. Inspection tools shorten that loop. They also improve data quality, because the researcher is usually the person who can recognise that a pattern in the labels is a guideline problem rather than a rater problem.
The tools, from summary to single item.
- Campaign dashboard. A fixed set of panels per campaign, each a time series with the current value: time to first sample, buffer runway, labels per hour, gold accuracy, agreement on overlap items, low-effort flags, the request-to-mix stage clock, and cost per useful label. A filter row above all panels sets the campaign, time range and a slice (a subset such as one rater cohort, one prompt tag, or one model reference).
- Item inspector. Clicking any point on a panel lists the items behind it. Opening an item shows the prompt, every sample with its metadata (model reference, token counts, whether generation stopped because it hit the length limit), every label with the rater's pseudonym and active time, and every quality verdict. This is the tool that turns "agreement dropped" into "these 40 items have truncated responses".
- Slice and query tool. Saved, parameterised queries over a read-only copy of the data (the warehouse), plus a notebook or SQL editor for new questions. The saved queries are the panels' own definitions, so a researcher can start from exactly what the dashboard computed.
- Lineage view. For a dataset version: which campaigns, which quality filter, how many rows were dropped and why. For a label: which datasets include it. (See provenance and versioning.)
- Subscriptions. A researcher can subscribe to a panel threshold (for example agreement below 65% for six hours) and receive a message, instead of watching the dashboard.
Three design rules make these tools trustworthy. First, every number shows its uncertainty and its freshness: a gold accuracy computed from eight items is labelled as such, and a panel whose data is older than its freshness objective says "stale". Second, every number is clickable down to items, because an aggregate a researcher cannot inspect is an aggregate they will not trust. Third, the tools run on a read-only copy, never on the live database, and respect the same access rules as everything else: a researcher sees rater pseudonyms and aggregated rater statistics, not identities (see governance).
Compare and contrast. Generic BI dashboards show aggregates; experiment-tracking tools show training curves. Neither knows what an item, a gold item or an overlap group is, and neither can open the exact responses a rater saw. The inspection tools here are domain-specific, and their cost is maintenance: every new feedback type (see adding a feedback type) needs its own item renderer and its own quality panels.
What you would actually do. Ship the eight panels and the item inspector with the first campaign, on a replica with a 15-minute freshness objective; add the slice tool next; let researchers save queries and promote the useful ones into panels. Measure the self-serve rate by tagging every platform-team ticket that asks a data question that a panel or saved query could have answered. The data these tools expose is sensitive, which is the subject of the next section.
A panel is useful only if the decision it supports is larger than its noise. This makes the statistics of the panels, not their visual design, the main design problem.
Per-rater gold accuracy is noisy. A rater who has answered \(n_g\) gold items with \(k\) correct has accuracy \(\hat p = k/n_g\) and standard error \(\sqrt{\hat p(1-\hat p)/n_g}\). With small \(n_g\) the normal interval behaves badly, so panels use the Wilson score interval, whose centre and half-width are
\[ \tilde p = \frac{\hat p + \frac{z^2}{2n_g}}{1 + \frac{z^2}{n_g}}, \qquad h = \frac{z}{1 + \frac{z^2}{n_g}} \sqrt{\frac{\hat p(1-\hat p)}{n_g} + \frac{z^2}{4 n_g^2}} , \]with \(z = 1.96\) for 95%. A rater is flagged only when the whole interval lies below the threshold.
Campaign-level agreement is precise. Pairwise agreement on overlap items is a proportion over many pairs: with 2,000 overlap items labelled by 3 raters there are 6,000 rater pairs; treating them as independent (an optimistic assumption, since pairs share items) gives a standard error of about \(\sqrt{0.72 \cdot 0.28 / 6000} \approx 0.006\). A drop from 72% to 65% is many standard errors and worth a subscription alert; a drop to 71% is not.
Freshness. If the replica lags the primary by \(\ell\) and the panel's query runs every \(q\) minutes, the data on screen is up to \(\ell + q\) old. A 15-minute freshness objective with a 5-minute refresh leaves 10 minutes of acceptable replication and batch lag. At W1's 33.3 labels per minute, 15 minutes is about 500 labels, about 2% of the campaign, which is acceptable for decisions made on the scale of hours.
Which panels, and how each is computed.
| Panel | Formula | Decision it supports | Noise control |
|---|---|---|---|
| Time to first sample | p50, p95 of first-sample latency | Is supply healthy? | Per-hour quantiles; hide hours with < 50 events |
| Buffer runway | ready items / drain per minute | Act before raters idle | 10-min drain average |
| Labels per hour | count by hour | On track for the stopping rule? | Compare to plan line |
| Gold accuracy | correct / gold answered | Rater removal; gold-item errors | Wilson interval; flag only if upper bound < threshold |
| Agreement on overlap | mean pairwise match | Guideline ambiguity | Slice only when slice has ≥ 200 pairs |
| Low-effort flags | raters with median active time < floor | Review queue | Require ≥ 20 labels per rater |
| Request-to-mix clock | days in each stage | Where is the bottleneck? | None needed |
| Cost per useful label | spend / accepted units; estimate at completion | Budget | Show projection band |
Table. Dashboard panels, their formulas and how each controls noise. Thresholds are recommended defaults.
What you would actually do. Put intervals on every proportion, suppress slices below a minimum sample size rather than show noisy numbers, and design the gold schedule so that each rater accumulates enough gold early. Deviate from fixed panels only by promoting saved queries that researchers actually reuse.
The build artefacts are the panel queries as a named SQL file, a small runner that turns query results into panel values with Wilson intervals, and a test on a synthetic W1 database. The schema has two tables: events (one row per platform event such as first_sample, with its latency in milliseconds) and labels (one row per label, with active time, gold flags and an overlap marker).
Named queries. Keeping every panel's SQL in one file, with a -- name: header, means the dashboard, the slice tool and the tests run exactly the same text. The low-effort query uses window functions to compute each rater's median active time on non-gold items.
-- Self-serve panels (r-ops-observe). Tables: events(campaign_id, item_id, rater, kind, ts, ms)
-- and labels(campaign_id, item_id, rater, choice, active_ms, is_gold, gold_ok, overlap_group, ts).
-- name: throughput_per_hour
SELECT strftime('%Y-%m-%d %H:00', ts, 'unixepoch') AS hour, COUNT(*) AS labels
FROM labels WHERE campaign_id = :cid GROUP BY hour ORDER BY hour;
-- name: ttfs_quantiles
SELECT ms FROM events WHERE campaign_id = :cid AND kind = 'first_sample' ORDER BY ms;
-- name: gold_accuracy_by_rater
SELECT rater, SUM(gold_ok) * 1.0 / COUNT(*) AS gold_acc, COUNT(*) AS n_gold
FROM labels WHERE campaign_id = :cid AND is_gold = 1 GROUP BY rater ORDER BY gold_acc;
-- name: pairwise_agreement
SELECT AVG(CASE WHEN a.choice = b.choice THEN 1.0 ELSE 0.0 END) AS agree, COUNT(*) AS pairs
FROM labels a JOIN labels b ON a.item_id = b.item_id AND a.rater < b.rater
WHERE a.campaign_id = :cid AND a.overlap_group = 1;
-- name: low_effort_raters
WITH ranked AS (
SELECT rater, active_ms,
ROW_NUMBER() OVER (PARTITION BY rater ORDER BY active_ms) AS rn,
COUNT(*) OVER (PARTITION BY rater) AS n
FROM labels WHERE campaign_id = :cid AND is_gold = 0)
SELECT rater, n, active_ms AS median_ms FROM ranked
WHERE rn = (n + 1) / 2 AND active_ms < 40000 ORDER BY median_ms;
Runner. The runner executes the named queries against a read-only connection and applies the noise rules from the design table: quantiles from the sorted latencies and a Wilson upper bound for gold flags.
"""Run the named panel queries against a read replica (here: sqlite) and compute panel values.
Usage: python3 -m rdp.observe <db> <campaign_id>"""
from __future__ import annotations
import math, re, sqlite3, sys, pathlib
SQL = pathlib.Path(__file__).with_name("panels.sql").read_text()
QUERIES = {m.group(1): m.group(2).strip() for m in
re.finditer(r"-- name: (\w+)\n(.*?;)", SQL, flags=re.S)}
def q(db, name, cid):
return db.execute(QUERIES[name], {"cid": cid}).fetchall()
def quantile(xs, p):
if not xs: return None
i = min(len(xs) - 1, max(0, math.ceil(p * len(xs)) - 1)); return xs[i]
def wilson(k, n, z=1.96):
"""95% interval for a proportion; dashboards show it so small-n raters are not judged on noise."""
if n == 0: return (0.0, 1.0)
p = k / n; d = 1 + z*z/n; c = (p + z*z/(2*n)) / d
h = z * math.sqrt(p*(1-p)/n + z*z/(4*n*n)) / d
return (round(c - h, 3), round(c + h, 3))
def panels(db, cid):
ttfs = [r[0] for r in q(db, "ttfs_quantiles", cid)]
gold = q(db, "gold_accuracy_by_rater", cid)
out = {
"ttfs_p50_ms": quantile(ttfs, .50), "ttfs_p95_ms": quantile(ttfs, .95),
"agreement": q(db, "pairwise_agreement", cid)[0],
"low_effort_raters": [r[0] for r in q(db, "low_effort_raters", cid)],
# flag only raters whose whole interval is below the 80% gold threshold
"gold_flagged": [r for r, acc, n in gold if wilson(round(acc*n), n)[1] < 0.80],
}
return out
if __name__ == "__main__":
print(panels(sqlite3.connect(sys.argv[1]), sys.argv[2]))
Test. The synthetic database has 6,000 labels from 150 raters, of whom six (4%) work too fast (15–39 s per label) and one has 30% gold accuracy, plus 200 overlap items labelled by three raters with 72% of items unanimous. The test checks that time-to-first-sample quantiles fall inside W1's targets, that exactly the six fast raters are flagged, and that the 200 overlap items produce 600 rater pairs.
import random, sqlite3
from rdp.observe import panels, wilson
def make_db(seed=3):
rng, db = random.Random(seed), sqlite3.connect(":memory:")
db.execute("CREATE TABLE events(campaign_id, item_id, rater, kind, ts, ms)")
db.execute("CREATE TABLE labels(campaign_id, item_id, rater, choice, active_ms, is_gold, gold_ok, overlap_group, ts)")
cid = "w1_coding_pref"
raters = [f"r{i:03d}" for i in range(150)]
fast = set(raters[:6]) # 4% of 150 = 6 low-effort raters
bad_gold = "r149"
for i in range(6000):
r = rng.choice(raters)
ms = int(rng.uniform(15_000, 39_000)) if r in fast else int(rng.lognormvariate(12.4, 0.5))
is_gold = rng.random() < 0.05
ok = (rng.random() < (0.30 if r == bad_gold else 0.88)) if is_gold else None
db.execute("INSERT INTO labels VALUES (?,?,?,?,?,?,?,?,?)",
(cid, f"i{i}", r, rng.choice("AB"), ms, int(is_gold), ok, 0, 1_762_700_000 + i * 10))
db.execute("INSERT INTO events VALUES (?,?,?,?,?,?)",
(cid, f"i{i}", r, "first_sample", 0, int(rng.lognormvariate(6.9, 0.55))))
for g in range(200): # overlap items labelled by 3 raters
choices = ["A"] * 3 if rng.random() < 0.72 else ["A", "A", "B"]
for k, c in enumerate(choices):
db.execute("INSERT INTO labels VALUES (?,?,?,?,?,?,?,?,?)",
(cid, f"o{g}", f"r{k+10:03d}", c, 240_000, 0, None, 1, 0))
return db, cid
def test_panels_on_synthetic_w1():
db, cid = make_db()
p = panels(db, cid)
assert 700 <= p["ttfs_p50_ms"] <= 1300 and p["ttfs_p95_ms"] < 5000 # within W1 TTFS targets
assert set(p["low_effort_raters"]) == {f"r{i:03d}" for i in range(6)}
agree, pairs = p["agreement"]
assert pairs == 600 and 0.70 < agree < 0.90
def test_wilson_protects_small_n():
assert wilson(6, 8)[1] > 0.80 # 75% on 8 gold items: not enough evidence to flag
assert wilson(60, 80)[1] < 0.85
$ python3 -m pytest -q test_observe.py
.. [100%]
2 passed
Note that the low-accuracy rater r149 is not asserted as flagged: with about 2 gold items in this synthetic set (6,000 labels / 150 raters × 5%), its Wilson upper bound is above 80%, which is the W1 small-sample problem from the design level showing up in a test. Debugging tips. If the agreement query returns triple the expected pairs, the join is missing a.rater < b.rater and counts each pair in both orders plus self-pairs. If quantiles disagree with the serving team's numbers, check whether both sides use the same quantile definition (nearest-rank here) and the same event (first sample served, not first sample generated).
SLOs for the inspection tools. The tools have their own users and objectives: panels load within 3 s for 95% of loads; data is no more than 15 minutes old for 99% of panel loads; the item inspector opens any item within 2 s; and no self-serve query may run on the primary database. Queries from the slice tool run with a statement timeout (for example 60 s) and a per-user concurrency cap on the warehouse, so one large exploratory query cannot starve the dashboards.
Dashboard specification. The panels are defined as code next to their queries so that every campaign gets the same dashboard and every change is reviewed:
dashboard: campaign_overview
filters: [campaign_id, time_range, slice: {rater_cohort, prompt_tag, model_ref}]
panels:
- {name: ttfs, query: ttfs_quantiles, show: [p50, p95], slo_line: {p50: 2000, p95: 5000}}
- {name: runway, query: buffer_runway, unit: minutes, alert_below: 20}
- {name: labels_per_hour, query: throughput_per_hour, plan_line: from_campaign_spec}
- {name: gold_accuracy, query: gold_accuracy_by_rater, interval: wilson95, flag: upper_lt_0.80, min_n: 10}
- {name: agreement, query: pairwise_agreement, min_pairs_per_slice: 200, subscribe_default: lt_0.65_for_6h}
- {name: low_effort, query: low_effort_raters, min_labels: 20}
- {name: request_to_mix, query: stage_clock, stages: [scope, pilot, collect, qa, export, mix]}
- {name: cost, query: spend_and_useful, show: [per_useful, estimate_at_completion]}
# buffer_runway, stage_clock and spend_and_useful are served by the sampler and cost modules
drilldown: item_inspector # every point -> items; every item -> samples, labels, verdicts, lineage
freshness_slo_minutes: 15
Symptom. On collection day 3 the researcher's subscription fires: agreement on overlap items has been below 65% for six hours (it reads 65.2% for the day, against 72% on days 1 and 2). Gold accuracy and the low-effort panel are unchanged, which already argues against a rater problem.
Separating causes. Three hypotheses fit falling agreement with stable gold: a new, harder prompt subset; a guideline change; or a change in the samples themselves. Slicing agreement by prompt tag shows the drop spread across all tags, which weakens the first hypothesis. The guideline version is unchanged. Slicing by a sample attribute (finish reason) is decisive: 31% of overlap items labelled that day contain at least one response that stopped because it hit the length limit, against under 2% on earlier days. On those items agreement is 50%, near chance for a binary choice, while the rest sit at 72%; the mix \(0.31 \times 0.50 + 0.69 \times 0.72 \approx 0.65\) reproduces the panel. The item inspector shows truncated code ending mid-function in one or both responses. The campaign's history shows a revision on day 2 that reduced max_tokens from 1,024 to 512 to speed up refill.
Remedy. (1) Revert max_tokens and invalidate unserved buffered items generated under the bad revision. (2) Add a sample contract check to the sampler: an item is not admitted to the buffer if any response has finish reason "length", and the sampler alerts if more than 2% of generations are truncated. (3) Mark labels on truncated items as reject:invalid_sample in the quality service so the pipeline excludes them, and re-queue those prompts.
Cost. Day 3 produced about one sixth of the 25,260 assignments, roughly 4,200; at a 31% truncation rate about 1,300 labels were wasted, about $3,900 at $3.00 per assignment, plus the regeneration. Without the subscription it would most likely have been found at export, after three more days and about four times the loss.
Validation. The fix is supported if, on the next full day, truncated items are under 2% and agreement returns to within one standard error (about 0.6 points) of 72%. It is weakened if agreement stays low after truncation is removed, which would send the investigation back to prompts or guidelines.
Runbook: a researcher reports a data anomaly.
- Reproduce the number from the panel's saved query; if it differs, the problem is the tool (freshness, query bug), not the data.
- Check which panels moved together. Quality panels moving with stable effort and gold point at items or guidelines; gold falling with effort flags rising point at raters (see detecting low-effort work).
- Slice by sample attributes (model reference, finish reason, length), prompt attributes and rater cohort; stop at the first slice that explains most of the change.
- Open at least 20 items in the inspector from the worst slice and 20 from a healthy slice before deciding.
- Fix forward (config, guideline, rater action), mark affected labels with a verdict rather than deleting them, and add a contract check or subscription so the same cause is caught automatically next time.
Security, privacy, access control, retention and data governance
What is being protected. An RL data platform holds three different kinds of sensitive data, and each needs different rules. The first is confidential model material: prompts that reveal research directions and outputs from unreleased checkpoints. The second is personal data inside the content: an agent transcript can contain a user's name, an email address, or a credential that a tool printed. The third is personal data about the workforce: who the raters and experts are, what they are paid, and detailed behavioural records (time per item, gold accuracy, flags) that can affect their income. Governance is the set of rules and mechanisms that decide who may see each kind of data, for what purpose, for how long, and how that is proven afterwards.
Why it is harder here than in an ordinary application. The platform deliberately shows sensitive material to many people outside the organisation: vendor raters and contracted experts. It also copies data forward into derived artefacts (labels, training examples, dataset versions, dashboards) whose purpose is to be used by training jobs and researchers. A rule that is enforced only at the source is therefore not enough; it must travel with the data.
The mechanisms, following the data from source to aggregate.
- Data classes. Every stored object is tagged with a class (public prompt, model output, agent transcript, rater identity, rater behaviour, feedback label). Retention, access and export rules attach to the class, not to individual tables, so a new table inherits the right rules by being tagged.
- Scanning gates. Before an item is shown to a person, content is scanned for secrets (API keys, tokens, private keys) and personal data, and either redacted or held back. For W2 transcripts this matters most, because tool outputs are verbatim records of whatever the agent touched.
- Pseudonymisation. The platform never stores a vendor's worker ID next to labels. It stores a pseudonym: a keyed hash of the worker ID, computed with a secret key held in a key-management service. The same worker always gets the same pseudonym, so quality tracking works, but the pseudonym cannot be reversed without the key. Only the vendor (or a small vault role) can map a pseudonym back to a person, for payment or appeals.
- Least-privilege, attribute-based access. Access is denied unless a rule allows it. Rules use attributes of the person, the data and the situation rather than fixed role lists alone; this is attribute-based access control (ABAC), defined by NIST as deciding whether to allow an operation by evaluating attributes of the subject, the object, the operation and sometimes the environment against policy (Hu et al., NIST SP 800-162). Example: a rater may read a transcript only while holding an active lease on it, and only their own lease.
- Aggregation floors. Researchers see rater behaviour only in aggregates with at least \(k\) raters per cell (for example \(k = 5\)), and individual-level records only through the quality team, whose purpose is rater management.
- Retention and deletion. Each class has a retention period. The GDPR's principles of data minimisation and storage limitation say personal data should be limited to what is necessary and kept in identifiable form no longer than necessary for its purpose (GDPR Article 5). A sweeper deletes expired objects, and a deletion request (for example a rater leaving a programme, or a transcript found to contain a third party's data) follows lineage, the recorded parent-to-child links, to every derived label, dataset row and dataset version, which are then rebuilt without it.
- Audit and documentation. Every read of a sensitive class and every export is logged with who, what and why. Each released dataset version carries a datasheet describing its motivation, composition, collection process and recommended uses, following the "Datasheets for Datasets" proposal (Gebru et al.).
[SECRET:aws_key]) so the expert still sees that the agent leaked a key, which may be exactly the failing step to label. Experts see a transcript only while their lease is active; the corrected continuation they write is stored as a label under their pseudonym. The transcripts are retained for 365 days; the labels, which contain no raw identity, are kept as long as the dataset is in use.Compare and contrast. A conventional application mostly protects data from outsiders. Here the "outsiders" are part of the workflow, so the controls shift from perimeter to purpose: what a person may see depends on the task they are doing right now. The cost is friction: scanning adds latency to item preparation, aggregation floors frustrate researchers who want per-rater detail, and deletion propagation requires lineage that is complete. Rater welfare questions, such as exposure to harmful content, are governed by the same machinery and are discussed in annotator wellbeing.
What you would actually do. Tag every object with a data class at write time, scan before serving rather than after labelling, store only pseudonyms next to labels, make every access rule deny-by-default and lease-scoped for raters, and test deletion propagation on a real dataset before the first campaign. Deviate (for example, show researchers per-rater records) only through a named role with a logged purpose. Governance also has a price, which the next section counts along with everything else.
Governance design becomes quantitative through three questions: how many people see each sensitive object, how far a deletion fans out, and how much residual risk the scanning gate leaves.
Exposure. Let \(N\) be the number of items, \(\rho\) the mean number of people who view each (including overlap and review), and \(s\) the fraction of items containing sensitive content that slips past the scanner. Expected human exposures of unscanned sensitive content are \(E = N \rho s\).
Deletion fan-out. Lineage is a directed graph from sources to derived artefacts. Deleting a source requires visiting every descendant. For W2, one transcript has on average 1.1 reviews, each producing one label row; each export of the campaign's dataset is a new version containing that row. With \(v\) versions published, a single deletion touches \(1 + 1.1 + 1.1 + v\) objects (the transcript, its 1.1 review assignments on average, their 1.1 label rows, and \(v\) dataset versions) and forces \(v\) dataset rebuilds. Rebuilds are cheap (the W2 dataset is about 200 MB). Models already trained on a version cannot practically be "untrained"; the policy therefore has to say what deletion means for them (typically: excluded from future versions and future training, with the model's training manifest recording what it used).
Retention arithmetic. The volume held for each class is its arrival rate times its retention. If the platform runs campaigns with a combined 10,000 transcripts a month and retains transcripts for 365 days, steady state is 120,000 transcripts, about 12 GB at 100 KB each; storage cost is negligible, so retention periods should be set by purpose and risk, not by storage cost.
| Data class | Who may read | Retention (default) | Gate before use |
|---|---|---|---|
| Public prompt | Raters (leased), researchers | Keep | Decontamination checks (validation) |
| Model output | Raters (leased), researchers on the project | 730 days | Content scan |
| Agent transcript | Raters (leased), researchers on the project | 365 days | Secret + personal-data scan; export denied unless clean |
| Rater identity | Vendor admin only | 180 days after last work | Never leaves vendor vault |
| Rater behaviour | Quality team; researchers as aggregates with \(k \ge 5\) | 365 days | Aggregation floor |
| Feedback label | Researchers on the project; pipeline | Keep while datasets use it | Pseudonymous; accepted verdict for export |
Table. Data classes with recommended access and retention defaults. Periods are illustrative policy choices, not legal advice; the right periods depend on contracts, jurisdiction and purpose.
Access-review load. With \(u\) users holding \(g\) grants on average and a review every \(T\) days, reviewers must confirm \(ug/T\) grants per day. 200 users with 6 grants reviewed quarterly is about 13 grants a day; expiring grants automatically after 90 days unless renewed removes most of that work and is the recommended default.
What you would actually do. Treat the scanner's recall as a number to measure (seed known secrets into a test set and count what it catches), make lineage complete enough that deletion fan-out is a query rather than an investigation, and choose retention by purpose. The binding trade-off is researcher convenience against workforce privacy; aggregation floors and a named quality role are the default compromise.
The build artefacts are a policy file (data classes, retention and access rules) and four functions: a keyed pseudonym, an access decision, a retention sweeper and deletion propagation over lineage. Each is small enough to audit line by line, which is the point of governance code.
# Access policy (r-ops-gov). Deny by default; first matching allow wins only if no deny matches.
data_classes:
public_prompt: {retention_days: null} # keep; no personal data
model_output: {retention_days: 730}
agent_transcript: {retention_days: 365, scan: [secrets, pii]} # W2: tool outputs can carry secrets
rater_identity: {retention_days: 180, store: vendor_vault_only}
rater_behaviour: {retention_days: 365} # timings, gold scores: personal data about raters
feedback_label: {retention_days: null, pseudonymous: true}
rules:
- {effect: allow, role: rater, action: read, class: [public_prompt, model_output, agent_transcript],
when: "assignment.active and assignment.rater == subject.id"}
- {effect: allow, role: researcher, action: read, class: [feedback_label, model_output, public_prompt],
when: "subject.project in resource.projects"}
- {effect: allow, role: researcher, action: read, class: [rater_behaviour], when: "resource.aggregated and resource.k >= 5"}
- {effect: allow, role: quality_lead, action: read, class: [rater_behaviour], when: "subject.project in resource.projects"}
- {effect: allow, role: pipeline, action: export, class: [feedback_label], when: "resource.quality_verdict == 'accept'"}
- {effect: deny, role: "*", action: export, class: [agent_transcript], when: "resource.scan != 'clean'"}
- {effect: deny, role: "*", action: "*", class: [rater_identity], when: "subject.role != 'vendor_admin'"}
"""Governance primitives (r-ops-gov): ABAC evaluation, rater pseudonyms, retention, deletion propagation."""
from __future__ import annotations
import hmac, hashlib, time
def pseudonym(vendor_worker_id: str, key: bytes, campaign_scope: str = "") -> str:
"""Keyed HMAC: stable inside the platform, not reversible without the key (held in a KMS)."""
msg = f"{campaign_scope}|{vendor_worker_id}".encode()
return "rp_" + hmac.new(key, msg, hashlib.sha256).hexdigest()[:16]
def _eval(expr: str, subject: dict, resource: dict, assignment: dict) -> bool:
# Tiny, closed expression language: python eval with no builtins and only three names in scope.
class NS(dict): __getattr__ = dict.get
env = {"subject": NS(subject), "resource": NS(resource), "assignment": NS(assignment)}
return bool(eval(expr, {"__builtins__": {}}, env))
def decide(policy: dict, subject: dict, action: str, resource: dict, assignment: dict | None = None) -> str:
assignment = assignment or {}
def match(rule):
return ((rule["role"] in ("*", subject["role"])) and rule["action"] in ("*", action)
and resource["class"] in (rule["class"] if isinstance(rule["class"], list) else [rule["class"]])
and _eval(rule.get("when", "True"), subject, resource, assignment))
matched = [r for r in policy["rules"] if match(r)]
if any(r["effect"] == "deny" for r in matched): return "deny"
return "allow" if matched else "deny" # deny by default
def expired(rows: list[dict], classes: dict, now: float) -> list[str]:
out = []
for r in rows:
days = classes[r["class"]].get("retention_days")
if days is not None and now - r["created_at"] > days * 86400:
out.append(r["id"])
return out
def propagate_delete(root_ids: set[str], lineage: dict[str, list[str]]) -> set[str]:
"""lineage: parent id -> derived ids (samples -> items -> labels -> dataset rows -> dataset versions).
Returns every artifact that must be deleted or rebuilt."""
todo, hit = list(root_ids), set(root_ids)
while todo:
for child in lineage.get(todo.pop(), []):
if child not in hit:
hit.add(child); todo.append(child)
return hit
Notes on the design. pseudonym uses HMAC-SHA256 rather than a plain hash, because a plain hash of a short worker ID can be reversed by hashing every possible ID; the optional campaign scope gives a different pseudonym per campaign when a programme wants to prevent linking a rater's behaviour across campaigns. decide evaluates deny rules first and denies by default. The tiny expression evaluator is for teaching; production systems should use a real policy engine with a restricted, non-Turing-complete expression language and policy unit tests, since evaluating policy strings with a general interpreter is itself a security risk. propagate_delete is a breadth-first walk; it returns every descendant so the caller can delete rows and rebuild dataset versions.
import yaml, pathlib
from rdp.gov import pseudonym, decide, expired, propagate_delete
POL = yaml.safe_load(pathlib.Path("rdp/policy.yaml").read_text())
def test_pseudonym_stable_and_scoped():
k = b"k" * 32
assert pseudonym("vendorA:9912", k) == pseudonym("vendorA:9912", k)
assert pseudonym("vendorA:9912", k, "w1") != pseudonym("vendorA:9912", k, "w2")
def test_rater_sees_transcript_only_while_assigned():
s = {"role": "rater", "id": "rp_1"}; res = {"class": "agent_transcript"}
assert decide(POL, s, "read", res, {"active": True, "rater": "rp_1"}) == "allow"
assert decide(POL, s, "read", res, {"active": False, "rater": "rp_1"}) == "deny"
assert decide(POL, s, "read", res, {"active": True, "rater": "rp_2"}) == "deny"
def test_researcher_needs_aggregation_for_rater_behaviour():
s = {"role": "researcher", "project": "rm"}
assert decide(POL, s, "read", {"class": "rater_behaviour", "aggregated": True, "k": 12}) == "allow"
assert decide(POL, s, "read", {"class": "rater_behaviour", "aggregated": False, "k": 1}) == "deny"
def test_unscanned_transcript_cannot_be_exported():
s = {"role": "pipeline"}
assert decide(POL, s, "export", {"class": "agent_transcript", "scan": "pending"}) == "deny"
def test_retention_and_delete_propagation():
now = 400 * 86400
rows = [{"id": "t1", "class": "agent_transcript", "created_at": 0},
{"id": "l1", "class": "feedback_label", "created_at": 0}]
assert expired(rows, POL["data_classes"], now) == ["t1"]
lineage = {"t1": ["item7"], "item7": ["lab1", "lab2"], "lab1": ["ds_w2@v3"], "lab2": ["ds_w2@v3"]}
assert propagate_delete({"t1"}, lineage) == {"t1", "item7", "lab1", "lab2", "ds_w2@v3"}
$ python3 -m pytest -q test_gov.py
..... [100%]
5 passed
Debugging tips. If a rater is denied an item they hold, compare the pseudonym in the lease with the subject ID; a pseudonym computed with a campaign scope will not match one computed without. If retention never expires anything, check that created_at is in seconds and that classes with retention_days: null are intentional. If deletion propagation misses a dataset version, the export step is not writing a lineage edge from label to version; add the edge in the same transaction that writes the manifest.
Controls as objectives. Governance is operated like any other service, with measurable objectives and alerts:
| Control | Indicator | Objective (recommended default) |
|---|---|---|
| Scan before serve | Items served with scan status ≠ clean | 0; page on any |
| Scanner recall | Seeded secrets caught / seeded | ≥ 95% on the weekly seeded set |
| Deletion completion | Deletion requests fully propagated ≤ 30 days / requests | 100% |
| Retention | Objects past retention still stored | 0 after the nightly sweep |
| Access | Grants older than 90 days without renewal | 0 |
| Audit | Sensitive reads without an audit record | 0 |
Table. Governance objectives. The 30-day deletion target is an internal default, not a statement of any legal deadline.
Symptom. On the fourth day of the W2 campaign an expert flags a transcript: a tool output contains what looks like a live cloud access key. By then 640 transcripts have been opened, by 36 of the 40 experts.
Diagnosis. The pre-serve scanner covered common key formats but not the format used by one internal tool whose outputs appear in the agent's sandbox logs. Re-scanning all 2,000 transcripts with the missing pattern added finds 37 transcripts with credential-shaped strings (illustrative numbers); 12 of them have already been opened, by 9 experts, 13 views in total. The audit log gives the exact list of who opened what and when.
Containment and remedy, in order. (1) Stop serving the 37 transcripts immediately by marking their scan status blocked; the access rule denies them everywhere, including the inspector. (2) Notify the owners of the credentials to revoke and rotate them; revocation, not deletion, is what actually removes the risk. (3) Redact the 25 unopened transcripts and return them to the pool. (4) For the 12 opened transcripts, run deletion propagation: 12 transcripts, 13 labels, and the one dataset version already exported (version 1) are found; version 1 is rebuilt without those 13 labels as version 2, and the registry marks version 1 as superseded. (5) Inform the 9 experts through the vendor, under their confidentiality terms, that specific material they viewed contained credentials. (6) Add the missing pattern to the scanner, add generic high-entropy-string detection, and add seeded examples of the new format to the weekly recall test.
Cost. The 13 lost reviews are about 7.6 expert-hours at 35 minutes each, about $910 at $120/h; the rebuild is minutes. The dominant cost is the credential rotation work outside the platform.
Validation. The fix is supported if the weekly seeded-recall test, now including the new format, catches at least 95% and a full re-scan of all active campaigns finds no further unblocked credentials. It is weakened if the high-entropy detector produces so many false positives that experts see many placeholders in legitimate content (for example hashes the agent was supposed to compare), which would reduce label quality; the false-positive rate on a sample of 200 flagged strings is the number to watch.
Runbook: sensitive data exposed in served content.
- Block: set scan status to
blockedfor every matching item; confirm the inspector and exports deny them. - Scope: re-scan all active and recent campaigns with the new pattern; pull the audit log of views for every match.
- Neutralise: if the content is a credential, have it revoked; if personal data of a third party, follow the privacy team's process.
- Propagate: run lineage deletion or redaction for affected items; rebuild and supersede dataset versions; record which trained models used superseded versions.
- Notify: affected owners, the privacy or security function, and, through the vendor, the workers who viewed the material.
- Prevent: add the pattern and seeded examples to the recall test; record the exposure count \(E\) and the time from first view to block.
Cost accounting and unit economics of human data
What it is. Cost accounting for an RL data platform attributes every dollar spent to the campaign that caused it and divides by the units of data that were actually usable. The result, cost per useful unit (per accepted comparison, per reviewed transcript, per rubric), is the number a researcher budgets with and the number that tells the platform team whether an improvement paid off. "Useful" is the important word: a label that QA rejects, an item built on a truncated sample, or an hour a rater spent waiting for the queue to refill are all paid for and all produce nothing.
Why it matters. Human data is usually the largest variable cost in a post-training data budget, and its cost structure is unintuitive. Engineers tend to watch the compute bill because it is the bill they can see in their own dashboards; the people bill arrives through a vendor invoice weeks later. A platform without unit economics will therefore optimise the wrong thing: it will save model tokens and waste rater hours.
The components of the cost of one campaign.
- Productive labour. Paid time on items that end up in the dataset. Priced per hour (W1's vendor raters at $40/h, W2's experts at $120/h) or per task.
- Measurement overhead. Paid time on gold items and on overlap repeats. These are not waste: they are what makes quality measurable (see measuring quality). They should be budgeted deliberately.
- Waste. Paid time on labels that QA rejects, on items built from invalid samples, and idle time when the queue is empty.
- Generation. Model tokens (or GPU time) to produce the samples people judge. Providers discount asynchronous work: Anthropic lists a 50% batch discount and cache reads at a fraction of the base input price (Anthropic pricing); OpenAI's Batch API is also 50% cheaper (OpenAI Batch guide).
- Fees. Vendor or marketplace margins. They can be large and are structured differently by provider; Prolific, for example, publishes a platform fee of 42.857% on top of participant rewards for corporate customers and 33.3% for academic and non-profit customers, and a minimum participant pay of $8.00 per hour (Prolific help centre). Managed vendors usually quote an all-in hourly or per-task rate instead.
- Platform. A share of the platform's fixed costs (engineering, infrastructure), allocated by an agreed rule such as labour hours.
Compare and contrast. Per-hour pricing puts throughput risk on the buyer: slow raters and idle time cost the buyer money. Per-task pricing moves that risk to the vendor, who then has an incentive to go fast, which is the incentive that low-effort detection exists to counter (see pay and incentives). Neither removes the need to measure cost per useful unit; they change which line of the breakdown moves when something goes wrong.
What you would actually do. Record every paid minute against an assignment, a gold item, an overlap repeat or idle time, so the breakdown in the figure can be produced for any campaign at any moment. Report cost per useful unit with its breakdown, not a single total. Treat idle time as a reliability metric owned by the platform. Then use the breakdown to choose where to spend effort: for W1 the levers are QA rejects and idle time, not tokens. This closes the chapter's loop: the architecture, reliability, inspection and governance work in the earlier sections are all justified, or not, by what they do to this number. The next chapter assembles all of it into a minimal runnable platform (see a minimal platform).
The unit-cost equation. For a campaign with work types \(j\) (labelling, double review, rubric writing, grading), let \(n_j\) be units worked, \(\bar t_j\) the mean minutes per unit, and \(w_j\) the hourly rate. Let \(G\) be generation cost, \(I\) idle paid hours at rate \(w_0\), \(P\) the platform allocation and \(U\) the number of useful units. Then
\[ C_u = \frac{\sum_j n_j \bar t_j w_j / 60 \;+\; G \;+\; I w_0 \;+\; P}{U}. \]Two details matter. Cost follows the mean time per unit, not the median: W1's median is 4.0 minutes but its mean is 4.5, and using the median would understate labour by 11%. And \(U\) is counted after quality filtering: \(U = n_{\text{primary}}(1 - r)\) for a reject rate \(r\).
Generation cost. With \(R\) responses of \(\bar x\) input and \(\bar y\) output tokens at prices \(p_x\), \(p_y\) per million tokens, \(G = R(\bar x p_x + \bar y p_y)/10^6\). Batch discounts multiply \(G\) by 0.5 where offered; cached prompt prefixes reduce the input term.
Sensitivities. The derivative of \(C_u\) with respect to the reject rate is \(C_u/(1-r)\) per unit of \(r\): each additional percentage point of rejects raises W1's cost per useful comparison by about 4.5 cents, or about $830 over the campaign at constant useful output. Each idle hour across the pool costs \(N_r w_0 = 150 \times \$40 = \$6{,}000\). By contrast, a 10% change in token count moves \(C_u\) by about 0.2 cents.
| W1 line item | Units | Cost | Share | Lever |
|---|---|---|---|---|
| Accepted comparisons | 18,400 | $55,200 | 72.5% | Guidelines, interface speed |
| Overlap repeats (10% × 2 extra) | 4,000 | $12,000 | 15.8% | Overlap rate; adaptive overlap on hard items |
| QA rejects (8%) | 1,600 | $4,800 | 6.3% | Earlier detection, rater feedback |
| Gold items (5%) | 1,260 | $3,780 | 5.0% | Gold schedule (front-load, then taper) |
| Generation (assumed tokens) | 40,000 responses | $344 | 0.5% | Batch, caching |
| Total | $76,124 | 100% | \(C_u = \$4.14\) |
Table. W1 cost breakdown, illustrative. Labour rows use $3.00 per assignment (4.5 min at $40/h) and sum to the example sheet's $75,780.
Marginal decisions. Overlap is the largest non-productive line. Its value is measurement: agreement on 2,000 items with three raters each is precise to about 0.6 points (see dashboards). Halving overlap to 5% saves $6,000 and roughly multiplies that standard error by \(\sqrt 2\), to about 0.8 points, still enough to detect a 7-point drop; it is a reasonable saving for a campaign whose guidelines are mature, and a bad one for a pilot. For W3 the marginal question is different: rubric writing is a one-off $150,000 (at the assumed rate), but the AI grader is paid every time a rubric is applied. Assuming about 3,000 input and 300 output tokens per grading call at the same $2/$10 prices, a grade costs about $0.009, so one million graded RL rollouts cost about $9,000; over a long RL programme the grader can rival the human cost and belongs in the same ledger.
What you would actually do. Budget campaigns in useful units with an explicit reject-rate assumption, report \(C_u\) with its breakdown, and decide overlap and gold rates as measurement purchases with a stated precision target. Spend engineering on idle time and rejects before tokens.
The build artefact is a cost model that reproduces the reference workloads' figures exactly and can be pointed at live data. A Work is one kind of paid task (units, mean minutes, rate, useful units); a Campaign combines work, generation tokens and prices, idle hours and a platform allocation, and returns totals, a breakdown and cost per useful unit.
"""Unit economics of human data (r-ops-cost). All W-numbers are the book's illustrative workloads.
cost per useful unit = (labour + review + generation + idle + platform) / useful units"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Work:
name: str
units: int # assignments / transcripts / prompts actually worked
minutes_per_unit: float # mean, not median: cost follows the mean
rate_per_h: float # all-in hourly rate paid to the vendor or expert
useful_units: float # units that survive QA and enter the dataset
@dataclass
class Campaign:
name: str
work: list[Work]
gen_in_tokens: float = 0.0 # model tokens spent producing what humans see
gen_out_tokens: float = 0.0
price_in_per_mtok: float = 0.0
price_out_per_mtok: float = 0.0
idle_rater_hours: float = 0.0 # paid time with nothing to do (starved queue, outage)
platform_alloc: float = 0.0 # share of fixed platform cost (assumption, set per org)
def hours(self): return sum(w.units * w.minutes_per_unit / 60 for w in self.work)
def labour(self): return sum(w.units * w.minutes_per_unit / 60 * w.rate_per_h for w in self.work)
def generation(self):
return (self.gen_in_tokens * self.price_in_per_mtok + self.gen_out_tokens * self.price_out_per_mtok) / 1e6
def idle(self): return self.idle_rater_hours * self.work[0].rate_per_h
def total(self): return self.labour() + self.generation() + self.idle() + self.platform_alloc
def per_useful(self, useful): return self.total() / useful
def breakdown(self):
t = self.total()
return {k: round(v / t, 4) for k, v in
{"labour": self.labour(), "generation": self.generation(),
"idle": self.idle(), "platform": self.platform_alloc}.items()}
def w1(idle_rater_hours=0.0, reject_rate=0.08):
useful = 20_000 * (1 - reject_rate)
return Campaign("W1", [Work("label", 25_260, 4.5, 40.0, useful)],
gen_in_tokens=40_000 * 800, gen_out_tokens=40_000 * 700, # ASSUMED 800 in / 700 out per response
price_in_per_mtok=2.0, price_out_per_mtok=10.0, # ASSUMED list price, see text
idle_rater_hours=idle_rater_hours), useful
def w2():
return Campaign("W2", [Work("review", 2_000, 35, 120.0, 2_000),
Work("double_review", 200, 35, 120.0, 0)]), 2_000
def w3(rate=120.0): # W3 expert rate is an ASSUMPTION (= W2's rate)
return Campaign("W3", [Work("rubric", 3_000, 25, rate, 3_000),
Work("grade", 12_000, 2, rate, 12_000)]), 3_000
The tests pin the example-sheet numbers: 1,894.5 rater-hours and $75,780 for W1, $4.12 labour per useful comparison, $344 generation under the stated assumptions, $154,000 and $77 per transcript for W2, and 1,650 hours and $198,000 for W3 at the assumed rate. Two further tests encode the chapter's operating lessons: a 45-minute stall costs more than ten times the generation bill, and raising the reject rate from 8% to 15% moves all-in cost per useful comparison from $4.14 to $4.48.
from rdp.cost import w1, w2, w3
def test_w1_matches_example_sheet():
c, useful = w1()
assert c.hours() == 1_894.5 and round(c.labour()) == 75_780
assert round(c.labour() / useful, 2) == 4.12 # labour-only cost per useful comparison
assert round(c.generation()) == 344 # 32 M in * $2 + 28 M out * $10
assert c.breakdown()["generation"] < 0.005 # generation < 0.5% of spend
def test_w1_outage_idle_costs_more_than_all_generation():
c, useful = w1(idle_rater_hours=112.5) # 150 raters idle for 45 min
assert round(c.idle()) == 4_500 and c.idle() > 10 * c.generation()
def test_w1_reject_rate_sensitivity():
base, u0 = w1(); worse, u1 = w1(reject_rate=0.15)
assert round(base.per_useful(u0), 2) == 4.14 and round(worse.per_useful(u1), 2) == 4.48
def test_w2_and_w3():
c2, n2 = w2(); assert round(c2.labour()) == 154_000 and round(c2.labour() / n2) == 77
c3, n3 = w3(); assert round(c3.hours()) == 1_650 and round(c3.labour()) == 198_000
assert round(c3.labour() / n3) == 66
$ python3 -m pytest -q test_cost.py
.... [100%]
4 passed
Connecting to live data. In production the inputs come from the warehouse: units and mean minutes from submitted assignments grouped by work type, useful_units from quality verdicts, idle hours from the vendor's paid-time feed minus active assignment time, and token counts from the sampler's sample records. Debugging tips. If computed labour disagrees with the vendor invoice by more than a few percent, compare paid time (from the vendor) with active time (from the UI): the gap is breaks, onboarding and idle time, and it belongs in the idle line, not in time per unit. If cost per useful unit jumps at export, check whether the quality filter version changed between the dashboard and the pipeline.
Cost dashboard. Cost is monitored per campaign with four panels and one alert:
panels:
- spend_by_line: labour_productive, overlap, gold, rejects, invalid_sample, idle, generation, fees # stacked by day
- cost_per_useful: spend_to_date / useful_to_date, with the plan line from the campaign spec
- estimate_at_completion: spend_to_date + (target_useful - useful_to_date) * cost_per_useful_last_24h
- idle_share: idle_paid_minutes / paid_minutes # owned by the platform team, SLO <= 1% per day
alerts:
- EACOverBudget: estimate_at_completion > 1.10 * budget for 6h -> ticket to researcher and platform
- IdleShareHigh: idle_share > 0.03 for 1h -> page platform on-call
The estimate at completion (EAC) projects final spend from the cost per useful unit over the last 24 hours, which reacts to a change in reject rate within a day; a projection from the campaign average reacts days later.
Symptom. On the evening of collection day 3 the EAC panel crosses 110% of the $76,124 plan and the alert fires. Three things happened that day: the 45-minute starvation from the reliability incident ($4,500 of idle time), the truncated-sample problem found through the inspection tools (about 1,300 wasted labels, $3,900), and a rise in the QA reject rate on fresh labels from 8% to 15%.
Separating causes. The spend-by-line panel attributes the overrun: idle and invalid-sample lines are one-off and already fixed. The reject line is the one that would keep growing. If 15% rejects persisted for the whole campaign with the one stall, the cost model gives $80,624 for 17,000 useful comparisons, $4.74 each, 15% above plan; reaching the target 18,400 useful comparisons would need about 1,650 more comparisons and roughly $6,240 more labour. Slicing rejects by rater cohort shows that the increase comes almost entirely from a group of 20 raters onboarded on day 2, whose gold accuracy, from a front-loaded gold schedule, is 71% with an interval entirely below 80%.
Remedy. (1) Pause the new cohort's access to W1 and route them to a calibration set with feedback (see running the quality program). (2) Ask the vendor to bill rejected work from the cohort under the contract's quality clause, if there is one. (3) Keep the target at 18,400 useful comparisons and let the stopping rule extend collection by the required amount rather than shipping a smaller dataset silently. (4) Record the day-3 one-off costs against their causes (reliability, sampler configuration) so that the next campaign's plan includes a realistic allowance.
Validation. The remedy is supported if the 24-hour reject rate returns to 8–9% within a day of removing the cohort and the EAC falls back under 105% of plan. It is weakened if rejects stay high with the cohort removed, which would point to a guideline or sample problem affecting everyone.
Chargeback and reporting. Monthly, each research team receives its campaigns' spend by line and cost per useful unit, plus its share of the platform's fixed cost. Two rules keep this honest. Idle time and invalid-sample waste caused by the platform are charged to the platform, not the researcher, so the team that can fix reliability is the team that sees its cost. And measurement overhead (gold and overlap) is shown separately so that researchers can buy more or less of it knowingly.
Runbook: campaign over budget.
- Read the spend-by-line panel; identify which line moved and whether it is one-off (idle, invalid samples) or continuing (rejects, slower time per unit).
- For a continuing line, slice by rater cohort, prompt tag and model reference; find the slice that explains most of the change.
- Decide with the researcher: fix and extend, reduce the target, or stop. Record the decision in the campaign spec so the stopping rule and the EAC follow it.
- Charge one-off platform-caused waste to the platform and open the corresponding reliability or sampler action.
- After the campaign, compare final \(C_u\) with plan and update the planning defaults (reject rate, idle allowance) for the next campaign of the same type.
Building One: The Practitioner's Path
The earlier chapters described each part of an RL data platform on its own: campaign specs (Chapter 3), sample generation (Chapter 4), feedback interfaces (Chapter 5), quality (Chapter 6), the pipeline into training data (Chapter 7) and operations (Chapter 11). This chapter puts the parts together into one small system that runs. It is the hands-on chapter: every component is real code in the book's _code12/ directory, with tests that pass, and the code shown here is pasted from those files without edits.
The chapter follows the order in which a team actually builds such a platform. First comes a minimal end-to-end platform for the W1 pairwise preference campaign: a campaign spec, a sampler that calls a stand-in model, a small HTTP service, a React comparison screen, SQLite storage, gold-based quality control and an export to reward-model training pairs. Second, the platform gains a new feedback type, the W3 rubric data, added end to end so that the cost of extension becomes visible. Third comes the test ladder: unit tests, replay of frozen data, shadow campaigns and staged rollout, each catching a class of failure the lower rungs cannot see. Last is launch: the ordered steps for a first campaign, what on-call means for a data platform, and the incidents to expect in the first days.
The point of building the minimal version first is that the hard problems of this field are not where newcomers expect them. The model call and the web page are easy. The difficult parts are the joins between components: an on-screen choice that must map back to the right model, a retry that must not create a second label, a removed rater whose items must be labelled again, an export that must be byte-identical when re-run. A small platform that gets these joins right is a better foundation than a large one that does not.
The design target for the chapter is the W1 campaign at full size, even though the tests run a scaled-down copy. That fixes the numbers the minimal platform must handle and shows where its simple choices stop being adequate.
W1 needs 20,000 comparisons: 2,000 overlap items × 3 raters plus 18,000 single-labelled items = 24,000 labels. With 5% gold the campaign issues 24,000 / 0.95 ≈ 25,263 assignments (the example sheet rounds this to 25,260). 150 raters working 20 h/week at a mean of 4.5 min per label produce at most 150 / 4.5 ≈ 33 labels per minute, about 0.56 writes per second. On a 2-vCPU test container the chapter's service completed a full "next task + submit label" cycle in 15 ms with 20,000 items loaded (measured; see the Operate level of the next section), about 66 cycles per second, roughly 120 times the W1 peak. A single SQLite file is therefore adequate for one W1-sized campaign on one host.
The design rule that follows is to choose the simplest component that meets the measured load with a large margin, and to write down the threshold at which it must be replaced. SQLite allows only one writer at a time and its write-ahead log does not work over a network filesystem (SQLite documentation), so the replacement point is the first time two hosts must write labels, not a label count. Each later section gives its own numbers: lease length and gold warm-up cost, the sample size a canary needs, and buffer runway during an endpoint outage.
All code lives in the book's companion directory _code12/. The Python side uses only the standard library (WSGI, sqlite3, json) plus pytest for tests; the user interface is TypeScript with React types and is type-checked with tsc. The layout is:
_code12/
w1_campaign.json campaign spec for W1 (full-size numbers)
fbp/spec.py CampaignSpec, validation, cost model
fbp/ftypes.py feedback-type registry + Pairwise
fbp/store.py SQLite schema, migrations, assignment, submission
fbp/sampler.py stub model endpoint, retries, buffer fill
fbp/quality.py gold accuracy, Wilson bounds, removal, agreement
fbp/export.py export to training records + manifest
fbp/service.py HTTP API (stdlib WSGI)
fbp/rubric.py W3 rubric feedback types (added in section 2)
fbp/simulate.py in-process client + simulated raters
fbp/replay.py snapshot, export diff, shadow agreement
fbp/rollout.py staged-rollout assignment and gates
fbp/launch_check.py preflight checks
tests/ test_mvp.py, test_rubric.py, test_ladder.py
ui/src/ types.ts, api.ts, ComparisonTask.tsx, RubricGradeTask.tsx
ui/test/api.test.ts client retry tests (node:test)
demo.py end-to-end run with printed results
To reproduce every result in the chapter, run these from _code12/:
python3 -m pytest # 18 passed
python3 demo.py # preflight, simulated campaign, quality, export
cd ui && npm install @types/react@18 typescript && npx tsc -p . # type-check, exit 0
node --experimental-strip-types --test test/api.test.ts # 2 passed
python3 -m fbp.service --db w1.db --port 8080 # live server
A platform built this way is operable from the first campaign only if its measurements exist from the first campaign. Each section's Operate level therefore names the signals the code already emits and the service-level objectives (SLOs) they support: time to first sample, submit success rate, buffer runway, gold accuracy per rater, agreement on overlap items and export freshness. The launch section turns these into a dashboard, alert rules and a runbook, and works one incident with numbers.
The minimal platform also has known limits that matter in production, stated here so they are not discovered during a campaign. Rater identity is a request header standing in for a real authentication layer. The task query scans unfinished items, so its latency grows with campaign size (measured in the next section). SQLite ties the service to one host. There is no vendor integration, no PII scrubbing and no access control on exports; Chapters 10 and 11 cover those. Each limit has a replacement path, and the sections note the measurement that should trigger it rather than replacing components in advance.
A minimal end-to-end feedback platform you can run
What it is. A minimal feedback platform is the smallest set of components that can take a research request for preference data and return a file a reward-model trainer can consume, with enough quality control that the file can be trusted. It has seven parts, and each has one job.
- Campaign spec. A JSON document that states everything about the campaign: feedback type, guideline version, which two model checkpoints are compared, how many items, how much overlap, how much gold, the quality thresholds, the lease length and the budget. It receives the researcher's request; it produces a validated, versioned contract that every other component reads. Validation rejects unknown fields, impossible values and a budget the estimated cost exceeds.
- Sampler. It receives prompts and the two checkpoints from the spec, calls each model endpoint (retrying transient failures with exponential backoff), and writes one item per prompt: the prompt, both responses, and a random flag that decides which response appears on the left. It produces a pre-generated buffer of items so raters never wait on a model call.
- Store. One SQLite database with five tables: campaigns, items, raters, assignments and labels. It is the only shared state. An assignment is a lease: a record that a given rater holds a given item until a deadline.
- Label API. A small HTTP service with four endpoints: give me my next task, accept my label, show campaign quality, export. It receives requests from the browser and the operator; it produces assignments, stored labels and reports.
- Comparison UI. A React screen showing the prompt and two responses labelled "Response 1" and "Response 2", buttons for which is better and by how much, an optional note, and keyboard shortcuts. The strength scale follows the practice reported for Llama 2, whose annotators marked a preference as significantly better, better, slightly better or negligibly better, and whose reward model used that strength as a margin (Touvron et al., 2023). It measures active time on the task and sends it with the label.
- Quality. Code that scores each rater against gold items, comparisons whose correct answer is known in advance, and decides who is removed. It also measures agreement among raters on overlap items.
- Export. Code that turns accepted labels into reward-model pairs in the
prompt/chosen/rejectedlayout used by common trainers such as Hugging Face TRL's RewardTrainer (Hugging Face TRL documentation), checks each record against a data contract, and writes a manifest with a content hash.
One label, end to end. A rater opens the screen. The browser asks the API for the next task, sending the rater's identity. Inside one database transaction the API expires any leases past their deadline, returns the rater's existing open assignment if there is one (so a page refresh resumes the same task), and otherwise picks an item: a gold item with the spec's gold probability, otherwise the oldest unfinished item this rater has not seen. It inserts an assignment with a deadline and returns only what the screen needs: the prompt and the two responses in their on-screen order. Model names, the gold flag and the left/right mapping never leave the server. The rater reads, chooses, and submits. The browser sends the label with an idempotency key, a random identifier generated once per answer, so that if the network drops after the server saved the label, the retry returns the saved result instead of creating a second label. The server validates the label against the feedback type's rules, stores it and marks the assignment done. Later, quality code compares each rater's gold answers with the known answers; raters who are confidently below the threshold are removed, their labels are excluded, and their items become eligible to be labelled again. Finally, export maps every on-screen choice back to model identity, takes the majority over overlap labels, drops ties and split votes, and writes the pairs.
The W1 spec compares ckpt-current (model a) against ckpt-candidate (model b) on 20,000 items (10,000 coding prompts, two response pairs each) with 10% overlap at 3 raters and 5% gold. Validation computes 24,000 labels and 25,263 assignments; with the gold warm-up described at the Design level, cost is estimated at $79,341 against an $80,000 budget, so the spec passes. Each response pair is turned into an item whose responses are shown with the candidate on the left for roughly half of the items. A rater who clicks "Response 1, clear" on an item where the candidate is on the left has voted for model b. If that item is one of the 2,000 overlap items, two other raters label it too; a 2-to-1 vote for b becomes one exported pair with the candidate's response as chosen and agreement 0.667 in its metadata.
Compared with a hosted tool. Annotation tools such as Label Studio ship a pairwise comparison template (Label Studio templates), which covers the interface and storage. What such a template does not decide is the logic specific to RL data: on-policy sampling from live checkpoints, position randomisation with a reverse mapping, gold warm-up and removal with relabelling, majority aggregation and a training-ready export with provenance. Building the minimal platform makes those decisions explicit; buying a tool still requires making them, in configuration and glue code.
Contrast and cost. The minimal platform trades scale for clarity: one process, one database file, synchronous model calls during buffer fill, and a task query that scans unfinished items. Each of these is adequate for one W1-sized campaign and inadequate for a fleet of concurrent campaigns; the Operate level gives the measurements.
What you would actually do. Build these seven parts first, with the joins (blinding, idempotency, leases, position mapping, relabel on removal, contract-checked export) correct from the start, because each join that is wrong produces data that looks valid. Default to the standard library and SQLite for the first campaign; move to a managed database and a production web framework when a second host must write labels. Deviate only if an existing platform already provides the joins, in which case build the RL-specific logic as a layer on top of it.
The minimal platform has five design parameters that determine its cost and correctness: the gold rate, the gold warm-up, the removal rule, the lease length and the storage choice. Each can be set with a short calculation.
Gold exposure per rater. Let \(L\) be the number of real labels the campaign needs, \(g\) the gold rate (the fraction of assignments that are gold), and \(R\) the number of raters. Real labels per rater are \(L/R\). Because gold assignments are added on top, the gold seen by an average rater is
\[ G_{\text{rater}} = \frac{L}{R}\cdot\frac{g}{1-g}. \]A rater can be judged only after \(m\) gold items (the spec's min_gold_seen). If \(G_{\text{rater}} < m\), most raters are never judged at all.
For W1, \(L = 24{,}000\), \(R = 150\), \(g = 0.05\), so \(L/R = 160\) and \(G_{\text{rater}} = 160 \times 0.05/0.95 \approx 8.4\). With \(m = 10\), the average W1 rater would finish the whole campaign without reaching the minimum. The quality program would be blind exactly when it matters.
Gold warm-up. The remedy is to serve gold at a higher rate \(g_w\) until a rater has seen \(m\) gold items, then drop to \(g\). During warm-up a rater labels \(m(1-g_w)/g_w\) real items. The gold seen per rater becomes
\[ G_{\text{warm}} = m + \Big(\frac{L}{R} - m\frac{1-g_w}{g_w}\Big)\frac{g}{1-g}, \]and the extra assignments for the campaign are \(R\,(G_{\text{warm}} - G_{\text{rater}})\). This is CampaignSpec.warmup_extra_assignments() in the code.
With \(g_w = 0.20\) and \(m = 10\), warm-up covers \(10 \times 0.8/0.2 = 40\) real labels. Then \(G_{\text{warm}} = 10 + (160-40)\times 0.05/0.95 \approx 16.3\). Extra gold is \(150 \times (16.3 - 8.4) \approx 1{,}184\) assignments, or \(1{,}184 \times 4.5/60 \approx 88.8\) rater-hours and \(\approx \$3{,}552\) at $40/h. Total assignments rise from 25,263 to 26,447 and estimated cost from $75,789 to $79,341, about 4.7% more, still inside the $80,000 budget. Every rater is judged after about 50 assignments instead of never.
Removal rule. A point estimate of gold accuracy is noisy at small \(n\). The code uses the 95% Wilson score interval for a binomial proportion and removes a rater only when the interval's upper bound is below the threshold \(a_{\min}\): the platform must be confident the rater is bad. With \(k\) correct of \(n\), \(\hat p = k/n\) and \(z = 1.96\),
\[ \text{upper} = \frac{\hat p + \frac{z^2}{2n} + z\sqrt{\frac{\hat p(1-\hat p)}{n} + \frac{z^2}{4n^2}}}{1 + \frac{z^2}{n}}. \]| Gold correct | Point estimate | Wilson 95% interval | Verdict at \(a_{\min}=0.80\) |
|---|---|---|---|
| 5 / 10 | 0.50 | 0.237 – 0.763 | remove (upper < 0.80) |
| 7 / 10 | 0.70 | 0.397 – 0.892 | keep, keep measuring |
| 11 / 19 | 0.58 | 0.363 – 0.769 | remove |
| 13 / 20 | 0.65 | 0.433 – 0.819 | keep (rule is lenient) |
| 16 / 20 | 0.80 | 0.584 – 0.919 | keep |
The trade-off is explicit: the upper-bound rule rarely removes a good rater, but a mediocre rater at 65% survives until more gold accumulates. A random clicker on balanced gold (50%) is removed at its tenth gold item with probability about 0.62 (5 or fewer correct) and by its twentieth with probability about 0.87 (12 or fewer correct).
Lease length. A lease that is too short expires while a careful rater is still working, the item is issued to someone else, and both labels are paid for. A lease that is too long leaves abandoned items locked, which is harmless early in a campaign but stalls the last few hundred items at the end. The rule of thumb is a lease several times the slow tail of task time. W1's median is 4.0 min and mean 4.5 min; the spec sets 900 s (15 min). Late answers on expired leases are kept rather than discarded, because the work was done and paid for; the cost is occasional over-labelling of an item, which export handles by majority vote.
Storage choice. W1's peak write rate is about 0.56 labels per second (150 raters, one label per 4.5 minutes each). SQLite in write-ahead-log mode lets readers proceed while one writer commits, which fits a single service process; it is not designed for multiple hosts writing over a network filesystem (SQLite documentation).
| Decision | Minimal default | Switch when | Replacement |
|---|---|---|---|
| Database | SQLite, WAL, one file | a second host must write labels | PostgreSQL; same schema, row locks with SKIP LOCKED for assignment |
| Web layer | stdlib WSGI (PEP 3333) | need for auth middleware, OpenAPI docs, async model calls | FastAPI or similar; handlers keep the same bodies (FastAPI testing docs) |
| Generation | pre-generated buffer | multi-turn or on-policy freshness requirements | on-demand generation with a warm pool (Chapter 4) |
| Label payload | JSON column validated per type | analysts need SQL over label fields | typed per-type tables or a columnar export |
| Export grouping | one record per item | several pairs come from the same prompt (rankings, many responses) | keep a prompt id in metadata so the trainer can batch them; InstructGPT treated all comparisons from one prompt as a single batch element to avoid overfitting (Ouyang et al., 2022) |
| Aggregation | majority vote, drop ties | overlap is high and rater reliability varies | Dawid–Skene-style reliability weighting (Dawid and Skene, 1979) |
What you would actually do. Set the gold rate from the per-rater exposure formula rather than habit, add a warm-up whenever \(G_{\text{rater}} < m\), remove on the Wilson upper bound, and set the lease to a few multiples of median task time. Keep SQLite until a second writer host appears.
The code below is the whole minimal platform. It is organised so that everything specific to pairwise comparison lives in one class behind a registry; the store, service and export are generic. That choice pays off in the next section, where a second feedback type is added without touching them.
The campaign spec. The JSON file carries W1's full-size numbers. expected_raters and gold_rate_warmup feed the warm-up cost model.
{
"campaign_id": "w1-coding-pref-v1",
"feedback_type": "pairwise",
"guideline_version": "w1-guide-1.2",
"prompt_source": "prompts/w1_coding.jsonl",
"models": {"a": "ckpt-current", "b": "ckpt-candidate"},
"target_items": 20000,
"overlap_fraction": 0.10,
"overlap_k": 3,
"gold_rate": 0.05,
"gold_accuracy_min": 0.80,
"min_gold_seen": 10,
"min_seconds": 40,
"lease_seconds": 900,
"buffer_target": 2000,
"rate_usd_per_hour": 40,
"est_minutes_per_label": 4.5,
"budget_usd": 80000,
"expected_raters": 150,
"gold_rate_warmup": 0.20
}
load_spec rejects unknown keys, so a typo such as gold_rat fails at load instead of silently taking a default. validate returns a list of errors, which the API returns verbatim with status 422.
"""Campaign spec: the single source of truth a campaign is launched from."""
from __future__ import annotations
import json
from dataclasses import dataclass, fields
@dataclass(frozen=True)
class CampaignSpec:
campaign_id: str
feedback_type: str # key into fbp.ftypes.REGISTRY
guideline_version: str # stamped on every exported record
prompt_source: str
models: dict # {"a": checkpoint, "b": checkpoint}
target_items: int # distinct non-gold items to label
overlap_fraction: float # share of items labelled by several raters
overlap_k: int # raters per overlap item
gold_rate: float # share of assignments that are gold items
gold_accuracy_min: float # removal threshold on gold accuracy
min_gold_seen: int # gold items before a rater can be judged
min_seconds: float # labels faster than this are dropped
lease_seconds: int # an unanswered assignment is reissued after this
buffer_target: int # pre-generated items to keep ready
rate_usd_per_hour: float
est_minutes_per_label: float
budget_usd: float
expected_raters: int = 1
gold_rate_warmup: float = 0.0 # gold share until a rater has seen min_gold_seen gold
def labels_needed(self) -> int:
overlap_items = round(self.target_items * self.overlap_fraction)
return overlap_items * self.overlap_k + (self.target_items - overlap_items)
def assignments_needed(self) -> int:
# gold assignments ride on top of real ones: real = (1 - g) * total
return round(self.labels_needed() / (1 - self.gold_rate))
def warmup_extra_assignments(self) -> int:
"""Extra gold served so every rater reaches min_gold_seen early (store.next_assignment)."""
if self.gold_rate_warmup <= self.gold_rate:
return 0
g, gw = self.gold_rate, self.gold_rate_warmup
real_per_rater = self.labels_needed() / self.expected_raters
warm_real = min(real_per_rater, self.min_gold_seen * (1 - gw) / gw)
gold = self.min_gold_seen + (real_per_rater - warm_real) * g / (1 - g)
return round((gold - real_per_rater * g / (1 - g)) * self.expected_raters)
def est_cost_usd(self) -> float:
n = self.assignments_needed() + self.warmup_extra_assignments()
return round(n * self.est_minutes_per_label / 60 * self.rate_usd_per_hour, 2)
def validate(spec: CampaignSpec, known_types: set[str]) -> list[str]:
"""Return human-readable errors; an empty list means the spec can launch."""
e = []
if spec.feedback_type not in known_types:
e.append(f"unknown feedback_type {spec.feedback_type!r}")
if not 0 <= spec.overlap_fraction <= 1:
e.append("overlap_fraction must be in [0, 1]")
if spec.overlap_fraction > 0 and spec.overlap_k < 2:
e.append("overlap_k must be >= 2 when overlap_fraction > 0")
if not 0 < spec.gold_rate < 0.5 or not 0 <= spec.gold_rate_warmup < 0.5:
e.append("gold_rate and gold_rate_warmup must be below 0.5")
if not 0.5 < spec.gold_accuracy_min <= 1:
e.append("gold_accuracy_min must be in (0.5, 1]")
if spec.target_items <= 0 or spec.lease_seconds <= 0:
e.append("target_items and lease_seconds must be positive")
if set(spec.models) != {"a", "b"} and spec.feedback_type == "pairwise":
e.append("pairwise campaigns need models 'a' and 'b'")
if spec.est_cost_usd() > spec.budget_usd:
e.append(f"estimated cost ${spec.est_cost_usd():,.0f} exceeds "
f"budget ${spec.budget_usd:,.0f}")
return e
def load_spec(path: str) -> CampaignSpec:
raw = json.load(open(path))
unknown = set(raw) - {f.name for f in fields(CampaignSpec)}
if unknown: # typos such as "gold_rat" must fail loudly, not default
raise ValueError(f"unknown spec fields: {sorted(unknown)}")
return CampaignSpec(**raw)
The feedback-type interface. Five methods define a feedback type: render (the only path from a stored item to the browser), validate, is_correct (gold scoring), export and check_record (the data contract). Pairwise.canonical is the reverse mapping from screen position to model identity; it is the single most important function in the platform, because an error there flips labels without producing any error message.
"""Feedback-type registry. The service, store and exporter are generic;
everything specific to one kind of feedback lives behind this interface."""
from __future__ import annotations
from collections import Counter
from typing import Protocol
Row = tuple[dict, list[dict]] # (item payload, accepted label payloads)
class FeedbackType(Protocol):
name: str
schema_version: int
def render(self, item: dict) -> dict: ... # what the UI may see
def validate(self, item: dict, label: dict) -> list[str]: ... # reject bad labels
def is_correct(self, item: dict, gold: object, label: dict) -> bool: ...
def export(self, rows: list[Row], meta: dict) -> list[dict]: ...
def check_record(self, rec: dict) -> list[str]: ... # data contract
REGISTRY: dict[str, FeedbackType] = {}
def register(ft: FeedbackType) -> FeedbackType:
REGISTRY[ft.name] = ft
return ft
class Pairwise:
"""Two responses, shown in random left/right order; label = which is better."""
name, schema_version = "pairwise", 1
STRENGTHS = ("negligible", "slight", "clear", "significant")
def render(self, item):
a, b = item["response_a"], item["response_b"]
left, right = (a, b) if item["left_is_a"] else (b, a)
return {"prompt": item["prompt"], "left": left, "right": right} # no model names
def validate(self, item, label):
errs = []
if label.get("choice") not in ("left", "right", "tie"):
errs.append("choice must be left, right or tie")
if label.get("choice") != "tie" and label.get("strength") not in self.STRENGTHS:
errs.append(f"strength must be one of {self.STRENGTHS}")
if len(label.get("note", "")) > 2000:
errs.append("note longer than 2000 characters")
return errs
@staticmethod
def canonical(item: dict, label: dict) -> str:
"""Map the on-screen choice back to model identity: 'a', 'b' or 'tie'."""
c = label["choice"]
if c == "tie":
return "tie"
return ("a" if c == "left" else "b") if item["left_is_a"] else ("b" if c == "left" else "a")
def is_correct(self, item, gold, label):
return self.canonical(item, label) == gold
def export(self, rows, meta):
out = []
for item, labels in rows:
votes = Counter(self.canonical(item, l) for l in labels)
if not votes:
continue
(top, n), = votes.most_common(1)
if top == "tie" or list(votes.values()).count(n) > 1:
continue # ties and split votes carry no pair
chosen, rejected = ("response_a", "response_b") if top == "a" else ("response_b", "response_a")
out.append({"prompt": item["prompt"], "chosen": item[chosen], "rejected": item[rejected],
"meta": {**meta, "item_id": item["item_id"], "n_labels": len(labels),
"agreement": round(n / len(labels), 3),
"chosen_model": item["models"][top]}})
return out
def check_record(self, rec):
errs = [f"missing {k}" for k in ("prompt", "chosen", "rejected", "meta") if not rec.get(k)]
if not errs and rec["chosen"] == rec["rejected"]:
errs.append("chosen == rejected")
if not errs and not {"campaign_id", "guideline_version", "item_id"} <= rec["meta"].keys():
errs.append("meta lacks provenance keys")
return errs
register(Pairwise())
Storage, assignment and submission. Migrations are numbered and recorded in schema_migrations, so the same code can open an old or new database. next_assignment runs in a BEGIN IMMEDIATE transaction, which takes SQLite's write lock up front so two concurrent requests cannot lease the same last slot. The UNIQUE(item_id, rater_id) constraint guarantees a rater never sees an item twice, and the active-rater join in the capacity check means a removed rater's work is redone. submit_label is idempotent on the client's key: the same key for the same assignment returns the stored label; the same key for a different assignment is a conflict.
"""SQLite storage: schema, migrations, task assignment and label submission."""
from __future__ import annotations
import json, random, sqlite3, uuid
MIGRATIONS = {
1: """
CREATE TABLE campaigns(campaign_id TEXT PRIMARY KEY, spec_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'draft' CHECK(status IN ('draft','live','paused','closed')));
CREATE TABLE items(item_id TEXT PRIMARY KEY, campaign_id TEXT NOT NULL REFERENCES campaigns,
payload_json TEXT NOT NULL, is_gold INTEGER NOT NULL DEFAULT 0, gold_json TEXT,
target_labels INTEGER NOT NULL DEFAULT 1, created_at REAL NOT NULL);
CREATE TABLE raters(rater_id TEXT PRIMARY KEY,
status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active','removed')));
CREATE TABLE assignments(assignment_id TEXT PRIMARY KEY, item_id TEXT NOT NULL REFERENCES items,
campaign_id TEXT NOT NULL, rater_id TEXT NOT NULL, issued_at REAL NOT NULL,
lease_expires REAL NOT NULL,
status TEXT NOT NULL CHECK(status IN ('open','done','expired')),
UNIQUE(item_id, rater_id)); -- a rater never sees an item twice
CREATE TABLE labels(label_id TEXT PRIMARY KEY,
assignment_id TEXT NOT NULL UNIQUE REFERENCES assignments,
item_id TEXT NOT NULL, campaign_id TEXT NOT NULL, rater_id TEXT NOT NULL,
feedback_type TEXT NOT NULL, schema_version INTEGER NOT NULL,
payload_json TEXT NOT NULL, seconds REAL NOT NULL, submitted_at REAL NOT NULL,
idempotency_key TEXT NOT NULL UNIQUE);
CREATE INDEX ix_items_campaign ON items(campaign_id, is_gold);
CREATE INDEX ix_assign_item ON assignments(item_id, status);
CREATE INDEX ix_assign_rater ON assignments(rater_id, campaign_id, status);
CREATE INDEX ix_labels_item ON labels(item_id);
""",
}
class Conflict(Exception): ...
class Invalid(Exception): ...
def connect(path: str) -> sqlite3.Connection:
conn = sqlite3.connect(path, isolation_level=None, check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL") # readers do not block the single writer
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("PRAGMA busy_timeout=5000")
migrate(conn)
return conn
def migrate(conn: sqlite3.Connection) -> int:
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations(version INTEGER PRIMARY KEY)")
done = {r[0] for r in conn.execute("SELECT version FROM schema_migrations")}
for v in sorted(MIGRATIONS):
if v not in done:
conn.execute("BEGIN IMMEDIATE")
for stmt in filter(str.strip, MIGRATIONS[v].split(";")):
conn.execute(stmt)
conn.execute("INSERT INTO schema_migrations VALUES (?)", (v,))
conn.execute("COMMIT")
return max(MIGRATIONS)
def create_campaign(conn, spec_dict: dict) -> None:
conn.execute("INSERT INTO campaigns(campaign_id, spec_json) VALUES (?,?)",
(spec_dict["campaign_id"], json.dumps(spec_dict)))
def spec_of(conn, campaign_id: str) -> dict:
row = conn.execute("SELECT spec_json FROM campaigns WHERE campaign_id=?", (campaign_id,)).fetchone()
if row is None:
raise Invalid(f"no campaign {campaign_id}")
return json.loads(row[0])
def add_item(conn, campaign_id, payload, now, target_labels=1, gold=None) -> str:
item_id = payload.get("item_id") or f"it-{uuid.uuid4().hex[:12]}"
payload = {**payload, "item_id": item_id}
conn.execute("INSERT INTO items VALUES (?,?,?,?,?,?,?)",
(item_id, campaign_id, json.dumps(payload), int(gold is not None),
json.dumps(gold) if gold is not None else None, target_labels, now))
return item_id
def next_assignment(conn, campaign_id, rater_id, now, rng: random.Random):
"""Lease one item to a rater, or return None when nothing is available."""
spec = spec_of(conn, campaign_id)
conn.execute("BEGIN IMMEDIATE") # serialise writers: no double issue
try:
conn.execute("INSERT OR IGNORE INTO raters(rater_id) VALUES (?)", (rater_id,))
if conn.execute("SELECT status FROM raters WHERE rater_id=?", (rater_id,)).fetchone()[0] != "active":
conn.execute("COMMIT"); return None
conn.execute("UPDATE assignments SET status='expired' WHERE status='open' AND lease_expires<?", (now,))
row = conn.execute("""SELECT a.assignment_id, i.payload_json FROM assignments a JOIN items i USING(item_id)
WHERE a.rater_id=? AND a.campaign_id=? AND a.status='open'""",
(rater_id, campaign_id)).fetchone()
if row: # page refresh: resume the same task
conn.execute("COMMIT"); return row[0], json.loads(row[1])
unseen = "NOT EXISTS (SELECT 1 FROM assignments x WHERE x.item_id=i.item_id AND x.rater_id=:r)"
pick = None
seen_gold = conn.execute("""SELECT count(*) FROM assignments a JOIN items i USING(item_id)
WHERE a.rater_id=? AND a.campaign_id=? AND i.is_gold=1""",
(rater_id, campaign_id)).fetchone()[0]
rate = spec["gold_rate"]
if seen_gold < spec["min_gold_seen"]: # warm-up: judge new raters early
rate = max(rate, spec.get("gold_rate_warmup", 0.0))
if rng.random() < rate:
golds = conn.execute(f"""SELECT item_id, payload_json FROM items i WHERE campaign_id=:c AND is_gold=1
AND {unseen} ORDER BY item_id""", {"c": campaign_id, "r": rater_id}).fetchall()
pick = rng.choice(golds) if golds else None # unpredictable position in the queue
if pick is None: # unfinished items first, oldest first
pick = conn.execute(f"""
SELECT item_id, payload_json FROM items i WHERE campaign_id=:c AND is_gold=0 AND {unseen}
AND (SELECT count(*) FROM assignments y JOIN raters ry USING(rater_id)
WHERE y.item_id=i.item_id AND y.status IN ('open','done')
AND ry.status='active') < i.target_labels -- removed raters' work is redone
ORDER BY (SELECT count(*) FROM labels l WHERE l.item_id=i.item_id) DESC, created_at
LIMIT 1""", {"c": campaign_id, "r": rater_id}).fetchone()
if pick is None:
conn.execute("COMMIT"); return None
aid = f"as-{uuid.uuid4().hex[:12]}"
conn.execute("INSERT INTO assignments VALUES (?,?,?,?,?,?, 'open')",
(aid, pick[0], campaign_id, rater_id, now, now + spec["lease_seconds"]))
conn.execute("COMMIT")
return aid, json.loads(pick[1])
except Exception:
conn.execute("ROLLBACK"); raise
def submit_label(conn, ftype, assignment_id, rater_id, payload, seconds, idem_key, now) -> tuple[str, bool]:
"""Store one label. Returns (label_id, replayed). Safe to retry with the same key."""
prev = conn.execute("SELECT label_id, assignment_id FROM labels WHERE idempotency_key=?", (idem_key,)).fetchone()
if prev:
if prev[1] != assignment_id:
raise Conflict("idempotency key reused for a different assignment")
return prev[0], True
a = conn.execute("""SELECT a.*, i.payload_json FROM assignments a JOIN items i USING(item_id)
WHERE assignment_id=?""", (assignment_id,)).fetchone()
if a is None or a["rater_id"] != rater_id:
raise Conflict("assignment not found for this rater")
if a["status"] == "done":
raise Conflict("assignment already answered")
errs = ftype.validate(json.loads(a["payload_json"]), payload)
if errs:
raise Invalid("; ".join(errs))
lid = f"lb-{uuid.uuid4().hex[:12]}"
conn.execute("BEGIN IMMEDIATE")
try: # a late answer on an expired lease is kept: the work was done and paid for
conn.execute("INSERT INTO labels VALUES (?,?,?,?,?,?,?,?,?,?,?)",
(lid, assignment_id, a["item_id"], a["campaign_id"], rater_id, ftype.name,
ftype.schema_version, json.dumps(payload), seconds, now, idem_key))
conn.execute("UPDATE assignments SET status='done' WHERE assignment_id=?", (assignment_id,))
conn.execute("COMMIT")
except sqlite3.IntegrityError:
conn.execute("ROLLBACK")
raise Conflict("duplicate submission")
return lid, False
Sampler. StubModel stands in for a live endpoint and can inject failures. Its text contains only a hash, no checkpoint name: an earlier version printed the checkpoint name inside the response, and the blinding test below failed on it, which is the same failure a real model produces when it states its own name. Overlap membership is a hash of the prompt id, so it does not depend on fill order.
"""Sampler: turns prompts into labelable items by calling model endpoints."""
from __future__ import annotations
import hashlib, random, time
from fbp import store
class EndpointError(Exception): ...
class StubModel:
"""Stands in for a live inference endpoint. Deterministic text; optional failures."""
def __init__(self, checkpoint: str, fail_rate: float = 0.0, seed: int = 0):
self.checkpoint, self.fail_rate, self.rng = checkpoint, fail_rate, random.Random(seed)
self.calls = 0
def generate(self, prompt: str) -> str:
self.calls += 1
if self.rng.random() < self.fail_rate:
raise EndpointError(f"{self.checkpoint}: 503")
h = hashlib.sha256(f"{self.checkpoint}|{prompt}".encode()).hexdigest()[:8]
return f"def solve(): # variant {h}\n ..."
def call_with_retry(model: StubModel, prompt: str, tries: int = 3, sleep=time.sleep) -> str:
for k in range(tries):
try:
return model.generate(prompt)
except EndpointError:
if k == tries - 1:
raise
sleep(0.05 * 2 ** k) # exponential backoff between attempts
def fill_buffer(conn, spec: dict, prompts: list[dict], models: dict[str, StubModel],
n: int, now: float, seed: int = 0, sleep=time.sleep) -> dict:
"""Pre-generate up to n new items. Returns counts for the dashboard."""
rng = random.Random(seed)
have = {r[0] for r in conn.execute(
"SELECT json_extract(payload_json,'$.prompt_id') FROM items WHERE campaign_id=?", (spec["campaign_id"],))}
made = failed = 0
for p in prompts:
if made >= n:
break
if p["prompt_id"] in have:
continue
try:
ra = call_with_retry(models["a"], p["text"], sleep=sleep)
rb = call_with_retry(models["b"], p["text"], sleep=sleep)
except EndpointError:
failed += 1 # skip the prompt; it stays eligible next fill
continue
if ra == rb:
continue # identical responses carry no preference signal
# overlap membership is a stable function of the prompt id, not of fill order
bucket = int(hashlib.sha256(p["prompt_id"].encode()).hexdigest(), 16) % 1000
k = spec["overlap_k"] if bucket < spec["overlap_fraction"] * 1000 else 1
store.add_item(conn, spec["campaign_id"], {
"item_id": f"{spec['campaign_id']}:{p['prompt_id']}", "prompt_id": p["prompt_id"],
"prompt": p["text"], "response_a": ra, "response_b": rb,
"models": {"a": models["a"].checkpoint, "b": models["b"].checkpoint},
"left_is_a": rng.random() < 0.5, # randomise screen position per item
}, now, target_labels=k)
made += 1
return {"made": made, "failed": failed}
Quality. rater_report scores gold through the feedback type's own is_correct, so it works for any type. Verdicts are evaluated in order: not enough gold, confidently below the bar, too fast, otherwise acceptable.
"""Gold-based rater quality, overlap agreement and removal."""
from __future__ import annotations
import json, math, statistics
from itertools import combinations
from fbp.ftypes import REGISTRY
def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
"""95% Wilson score interval for a binomial proportion k/n."""
if n == 0:
return 0.0, 1.0
p = k / n
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return centre - half, centre + half
def rater_report(conn, campaign_id: str) -> dict[str, dict]:
spec = json.loads(conn.execute("SELECT spec_json FROM campaigns WHERE campaign_id=?",
(campaign_id,)).fetchone()[0])
ft = REGISTRY[spec["feedback_type"]]
rows = conn.execute("""SELECT l.rater_id, l.payload_json, l.seconds, i.payload_json AS item,
i.is_gold, i.gold_json FROM labels l JOIN items i USING(item_id)
WHERE l.campaign_id=?""", (campaign_id,)).fetchall()
by: dict[str, dict] = {}
for r in rows:
s = by.setdefault(r["rater_id"], {"labels": 0, "gold_seen": 0, "gold_correct": 0, "secs": []})
s["labels"] += 1
s["secs"].append(r["seconds"])
if r["is_gold"]:
s["gold_seen"] += 1
s["gold_correct"] += ft.is_correct(json.loads(r["item"]), json.loads(r["gold_json"]),
json.loads(r["payload_json"]))
for rid, s in by.items():
lo, hi = wilson(s["gold_correct"], s["gold_seen"])
s["gold_acc"] = round(s["gold_correct"] / s["gold_seen"], 3) if s["gold_seen"] else None
s["gold_ci"] = (round(lo, 3), round(hi, 3))
s["median_seconds"] = statistics.median(s.pop("secs"))
if s["gold_seen"] < spec["min_gold_seen"]:
s["verdict"] = "insufficient_gold"
elif hi < spec["gold_accuracy_min"]: # confidently below the bar
s["verdict"] = "remove"
elif s["median_seconds"] < spec["min_seconds"]:
s["verdict"] = "low_effort"
else:
s["verdict"] = "ok"
return by
def apply_removals(conn, report: dict[str, dict]) -> list[str]:
"""Remove raters judged 'remove' or 'low_effort'; export then drops all their labels."""
gone = [r for r, s in report.items() if s["verdict"] in ("remove", "low_effort")]
conn.executemany("UPDATE raters SET status='removed' WHERE rater_id=?", [(r,) for r in gone])
return gone
def pairwise_agreement(conn, campaign_id: str) -> float | None:
"""Share of rater pairs on overlap items whose canonical choices match."""
ft = REGISTRY["pairwise"]
items: dict[str, tuple[dict, list[str]]] = {}
for r in conn.execute("""SELECT l.item_id, l.payload_json, i.payload_json FROM labels l
JOIN items i USING(item_id) JOIN raters USING(rater_id)
WHERE l.campaign_id=? AND i.is_gold=0 AND raters.status='active'""",
(campaign_id,)):
item = json.loads(r[2])
items.setdefault(r[0], (item, []))[1].append(ft.canonical(item, json.loads(r[1])))
pairs = agree = 0
for _, votes in items.values():
for x, y in combinations(votes, 2):
pairs += 1
agree += x == y
return round(agree / pairs, 3) if pairs else None
Export. Records are sorted by their serialised form so the same labels always produce the same bytes and therefore the same SHA-256; the replay test in section 3 depends on this. Any contract violation aborts the export: a partially valid file is never written.
"""Generic export: accepted labels -> training records + a manifest."""
from __future__ import annotations
import hashlib, json
from fbp.ftypes import REGISTRY
CODE_VERSION = "fbp-0.3.0"
class ContractError(Exception): ...
def accepted_rows(conn, campaign_id: str, min_seconds: float):
"""Non-gold items with labels from active raters that pass the effort floor."""
rows: dict[str, tuple[dict, list[dict]]] = {}
dropped = {"removed_rater": 0, "too_fast": 0}
q = conn.execute("""SELECT i.item_id, i.payload_json AS item, l.payload_json AS label, l.seconds,
r.status FROM items i JOIN labels l USING(item_id) JOIN raters r USING(rater_id)
WHERE i.campaign_id=? AND i.is_gold=0 ORDER BY i.item_id, l.label_id""", (campaign_id,))
for r in q:
if r["status"] != "active":
dropped["removed_rater"] += 1; continue
if r["seconds"] < min_seconds:
dropped["too_fast"] += 1; continue
rows.setdefault(r["item_id"], (json.loads(r["item"]), []))[1].append(json.loads(r["label"]))
return list(rows.values()), dropped
def export_campaign(conn, campaign_id: str, out_path: str | None = None) -> tuple[list[dict], dict]:
spec = json.loads(conn.execute("SELECT spec_json FROM campaigns WHERE campaign_id=?",
(campaign_id,)).fetchone()[0])
ft = REGISTRY[spec["feedback_type"]]
rows, dropped = accepted_rows(conn, campaign_id, spec["min_seconds"])
meta = {"campaign_id": campaign_id, "guideline_version": spec["guideline_version"],
"feedback_type": ft.name, "schema_version": ft.schema_version, "code_version": CODE_VERSION}
records = sorted(ft.export(rows, meta), key=lambda r: json.dumps(r, sort_keys=True))
bad = [(i, e) for i, rec in enumerate(records) for e in ft.check_record(rec)]
if bad: # never ship a partially valid file
raise ContractError(f"{len(bad)} contract violations, first: {bad[0]}")
body = "".join(json.dumps(r, sort_keys=True) + "\n" for r in records)
manifest = {**meta, "n_records": len(records), "n_items_labelled": len(rows),
"dropped_labels": dropped, "sha256": hashlib.sha256(body.encode()).hexdigest()}
if out_path:
open(out_path, "w").write(body)
open(out_path + ".manifest.json", "w").write(json.dumps(manifest, indent=2))
return records, manifest
The HTTP service. Routes map to handlers that return (status, body); domain errors become 409 (conflict) or 422 (invalid). The import fbp.rubric line is the one change section 2 makes to this file. X-Rater-Id stands in for an authenticated identity and must be replaced by the real auth layer before any external rater uses the service.
"""HTTP API (stdlib WSGI). Run: python -m fbp.service --db w1.db --port 8080"""
from __future__ import annotations
import json, random, re, time
from fbp import store, quality, export
import fbp.rubric # noqa: F401 (W3: registers rubric types and migration 2)
from fbp.ftypes import REGISTRY
from fbp.spec import CampaignSpec, validate
class App:
def __init__(self, db_path: str, clock=time.time, seed: int | None = None):
self.conn, self.clock, self.rng = store.connect(db_path), clock, random.Random(seed)
self.routes = [
("GET", r"/healthz$", self.health),
("POST", r"/api/campaigns$", self.create_campaign),
("GET", r"/api/campaigns/([\w.:-]+)/next$", self.next_task),
("POST", r"/api/labels$", self.post_label),
("GET", r"/api/campaigns/([\w.:-]+)/quality$", self.quality),
("GET", r"/api/campaigns/([\w.:-]+)/export$", self.export),
]
def __call__(self, environ, start_response):
method, path = environ["REQUEST_METHOD"], environ.get("PATH_INFO", "/")
for m, pattern, handler in self.routes:
match = re.match(pattern, path)
if match and m == method:
try:
status, body = handler(environ, *match.groups())
except store.Invalid as e:
status, body = 422, {"error": str(e)}
except store.Conflict as e:
status, body = 409, {"error": str(e)}
break
else:
status, body = 404, {"error": "not found"}
data = b"" if body is None else json.dumps(body).encode()
reason = {200: "OK", 201: "Created", 204: "No Content", 404: "Not Found",
409: "Conflict", 422: "Unprocessable Entity", 401: "Unauthorized"}[status]
start_response(f"{status} {reason}", [("Content-Type", "application/json"),
("Content-Length", str(len(data)))])
return [data]
# In production the rater identity comes from the auth layer (SSO / vendor token),
# never from a value the browser chooses. X-Rater-Id stands in for it here.
@staticmethod
def rater(environ) -> str:
r = environ.get("HTTP_X_RATER_ID", "")
if not re.fullmatch(r"[\w.-]{1,64}", r):
raise store.Invalid("missing or malformed rater identity")
return r
@staticmethod
def body(environ) -> dict:
n = int(environ.get("CONTENT_LENGTH") or 0)
try:
return json.loads(environ["wsgi.input"].read(n) or b"{}")
except json.JSONDecodeError:
raise store.Invalid("body is not JSON")
def health(self, environ):
self.conn.execute("SELECT 1")
return 200, {"ok": True}
def create_campaign(self, environ):
raw = self.body(environ)
try:
spec = CampaignSpec(**raw)
except TypeError as e:
raise store.Invalid(str(e))
errs = validate(spec, set(REGISTRY))
if errs:
raise store.Invalid("; ".join(errs))
store.create_campaign(self.conn, raw)
return 201, {"campaign_id": spec.campaign_id, "assignments_needed": spec.assignments_needed(),
"est_cost_usd": spec.est_cost_usd()}
def next_task(self, environ, cid):
got = store.next_assignment(self.conn, cid, self.rater(environ), self.clock(), self.rng)
if got is None:
return 204, None
aid, item = got
ft = REGISTRY[store.spec_of(self.conn, cid)["feedback_type"]]
# render() is the only path from stored item to browser: no gold flag, no model names
return 200, {"assignment_id": aid, "feedback_type": ft.name, "item": ft.render(item)}
def post_label(self, environ):
b, rid = self.body(environ), self.rater(environ)
key = environ.get("HTTP_IDEMPOTENCY_KEY")
if not key:
raise store.Invalid("Idempotency-Key header required")
row = self.conn.execute("SELECT campaign_id FROM assignments WHERE assignment_id=?",
(b.get("assignment_id"),)).fetchone()
if row is None:
raise store.Conflict("unknown assignment")
ft = REGISTRY[store.spec_of(self.conn, row[0])["feedback_type"]]
seconds = float(b.get("seconds", -1))
if not 0 <= seconds <= 4 * 3600:
raise store.Invalid("seconds out of range")
lid, replayed = store.submit_label(self.conn, ft, b["assignment_id"], rid, b.get("payload", {}),
seconds, key, self.clock())
return (200 if replayed else 201), {"label_id": lid, "replayed": replayed}
def quality(self, environ, cid):
rep = quality.rater_report(self.conn, cid)
agree = (quality.pairwise_agreement(self.conn, cid)
if store.spec_of(self.conn, cid)["feedback_type"] == "pairwise" else None)
return 200, {"raters": rep, "pairwise_agreement": agree}
def export(self, environ, cid):
records, manifest = export.export_campaign(self.conn, cid)
return 200, {"manifest": manifest, "records": records}
if __name__ == "__main__":
import argparse
from wsgiref.simple_server import make_server
ap = argparse.ArgumentParser()
ap.add_argument("--db", default="fbp.db"); ap.add_argument("--port", type=int, default=8080)
a = ap.parse_args()
print(f"serving on :{a.port}")
make_server("127.0.0.1", a.port, App(a.db)).serve_forever()
The comparison UI. Three files: wire types, an API client and the component. The client retries network errors and 5xx responses with the same idempotency key and treats any 4xx as final, in the manner of payment APIs that save the first response for a key and return it on retries (Stripe API reference). The component counts only visible-tab time, keeps the answer on screen if saving fails, and never shows model names.
// Wire types shared by every task component. They mirror fbp/service.py.
export type Choice = "left" | "right" | "tie";
export type Strength = "negligible" | "slight" | "clear" | "significant";
export interface PairwiseView { prompt: string; left: string; right: string }
export interface PairwiseLabel { choice: Choice; strength?: Strength; note?: string }
export interface Task<V = unknown> {
assignment_id: string;
feedback_type: string;
item: V;
}
export interface SubmitResult { label_id: string; replayed: boolean }
import type { Task, SubmitResult } from "./types";
// The rater header stands in for the session cookie / token of a real auth layer.
const headers = (raterId: string) => ({ "Content-Type": "application/json", "X-Rater-Id": raterId });
export async function fetchNext<V>(campaignId: string, raterId: string): Promise<Task<V> | null> {
const r = await fetch(`/api/campaigns/${campaignId}/next`, { headers: headers(raterId) });
if (r.status === 204) return null; // queue empty for this rater
if (!r.ok) throw new Error(`next: ${r.status}`);
return r.json();
}
// Retries reuse the SAME idempotency key, so a timeout after the server committed
// cannot create a second label. 4xx answers are final and shown to the rater.
export async function submitLabel(
raterId: string, assignmentId: string, payload: unknown, seconds: number,
idempotencyKey: string, tries = 4,
): Promise<SubmitResult> {
for (let k = 0; k < tries; k++) {
let r: Response | null = null;
try {
r = await fetch("/api/labels", {
method: "POST",
headers: { ...headers(raterId), "Idempotency-Key": idempotencyKey },
body: JSON.stringify({ assignment_id: assignmentId, payload, seconds }),
});
} catch { /* network error: fall through and retry */ }
if (r?.ok) return r.json();
if (r && r.status < 500) throw new Error((await r.json()).error);
await new Promise((res) => setTimeout(res, 250 * 2 ** k)); // 250, 500, 1000, 2000 ms
}
throw new Error("Could not save after retries. Your answer is kept on this page.");
}
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { fetchNext, submitLabel } from "./api";
import type { Choice, PairwiseLabel, PairwiseView, Strength, Task } from "./types";
const STRENGTHS: Strength[] = ["negligible", "slight", "clear", "significant"];
// Counts only time the tab is visible, so a task left open over lunch
// does not look like 40 minutes of careful work.
function useActiveSeconds(resetKey: string | undefined): () => number {
const acc = useRef(0), since = useRef<number | null>(null);
useEffect(() => {
acc.current = 0;
since.current = document.hidden ? null : performance.now();
const onVis = () => {
if (document.hidden && since.current !== null) {
acc.current += performance.now() - since.current; since.current = null;
} else if (!document.hidden) since.current = performance.now();
};
document.addEventListener("visibilitychange", onVis);
return () => document.removeEventListener("visibilitychange", onVis);
}, [resetKey]);
return () => (acc.current + (since.current === null ? 0 : performance.now() - since.current)) / 1000;
}
export function ComparisonTask({ campaignId, raterId }: { campaignId: string; raterId: string }) {
const [task, setTask] = useState<Task<PairwiseView> | null | undefined>(undefined);
const [choice, setChoice] = useState<Choice | null>(null);
const [strength, setStrength] = useState<Strength | null>(null);
const [note, setNote] = useState("");
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const activeSeconds = useActiveSeconds(task?.assignment_id);
// one key per assignment: every retry of this answer carries the same key
const idemKey = useMemo(() => crypto.randomUUID(), [task?.assignment_id]);
const load = useCallback(async () => {
setChoice(null); setStrength(null); setNote(""); setError(null);
try { setTask(await fetchNext<PairwiseView>(campaignId, raterId)); }
catch (e) { setError(String(e)); }
}, [campaignId, raterId]);
useEffect(() => { void load(); }, [load]);
const ready = choice !== null && (choice === "tie" || strength !== null) && !saving;
const submit = useCallback(async () => {
if (!task || !ready) return;
const label: PairwiseLabel = { choice: choice!, ...(choice !== "tie" && { strength: strength! }),
...(note && { note }) };
setSaving(true);
try {
await submitLabel(raterId, task.assignment_id, label, activeSeconds(), idemKey);
await load();
} catch (e) { setError((e as Error).message); } // answer stays on screen
finally { setSaving(false); }
}, [task, ready, choice, strength, note, raterId, idemKey, activeSeconds, load]);
useEffect(() => { // 1 = left, 2 = tie, 3 = right
const onKey = (ev: KeyboardEvent) => {
if ((ev.target as HTMLElement).tagName === "TEXTAREA") return;
const map: Record<string, Choice> = { "1": "left", "2": "tie", "3": "right" };
if (map[ev.key]) setChoice(map[ev.key]);
if (ev.key === "Enter") void submit();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [submit]);
if (task === undefined) return <p>Loading…</p>;
if (task === null) return <p>No tasks available. Check back later.</p>;
const { prompt, left, right } = task.item;
return (
<main className="cmp">
<section className="prompt"><h2>Prompt</h2><pre>{prompt}</pre></section>
<div className="pair">
{/* neutral names: "Response 1/2", never model or checkpoint names */}
<article><h3>Response 1</h3><pre>{left}</pre></article>
<article><h3>Response 2</h3><pre>{right}</pre></article>
</div>
<fieldset>
<legend>Which response is better?</legend>
{(["left", "tie", "right"] as Choice[]).map((c, i) => (
<button key={c} aria-pressed={choice === c} onClick={() => setChoice(c)}>
{i + 1} · {c === "left" ? "Response 1" : c === "right" ? "Response 2" : "About the same"}
</button>
))}
</fieldset>
{choice && choice !== "tie" && (
<fieldset>
<legend>By how much?</legend>
{STRENGTHS.map((s) => (
<button key={s} aria-pressed={strength === s} onClick={() => setStrength(s)}>{s}</button>
))}
</fieldset>
)}
<textarea placeholder="Optional: what decided it?" maxLength={2000}
value={note} onChange={(e) => setNote(e.target.value)} />
{error && <p role="alert">{error}</p>}
<button disabled={!ready} onClick={() => void submit()}>{saving ? "Saving…" : "Submit (Enter)"}</button>
</main>
);
}
Tests. The helper builds a 300-item W1-shaped campaign through the real API with 40 gold items. The small run raises the gold rate to 0.30 so each simulated rater sees at least 10 gold items; the full-size spec keeps 0.05 with warm-up.
"""Builds a small W1-shaped campaign through the real API for tests."""
from __future__ import annotations
import json, os
from fbp import sampler, store
from fbp.service import App
from fbp.simulate import call
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def w1_small(**over) -> dict:
spec = json.load(open(os.path.join(HERE, "w1_campaign.json")))
# small run: more gold per assignment so each rater sees >= 10 gold items
spec.update(campaign_id="w1-test", target_items=300, gold_rate=0.30, budget_usd=2000)
spec.update(over)
return spec
def candidate_wins(prompt_id: str) -> str:
"""Simulated truth: the candidate checkpoint (b) is better on 2 of 3 prompts."""
return "a" if int(prompt_id.split("-")[1]) % 3 == 0 else "b"
def build(tmp_path, n_gold: int = 40, **over):
clock = [1_000_000.0]
app = App(str(tmp_path / "fbp.db"), clock=lambda: clock[0], seed=7)
spec = w1_small(**over)
st, body = call(app, "POST", "/api/campaigns", spec)
assert st == 201, body
prompts = [{"prompt_id": f"p-{i:05d}", "text": f"Write a function for task {i}"}
for i in range(spec["target_items"])]
models = {"a": sampler.StubModel("ckpt-current"), "b": sampler.StubModel("ckpt-candidate")}
made = sampler.fill_buffer(app.conn, spec, prompts, models, n=spec["target_items"],
now=clock[0], sleep=lambda s: None)
assert made["made"] == spec["target_items"]
for g in range(n_gold): # gold: one response is known to be wrong
store.add_item(app.conn, spec["campaign_id"], {
"item_id": f"gold-{g}", "prompt_id": f"g-{g}", "prompt": f"Gold task {g}",
"response_a": f"correct solution {g}", "response_b": f"off-by-one bug {g}",
"models": {"a": "gold", "b": "gold"}, "left_is_a": g % 2 == 0}, clock[0], gold="a")
return app, spec, clock
import json, os
import pytest
from fbp import quality, sampler
from fbp.export import export_campaign
from fbp.ftypes import REGISTRY
from fbp.simulate import SimRater, call, oracle, run
from fbp.spec import load_spec, validate
from tests.helpers import HERE, build, candidate_wins
def test_w1_spec_numbers():
spec = load_spec(os.path.join(HERE, "w1_campaign.json"))
assert validate(spec, set(REGISTRY)) == []
assert spec.labels_needed() == 24_000 # 2,000 x 3 + 18,000
assert spec.assignments_needed() == 25_263 # 24,000 / 0.95
assert spec.warmup_extra_assignments() == 1_184 # gold warm-up, 150 raters
assert round(spec.est_cost_usd()) == 79_341 # 26,447 x 4.5 min x $40/h
def test_spec_rejects_typos_and_overspend(tmp_path):
raw = json.load(open(os.path.join(HERE, "w1_campaign.json")))
p = tmp_path / "bad.json"
p.write_text(json.dumps({**raw, "gold_rat": 0.05}))
with pytest.raises(ValueError, match="gold_rat"):
load_spec(str(p))
p.write_text(json.dumps({**raw, "budget_usd": 50_000}))
assert any("exceeds budget" in e for e in validate(load_spec(str(p)), set(REGISTRY)))
def test_ui_never_sees_gold_flag_or_model_names(tmp_path):
app, spec, _ = build(tmp_path)
for r in range(30):
st, task = call(app, "GET", "/api/campaigns/w1-test/next", headers={"X-Rater-Id": f"r{r}"})
assert st == 200 and set(task["item"]) == {"prompt", "left", "right"}
assert "ckpt" not in json.dumps(task)
def test_retry_with_same_key_is_idempotent(tmp_path):
app, _, _ = build(tmp_path)
h = {"X-Rater-Id": "r1", "Idempotency-Key": "k-1"}
_, task = call(app, "GET", "/api/campaigns/w1-test/next", headers=h)
body = {"assignment_id": task["assignment_id"], "payload": {"choice": "left", "strength": "clear"},
"seconds": 200}
assert call(app, "POST", "/api/labels", body, h)[0] == 201
st, again = call(app, "POST", "/api/labels", body, h) # network retry
assert st == 200 and again["replayed"]
assert app.conn.execute("SELECT count(*) FROM labels").fetchone()[0] == 1
_, t2 = call(app, "GET", "/api/campaigns/w1-test/next", headers=h)
assert call(app, "POST", "/api/labels", {**body, "assignment_id": t2["assignment_id"]}, h)[0] == 409
def test_invalid_label_is_rejected_with_reason(tmp_path):
app, _, _ = build(tmp_path)
h = {"X-Rater-Id": "r1", "Idempotency-Key": "k-2"}
_, task = call(app, "GET", "/api/campaigns/w1-test/next", headers=h)
st, body = call(app, "POST", "/api/labels", {"assignment_id": task["assignment_id"],
"payload": {"choice": "left"}, "seconds": 90}, h)
assert st == 422 and "strength" in body["error"]
def test_expired_lease_is_reissued(tmp_path):
app, spec, clock = build(tmp_path, target_items=3, overlap_fraction=0.0, n_gold=0)
got = {call(app, "GET", "/api/campaigns/w1-test/next", headers={"X-Rater-Id": f"r{i}"})[1]["item"]["prompt"]
for i in range(3)}
assert len(got) == 3 # all three items leased
assert call(app, "GET", "/api/campaigns/w1-test/next", headers={"X-Rater-Id": "r9"})[0] == 204
clock[0] += spec["lease_seconds"] + 1 # leases lapse unanswered
assert call(app, "GET", "/api/campaigns/w1-test/next", headers={"X-Rater-Id": "r9"})[0] == 200
def test_sampler_survives_flaky_endpoint(tmp_path):
app, spec, clock = build(tmp_path, target_items=1, n_gold=0)
flaky = {"a": sampler.StubModel("ckpt-current", fail_rate=0.5, seed=3),
"b": sampler.StubModel("ckpt-candidate", fail_rate=0.5, seed=4)}
prompts = [{"prompt_id": f"p-{i:05d}", "text": f"extra {i}"} for i in range(1, 101)]
out = sampler.fill_buffer(app.conn, spec, prompts, flaky, n=100, now=clock[0], sleep=lambda s: None)
assert out["made"] + out["failed"] == 100 and out["failed"] > 0
assert flaky["a"].calls > 100 # retries happened
def test_end_to_end_quality_and_export(tmp_path):
app, spec, _ = build(tmp_path)
hidden = oracle(app.conn, "w1-test", candidate_wins)
raters = [SimRater(f"good{i}", "good", seed=i) for i in range(6)]
raters += [SimRater("spam1", "spammer", seed=11), SimRater("left1", "left", seed=12)]
posted = run(app, "w1-test", raters, hidden)
assert posted >= spec["target_items"]
report = quality.rater_report(app.conn, "w1-test")
assert report["spam1"]["verdict"] in ("remove", "low_effort")
assert report["left1"]["verdict"] == "remove" # ~50% on balanced gold
assert all(report[f"good{i}"]["verdict"] == "ok" for i in range(6))
assert sorted(quality.apply_removals(app.conn, report)) == ["left1", "spam1"]
assert run(app, "w1-test", raters[:6], hidden) > 0 # removed raters' items are redone
records, manifest = export_campaign(app.conn, "w1-test", str(tmp_path / "w1.jsonl"))
assert manifest["n_items_labelled"] == spec["target_items"]
assert manifest["dropped_labels"]["removed_rater"] > 0
assert all("gold" not in r["meta"]["item_id"] for r in records)
right = sum(r["meta"]["chosen_model"] == ("ckpt-candidate" if candidate_wins(
r["meta"]["item_id"].split(":")[1]) == "b" else "ckpt-current") for r in records)
assert right / len(records) > 0.85 # good raters are 90% accurate
assert quality.pairwise_agreement(app.conn, "w1-test") > 0.7
Running python3 demo.py drives six accurate simulated raters, one random fast clicker and one rater who always picks the left response through the same API, then prints:
[PASS] spec valid: ok
[PASS] buffer filled: 300 of 300 items ready
[PASS] gold pool size: 40 gold items; need >= 32 (3x a rater's expected exposure)
[PASS] gold answer position balanced: 50% of gold answers on the left (an always-left rater would score this)
[PASS] gold prompts distinct from real: 0 gold prompts also in the real pool
[PASS] export dry run: 0 records pass the contract
[PASS] endpoints healthy: model endpoints and label API respond
labels posted: 559
good0 labels= 70 gold=28/29 ci=(0.828, 0.994) median_s= 262.6 -> ok
good1 labels= 71 gold=22/24 ci=(0.742, 0.977) median_s= 276.6 -> ok
good2 labels= 70 gold=21/25 ci=(0.653, 0.936) median_s= 266.7 -> ok
good3 labels= 70 gold=16/17 ci=(0.73, 0.99) median_s= 248.1 -> ok
good4 labels= 69 gold=20/24 ci=(0.641, 0.933) median_s= 260.2 -> ok
good5 labels= 72 gold=27/28 ci=(0.823, 0.994) median_s= 279.7 -> ok
left1 labels= 67 gold=11/19 ci=(0.363, 0.769) median_s= 83.6 -> remove
spam1 labels= 70 gold=14/33 ci=(0.272, 0.592) median_s= 16.0 -> remove
removed: ['spam1', 'left1']
relabelled after removal: 148
pairwise agreement (active raters): 0.889
{'n_records': 300, 'n_items_labelled': 300, 'dropped_labels': {'removed_rater': 85, 'too_fast': 0}, 'sha256': '8a34a1cccd156f98a2accbb2c346304939f4461e9173f60fbfb6413e2f756667'}
The two bad raters are removed on the Wilson upper bound (0.769 and 0.592), their 85 labels are dropped, their items are relabelled by the remaining raters (148 more assignments), and the export covers all 300 items. Note that this run's agreement (0.889) reflects simulated raters with 90% accuracy, not W1's 72%.
Debugging tips. If export disagrees with what raters say they chose, test canonical on one item with each value of left_is_a. If a rater gets 204 while items remain, check whether all remaining items are already leased (open) or already seen by that rater. If gold accuracy is 100% for every rater, the gold is too easy or visually distinguishable from real items.
Running the minimal platform for a real campaign needs three things beyond the code: SLOs for the rater-facing path, observability for data correctness, and a known scaling limit with a measured trigger for replacing it.
| SLI | Definition | Objective (W1) | Source in code |
|---|---|---|---|
| Time to first sample | latency of GET /next returning 200 | p50 ≤ 2 s, p95 ≤ 5 s | request timing around next_task |
| Submit success | (201 + 200 replay) / all POST /labels excluding 422 | ≥ 99.95% | status codes from post_label |
| Buffer runway | ready unleased items / items consumed per minute | ≥ 60 min during shifts | items vs assignments tables |
| Export reproducibility | same snapshot, same SHA-256 | 100% | manifest sha256 |
The first scaling problem: a query that grows with the campaign. The task query must find, for one rater, an unfinished item that rater has not seen. In the minimal code it does so with correlated subqueries over every unfinished item. That is correct but its cost grows with the number of items and labels.
Symptom. During development, a load test of 1,000 "next + submit" cycles against 3,000 items took 45.2 s: 45 ms per cycle, and rising as labels accumulated. Projected to W1's 20,000 items and 24,000 labels (cost proportional to items × labels, about 160 times the test's), even the median time to first sample would have exceeded the 2 s p50 objective long before the campaign ended.
Diagnosis. The ordering clause counts labels per item, and the labels table had no index on item_id, so each count scanned the whole labels table: cost proportional to items × labels. The rater-side lookups also scanned assignments without an index on (rater_id, campaign_id, status).
Remedy. Two indexes added to migration 1 (ix_labels_item, ix_assign_rater). The same test then took 3.1 s: 3.1 ms per cycle, about a 14.6× improvement. At W1's full 20,000 items the cycle measured 15 ms (66 cycles per second), against a peak demand of 0.56 per second. All measurements were taken on a 2-vCPU container with Python 3.13 and SQLite 3.53; treat them as orders of magnitude, not benchmarks.
Cost and trade-off. Indexes slow writes slightly and grow the file; neither matters at W1's write rate. The remaining linear term (scanning unfinished items) is acceptable for one campaign of this size and is the trigger for the next change.
Validation. The fix is supported if cycle time stays roughly flat as labels grow at fixed item count, and weakened if it still rises with labels (another unindexed path). The next change, needed when campaigns reach about 10× W1 or many campaigns share one database, is to maintain a per-item active_count column and a partial index on unfinished items, or move to PostgreSQL with SELECT … FOR UPDATE SKIP LOCKED, so that picking a task is a constant-time index probe.
Correctness signals that must exist from the first day. (1) The share of exported pairs whose chosen response is on the left of the screen should be near 50%; a value near 0% or 100% means the reverse mapping is broken. (2) Per-rater left-click rate; a rater above about 80% left on balanced items is position-biased or not reading. (3) The 409 rate on submit; a rising rate means clients are re-sending answers with new keys, usually after a UI bug. (4) Dropped-label counts in each manifest, split by reason, so researchers can see how much paid work quality control discarded.
How to choose among remedies when the platform outgrows itself. If the bottleneck is task selection latency, fix the query first (cheap, local). If it is write contention from several service replicas, move the store to PostgreSQL (moderate, changes deployment). If it is model-call latency in buffer fill, parallelise generation or switch to an on-demand warm pool (Chapter 4). Measure first: each remedy addresses a different term and none helps the others.
Adding a new feedback type end to end
What "a new feedback type" means. A feedback type is a kind of judgment a person records about model output, together with everything the platform must know to collect it and turn it into training signal: what the person sees, what they may submit, how their work is checked, and what record leaves the platform. Pairwise preference is one type. Rubric data, ratings, critiques, corrected continuations and step-level labels are others (Chapter 1). Research needs change faster than platforms, so the cost of adding a type is one of the most important properties of the platform's design.
Why rubrics, and why now. Pairwise preferences work when a person can tell which of two responses is better. In domains such as legal drafting or medicine, "better" depends on many specific requirements, and a single comparison hides which requirement decided it. Rubric data makes the requirements explicit: an expert writes, for each prompt, a list of checkable criteria with weights, including negative-weight pitfalls such as citing a law that does not exist. A response's score is the weighted share of criteria it meets. HealthBench is a public example of this format: physicians wrote conversation-specific criteria, each worth between −10 and 10 points, and a response's score is the points of met criteria divided by the maximum possible (Arora et al., 2025). Rubrics as Rewards uses instance-specific rubrics as the reward for on-policy RL in such domains and reports relative improvements of up to 31% on HealthBench and 7% on GPQA-Diamond over LLM-judge baselines that use direct Likert-style rewards (Gunjal et al., 2025). In RL use, an AI grader applies the human-written rubric to each policy sample, so the human data is the rubric and the human grades that calibrate the AI grader.
The five touch points. On a platform built like the minimal one, adding a type changes five things and nothing else.
- Schema. Labels are stored as JSON validated by the type, so most types need no new tables. Rubrics do need one: a rubric is a durable object that later grading tasks reference. A numbered migration adds a
rubricstable with a content-hash identifier and a version per prompt, so a grade always points to the exact rubric text it was given. - The type class. Two classes implement the five-method interface:
rubric_author(experts write 8–12 criteria, validated for count, unique ids, length and integer weights in [−10, 10]) andrubric_grade(graders mark each criterion met or not met). - The interface. A new React component shows the prompt, one response and the criteria, with an explicit met/not-met choice per criterion and no default, so "not met" can never be a skipped click. Weights are hidden from graders: they judge whether a criterion holds, and arithmetic happens on the server.
- Quality. Gold for authoring is a set of key points an expert reference rubric covers; gold for grading is a reference set of met/not-met marks, and a grade counts as correct when at least 80% of its marks match.
- Export and gate. The grading export groups the four graded responses of each prompt with the rubric and computes scores. A release gate then compares an AI grader's marks with the human majority marks; only if item-level agreement is at least 0.8 do the rubrics go to the RL reward service.
The service, store, quality report and export pipeline do not change, apart from one import line that registers the new types.
A W3 prompt asks for a mutual NDA confidentiality clause. The expert's rubric has 10 criteria: eight positive (the term is stated in years, 5 points; confidential information is defined with standard exclusions, 5; obligations are mutual, 4; survival after termination, 3; disclosure required by law is permitted with notice, 3; return or destruction of materials, 2; consistent defined terms, 2; plain structure, 1) and two pitfalls (cites a statute or case that does not exist, −5; imposes obligations on one party only, −3). The maximum is 25 points. A draft that meets the first four positives, the return-of-materials and plain-structure criteria, and falls into the one-sided pitfall earns 5 + 5 + 4 + 3 + 2 + 1 − 3 = 17 points, a score of 17/25 = 0.68. Graders see the ten criteria without weights; the server computes 0.68.
Compared with pairwise. Pairwise labelling needs no per-prompt setup and is fast (W1's median is 4 minutes), but each label carries about one bit and no reason. Rubric data costs a large up-front expert investment per prompt (W3: about 25 minutes) and then yields many cheap, explainable judgments. The two also fail differently: pairwise labels drift with taste, rubrics drift with wording.
What you would actually do. Before writing code for a new type, write its five touch points on one page: stored objects, label schema and validation, what the screen shows and hides, how gold works, and the exported record with its contract. If the type needs a change to the service or store beyond registration, treat that as a defect in the platform's extension interface and fix the interface first.
Scoring. Let a rubric have criteria \(i = 1,\dots,K\) with integer weights \(w_i \in [-10, 10]\setminus\{0\}\), and let \(m_i \in \{0,1\}\) indicate whether a response meets criterion \(i\). The score is
\[ s = \operatorname{clip}_{[0,1]}\!\left(\frac{\sum_{i} w_i m_i}{\sum_{i: w_i > 0} w_i}\right). \]The numerator adds points for met positive criteria and subtracts points for met pitfalls; the denominator is the best achievable score. This follows the HealthBench scoring rule (Arora et al., 2025) with one difference: HealthBench lets an individual example score fall below zero and clips only the mean over examples to [0, 1], whereas the platform clips each response's score so that a single RL reward stays in [0, 1]. For the W3 example, \(s = 17/25 = 0.68\).
Binary versus graded criteria. Per-criterion Likert scales (0–4) add information but multiply disagreement: two graders who agree a criterion is "mostly met" may pick 2 and 3. Binary marks make agreement measurable as a simple proportion and match what an AI grader can be asked reliably. The platform default is binary; graded criteria are a later option if binary agreement is high and researchers need finer reward.
Workload. The W3 sheet gives the two human workloads.
For W3, 3,000 prompts × 25 min of rubric writing = 1,250 expert-hours. Graders score 4 responses per prompt: 12,000 responses × 2 min = 400 hours. W3 does not state a rate; if the W2 expert rate of $120/h applied to both (an assumption), the total would be 1,650 h × $120 = $198,000.
The release gate needs an estimate of item-level human–AI agreement \(\hat a\) precise enough to compare with 0.8. With \(n\) independent item judgments, the 95% half-width is about \(1.96\sqrt{\hat a(1-\hat a)/n}\). For a half-width of 0.01 at \(\hat a = 0.8\), \(n \approx 1.96^2 \times 0.16 / 0.01^2 \approx 6{,}147\) item judgments, which is about 615 graded responses at 10 criteria each, or 5% of the 12,000. For a half-width of 0.02, 1,537 judgments (about 154 responses) suffice. Judgments within one response are correlated, so treat these as lower bounds.
Design decisions.
| Decision | Options | Default and reason |
|---|---|---|
| Where labels live | JSON payload validated per type; typed tables per type | JSON payload: a new type needs no migration for labels. Durable objects that others reference (rubrics) get their own table. |
| Rubric identity | auto-increment id; content hash | Content hash plus a per-prompt version: editing a criterion creates a new rubric, and old grades keep pointing at the text they were given. |
| Weights visible to graders | shown; hidden | Hidden: graders judge criteria, not totals, which removes the temptation to adjust marks toward an intended score. |
| Criterion scale | binary; 0–4 | Binary, for measurable agreement and AI-grader compatibility. |
| Campaign structure | one campaign with two task kinds; two chained campaigns | Two campaigns: authors and graders are different populations with different rates, gold and stopping rules. |
| Release gate | overall agreement; per criterion class | Overall agreement in the minimal code; the Operate level shows why production needs per-class gates. |
What you would actually do. Fix the scoring formula and the exported record before collecting any rubric, size the agreement sample from the half-width the gate needs, and budget authoring as the dominant cost (here 1,250 of 1,650 hours).
The new module registers two feedback types and one migration. Because store.connect() runs any migration not yet recorded, importing the module before connecting is enough to add the rubrics table to new and existing databases.
"""W3 rubric feedback: experts author per-prompt rubrics; graders mark each
criterion met / not met on model responses; the export feeds an RL reward service."""
from __future__ import annotations
import hashlib, json, re
from collections import Counter, defaultdict
from fbp import store
from fbp.ftypes import register
MIN_ITEMS, MAX_ITEMS = 8, 12
# Plugin migration: runs on the next store.connect() after this module is imported.
store.MIGRATIONS[2] = """
CREATE TABLE rubrics(rubric_id TEXT PRIMARY KEY, prompt_id TEXT NOT NULL, version INTEGER NOT NULL,
rubric_json TEXT NOT NULL, author_label_id TEXT NOT NULL REFERENCES labels(label_id),
created_at REAL NOT NULL, UNIQUE(prompt_id, version))
"""
def rubric_id(items: list[dict]) -> str:
canon = json.dumps(sorted(items, key=lambda i: i["id"]), sort_keys=True)
return "rb-" + hashlib.sha256(canon.encode()).hexdigest()[:16] # content-addressed
def score(items: list[dict], met: dict[str, bool]) -> float:
"""Points of met criteria (pitfalls carry negative weight) over the maximum positive points."""
earned = sum(i["weight"] for i in items if met[i["id"]])
best = sum(i["weight"] for i in items if i["weight"] > 0)
return min(1.0, max(0.0, earned / best))
class RubricAuthor:
name, schema_version = "rubric_author", 1
def render(self, item):
return {"prompt": item["prompt"], "min_items": MIN_ITEMS, "max_items": MAX_ITEMS}
def validate(self, item, label):
its, errs = label.get("items", []), []
if not MIN_ITEMS <= len(its) <= MAX_ITEMS:
errs.append(f"need {MIN_ITEMS}-{MAX_ITEMS} criteria, got {len(its)}")
ids = [i.get("id") for i in its]
if len(set(ids)) != len(ids) or not all(re.fullmatch(r"c\d{1,2}", str(x)) for x in ids):
errs.append("criterion ids must be unique, like c1..c12")
for i in its:
if not 10 <= len(i.get("criterion", "")) <= 300:
errs.append(f"{i.get('id')}: criterion must be 10-300 characters")
w = i.get("weight")
if not isinstance(w, int) or isinstance(w, bool) or w == 0 or not -10 <= w <= 10:
errs.append(f"{i.get('id')}: weight must be a non-zero integer in [-10, 10]")
if not any(isinstance(i.get("weight"), int) and i["weight"] > 0 for i in its):
errs.append("at least one criterion needs a positive weight")
return errs
def is_correct(self, item, gold, label):
"""Gold = key points an expert reference rubric covers; each must appear in some criterion."""
text = " ".join(i["criterion"].lower() for i in label["items"])
return all(k in text for k in gold["must_cover"])
def export(self, rows, meta):
out = []
for item, labels in rows: # first accepted rubric wins; others kept as a count
its = labels[0]["items"]
out.append({"prompt_id": item["prompt_id"], "prompt": item["prompt"],
"rubric_id": rubric_id(its), "items": its,
"meta": {**meta, "item_id": item["item_id"], "n_alternatives": len(labels) - 1}})
return out
def check_record(self, rec):
return [] if MIN_ITEMS <= len(rec["items"]) <= MAX_ITEMS else ["rubric size out of range"]
class RubricGrade:
name, schema_version = "rubric_grade", 1
def render(self, item): # weights hidden: graders judge met / not met only
return {"prompt": item["prompt"], "response": item["response"],
"criteria": [{"id": i["id"], "criterion": i["criterion"]} for i in item["rubric"]]}
def validate(self, item, label):
want, met = {i["id"] for i in item["rubric"]}, label.get("met", {})
errs = []
if set(met) != want:
errs.append(f"score every criterion exactly once: missing {sorted(want - set(met))}, "
f"unknown {sorted(set(met) - want)}")
if not all(isinstance(v, bool) for v in met.values()):
errs.append("each criterion is true (met) or false (not met)")
return errs
def is_correct(self, item, gold, label):
agree = sum(label["met"][k] == v for k, v in gold.items())
return agree / len(gold) >= 0.8
def export(self, rows, meta):
by_prompt: dict[str, dict] = {}
for item, labels in rows:
met = {}
for cid in (i["id"] for i in item["rubric"]):
votes = Counter(l["met"][cid] for l in labels)
(v, n), = votes.most_common(1)
if list(votes.values()).count(n) == 1: # skip criteria with a tied vote
met[cid] = v
if len(met) < len(item["rubric"]):
continue
rec = by_prompt.setdefault(item["prompt_id"], {
"prompt_id": item["prompt_id"], "prompt": item["prompt"], "rubric_id": item["rubric_id"],
"rubric": item["rubric"], "graded": [], "meta": {**meta, "item_id": item["prompt_id"]}})
rec["graded"].append({"response_id": item["response_id"], "response": item["response"],
"met": met, "score": round(score(item["rubric"], met), 4),
"n_graders": len(labels)})
return list(by_prompt.values())
def check_record(self, rec):
ids = {i["id"] for i in rec["rubric"]}
errs = [] if MIN_ITEMS <= len(ids) <= MAX_ITEMS else ["rubric size out of range"]
for g in rec["graded"]:
if set(g["met"]) != ids:
errs.append(f"{g['response_id']}: criteria mismatch")
if not 0 <= g["score"] <= 1:
errs.append(f"{g['response_id']}: score outside [0, 1]")
return errs
register(RubricAuthor())
register(RubricGrade())
def promote_rubrics(conn, author_records: list[dict], grade_campaign: str,
responses: dict[str, list[dict]], label_ids: dict[str, str], now: float) -> int:
"""Freeze accepted rubrics (versioned) and create one grading item per (prompt, response)."""
made = 0
for rec in author_records:
v = 1 + (conn.execute("SELECT max(version) FROM rubrics WHERE prompt_id=?",
(rec["prompt_id"],)).fetchone()[0] or 0)
conn.execute("INSERT OR IGNORE INTO rubrics VALUES (?,?,?,?,?,?)",
(rec["rubric_id"], rec["prompt_id"], v, json.dumps(rec["items"]),
label_ids[rec["meta"]["item_id"]], now))
for resp in responses[rec["prompt_id"]]:
store.add_item(conn, grade_campaign, {
"item_id": f"{grade_campaign}:{rec['prompt_id']}:{resp['response_id']}",
"prompt_id": rec["prompt_id"], "prompt": rec["prompt"], "rubric_id": rec["rubric_id"],
"rubric": rec["items"], "response_id": resp["response_id"], "response": resp["text"]}, now)
made += 1
return made
def ai_agreement(records: list[dict], ai_grade) -> float:
"""Item-level agreement between human majority labels and an AI grader."""
pairs = agree = 0
for rec in records:
crit = {i["id"]: i["criterion"] for i in rec["rubric"]}
for g in rec["graded"]:
for cid, human in g["met"].items():
pairs += 1
agree += ai_grade(rec["prompt"], g["response"], crit[cid]) == human
return agree / pairs
def release_to_reward_service(records: list[dict], ai_grade, threshold: float = 0.8) -> dict:
"""Gate: the AI grader becomes the RL reward only if it agrees with humans often enough."""
a = ai_agreement(records, ai_grade)
if a < threshold:
raise ValueError(f"AI-human item agreement {a:.3f} < {threshold}; do not release")
return {"grader_agreement": round(a, 4),
"rubrics": [{"prompt_id": r["prompt_id"], "prompt": r["prompt"], "rubric_id": r["rubric_id"],
"criteria": r["rubric"]} for r in records]}
The only change to the existing platform is one line in fbp/service.py, already visible in the listing of the previous section:
import fbp.rubric # noqa: F401 (W3: registers rubric types and migration 2)
The interface adds a types file and one component; types.ts and api.ts are reused unchanged. The submit button stays disabled until every criterion has an explicit mark.
// W3 wire types. Weights are deliberately absent: graders judge met / not met.
export interface Criterion { id: string; criterion: string }
export interface RubricGradeView { prompt: string; response: string; criteria: Criterion[] }
export interface RubricGradeLabel { met: Record<string, boolean>; note?: string }
import { useEffect, useMemo, useState } from "react";
import { fetchNext, submitLabel } from "./api";
import type { Task } from "./types";
import type { RubricGradeLabel, RubricGradeView } from "./rubricTypes";
type Mark = boolean | undefined;
export function RubricGradeTask({ campaignId, raterId }: { campaignId: string; raterId: string }) {
const [task, setTask] = useState<Task<RubricGradeView> | null | undefined>(undefined);
const [marks, setMarks] = useState<Record<string, Mark>>({});
const [error, setError] = useState<string | null>(null);
const [started, setStarted] = useState(0);
const idemKey = useMemo(() => crypto.randomUUID(), [task?.assignment_id]);
const load = async () => {
setMarks({}); setError(null);
try { setTask(await fetchNext<RubricGradeView>(campaignId, raterId)); setStarted(performance.now()); }
catch (e) { setError(String(e)); }
};
useEffect(() => { void load(); }, [campaignId, raterId]);
if (task === undefined) return <p>Loading…</p>;
if (task === null) return <p>No tasks available.</p>;
const { prompt, response, criteria } = task.item;
// every criterion must be marked explicitly: no default, so "not met" is never a skipped click
const unmarked = criteria.filter((c) => marks[c.id] === undefined).length;
const submit = async () => {
const label: RubricGradeLabel = { met: Object.fromEntries(criteria.map((c) => [c.id, marks[c.id]!])) };
try {
await submitLabel(raterId, task.assignment_id, label, (performance.now() - started) / 1000, idemKey);
await load();
} catch (e) { setError((e as Error).message); }
};
return (
<main className="rubric-grade">
<section><h2>Prompt</h2><pre>{prompt}</pre></section>
<section><h2>Response</h2><pre>{response}</pre></section>
<table>
<thead><tr><th>Criterion</th><th>Met</th><th>Not met</th></tr></thead>
<tbody>
{criteria.map((c) => (
<tr key={c.id}>
<td>{c.criterion}</td>
{[true, false].map((v) => (
<td key={String(v)}>
<input type="radio" name={c.id} checked={marks[c.id] === v}
onChange={() => setMarks({ ...marks, [c.id]: v })} />
</td>
))}
</tr>
))}
</tbody>
</table>
{error && <p role="alert">{error}</p>}
<button disabled={unmarked > 0} onClick={() => void submit()}>
{unmarked > 0 ? `${unmarked} criteria left` : "Submit"}
</button>
</main>
);
}
Tests. The tests run both campaigns through the API: an expert submits a 7-criterion rubric (rejected with 422) and then the W3 rubric (accepted) for five prompts; rubrics are promoted into 20 grading items; a simulated grader with 95% item accuracy marks them; export produces five records of four graded responses each. A stub AI grader with known accuracy then exercises the release gate in both directions: at 95% accuracy agreement passes 0.8, and at 65% the gate refuses to release.
import random
import pytest
from fbp import rubric, store
from fbp.export import export_campaign
from fbp.service import App
from fbp.simulate import call
W3_RUBRIC = [ # illustrative legal-drafting rubric: 8 positive criteria, 2 pitfalls
{"id": "c1", "criterion": "States the confidentiality term in years", "weight": 5},
{"id": "c2", "criterion": "Defines Confidential Information with standard exclusions", "weight": 5},
{"id": "c3", "criterion": "Obligations apply to both parties (mutual)", "weight": 4},
{"id": "c4", "criterion": "Survival of obligations after termination", "weight": 3},
{"id": "c5", "criterion": "Permits disclosure required by law with notice", "weight": 3},
{"id": "c6", "criterion": "Return or destruction of materials on request", "weight": 2},
{"id": "c7", "criterion": "Uses defined terms consistently", "weight": 2},
{"id": "c8", "criterion": "Plain sentence structure, no nested provisos", "weight": 1},
{"id": "c9", "criterion": "Cites a statute or case that does not exist", "weight": -5},
{"id": "c10", "criterion": "Imposes obligations on one party only", "weight": -3},
]
BASE = {"guideline_version": "w3-guide-1.0", "prompt_source": "inline", "models": {"policy": "ckpt-rl"},
"overlap_fraction": 0.0, "overlap_k": 1, "gold_rate": 0.01, "gold_accuracy_min": 0.8,
"min_gold_seen": 10, "min_seconds": 30, "lease_seconds": 3600, "buffer_target": 0,
"rate_usd_per_hour": 120, "est_minutes_per_label": 25, "budget_usd": 10_000}
def test_score_matches_worked_example():
met = {f"c{i}": i in (1, 2, 3, 4, 6, 8, 10) for i in range(1, 11)}
assert rubric.score(W3_RUBRIC, met) == pytest.approx(17 / 25) # 0.68
def test_migration_2_created_rubrics_table(tmp_path):
app = App(str(tmp_path / "w3.db"))
assert {r[0] for r in app.conn.execute("SELECT version FROM schema_migrations")} == {1, 2}
assert app.conn.execute("SELECT count(*) FROM rubrics").fetchone()[0] == 0
def run_w3(tmp_path, ai_accuracy: float):
rng, app = random.Random(5), App(str(tmp_path / "w3.db"), seed=1)
for cid, ftype, n in (("w3-author", "rubric_author", 5), ("w3-grade", "rubric_grade", 20)):
st, body = call(app, "POST", "/api/campaigns", {**BASE, "campaign_id": cid,
"feedback_type": ftype, "target_items": n})
assert st == 201, body
for p in range(5):
store.add_item(app.conn, "w3-author", {"item_id": f"w3-author:lp-{p}", "prompt_id": f"lp-{p}",
"prompt": f"Draft a mutual NDA confidentiality clause, variant {p}"}, 0)
h = {"X-Rater-Id": "expert1"}
for p in range(5): # experts author one rubric per prompt
_, task = call(app, "GET", "/api/campaigns/w3-author/next", headers=h)
bad = call(app, "POST", "/api/labels", {"assignment_id": task["assignment_id"], "seconds": 1500,
"payload": {"items": W3_RUBRIC[:7]}}, {**h, "Idempotency-Key": f"bad{p}"})
assert bad[0] == 422 and "need 8-12" in bad[1]["error"]
st, _ = call(app, "POST", "/api/labels", {"assignment_id": task["assignment_id"], "seconds": 1500,
"payload": {"items": W3_RUBRIC}}, {**h, "Idempotency-Key": f"ok{p}"})
assert st == 201
authored, _ = export_campaign(app.conn, "w3-author")
label_ids = dict(app.conn.execute("SELECT item_id, label_id FROM labels WHERE campaign_id='w3-author'"))
responses = {f"lp-{p}": [{"response_id": f"r{k}", "text": f"Clause draft {p}.{k}"} for k in range(4)]
for p in range(5)}
assert rubric.promote_rubrics(app.conn, authored, "w3-grade", responses, label_ids, 0) == 20
truth = {(p, k, c["id"]): rng.random() < 0.6 for p in range(5) for k in range(4) for c in W3_RUBRIC}
hg = {"X-Rater-Id": "grader1"}
for n in range(20): # graders: 95% item-level accuracy
st, task = call(app, "GET", "/api/campaigns/w3-grade/next", headers=hg)
assert set(task["item"]) == {"prompt", "response", "criteria"} # weights hidden
p, k = (int(x) for x in task["item"]["response"].split()[-1].split("."))
met = {c["id"]: truth[(p, k, c["id"])] ^ (rng.random() < 0.05) for c in task["item"]["criteria"]}
assert call(app, "POST", "/api/labels", {"assignment_id": task["assignment_id"], "seconds": 120,
"payload": {"met": met}}, {**hg, "Idempotency-Key": f"g{n}"})[0] == 201
graded, manifest = export_campaign(app.conn, "w3-grade")
assert manifest["n_records"] == 5 and all(len(r["graded"]) == 4 for r in graded)
def ai_grade(prompt, response, criterion): # stub AI grader with known accuracy
p, k = (int(x) for x in response.split()[-1].split("."))
cid = next(c["id"] for c in W3_RUBRIC if c["criterion"] == criterion)
return truth[(p, k, cid)] ^ (rng.random() > ai_accuracy)
return graded, ai_grade
def test_w3_end_to_end_release_gate_passes(tmp_path):
graded, ai_grade = run_w3(tmp_path, ai_accuracy=0.95)
out = rubric.release_to_reward_service(graded, ai_grade, threshold=0.8)
assert out["grader_agreement"] >= 0.8 and len(out["rubrics"]) == 5
def test_w3_release_gate_blocks_weak_grader(tmp_path):
graded, ai_grade = run_w3(tmp_path, ai_accuracy=0.65)
with pytest.raises(ValueError, match="do not release"):
rubric.release_to_reward_service(graded, ai_grade, threshold=0.8)
Debugging tips. A 422 with "unknown" criterion ids usually means the UI was given a different rubric version than the stored item; compare the item's rubric_id with the one the screen loaded. If the release gate fails while human–human agreement is high, inspect agreement per criterion: a handful of vague criteria ("well written") typically account for most disagreement. If scores cluster at 1.0, the rubric is too easy for the policy and gives no RL signal; that is a rubric problem, not a code problem.
Operating a new type means rolling it out under the test ladder (next section) and then watching signals specific to it. For rubric data the signals are:
| Signal | Formula | Healthy range (initial, to be calibrated) | Action when out of range |
|---|---|---|---|
| Rubric validation failures | 422 responses on rubric_author / submissions, by reason | falling after the first day | fix guideline examples for the top reason |
| Rubric size | distribution of criteria per rubric | mean near 10, few at the bounds | many at 8 or 12 suggests authors fit the limit, not the task |
| Grader–grader agreement | item-level, on double-graded responses | above the human–AI target | below it, the AI gate is meaningless; rewrite criteria |
| Human–AI agreement by class | separately for positive criteria and pitfalls | each ≥ 0.8 | block release for the failing class |
| Score saturation | share of policy samples scoring ≥ 0.95 | low early in RL | high share means the rubric no longer separates samples |
Symptom. The first W3 release candidate shows overall human–AI item agreement of 0.82 on 615 double-scored responses (6,150 item judgments), above the 0.8 gate. A researcher inspecting samples notices that responses citing invented statutes still score well.
Measurements that separate causes. Split agreement by criterion class. Each W3 rubric has 8 positive criteria and 2 pitfalls, so pitfalls are 20% of judgments. Agreement is 0.86 on positive criteria (4,920 judgments) and 0.66 on pitfalls (1,230 judgments, 95% half-width ≈ 0.026). The overall figure is the weighted mean 0.8 × 0.86 + 0.2 × 0.66 = 0.82: the aggregate hides a failing subgroup, the same reason canary analysis breaks metrics down by population (Google SRE Workbook). Disagreements are almost all one direction: the AI grader marks the fabricated-citation pitfall "not met" when humans mark it "met".
Why it matters. A missed −5 pitfall inflates a response's score by 5/25 = 0.20. Used as an RL reward, that rewards the policy for exactly the behaviour the expert wrote the pitfall to punish.
Intervention. (1) Change the gate to require ≥ 0.8 for each criterion class separately, which blocks this release. (2) For the citation pitfall, stop asking the grader to judge from memory: give it a citation-lookup step against a legal database, or route responses that contain citations to human review. (3) Rewrite the pitfall criteria in observable terms ("every cited statute or case can be found by its citation") rather than intent terms.
Cost. A per-class gate needs enough judgments per class: for ±0.02 on pitfalls about 1,537 judgments, roughly 770 responses at two pitfalls each, slightly more than the 615 the overall gate needed. Human review of citation-bearing responses adds grader hours in proportion to their share.
Validation. The remedy is supported if pitfall agreement on a fresh sample rises to at least 0.8 and the score of responses with known fabricated citations drops by about 0.2. It is weakened if pitfall agreement stays near 0.66, which would mean the AI grader cannot judge this criterion at all and it must be checked by a tool or by people.
Runbook: new feedback type goes live.
- Merge the type behind a campaign that only internal staff can see; run the type's unit tests and a replay of any pilot data.
- Run a shadow campaign of at least the size the agreement gate needs (W3: about 154 responses for ±0.02) with staff graders; compute grader–grader agreement first. If it is below the AI target, stop and rewrite the guideline.
- Open to a 5% canary of the expert pool; compare gold accuracy and time per task with the shadow staff.
- Run the release gate per criterion class. Only then point the reward service at the exported rubrics.
- After the first RL iteration, check score saturation on policy samples; schedule rubric revision when it rises.
The test ladder: unit, replay, shadow campaign, staged rollout
Why ordinary tests are not enough. In most software a bug produces an error, a crash or a wrong page. In a feedback platform the most damaging bugs produce nothing visible: a refactor that forgets the left/right randomisation still returns 201 for every label, still writes a valid JSONL file and still passes the data contract, while silently reversing about half of the preferences. A guideline edit that confuses raters produces well-formed labels with lower agreement. A new interface that slows raters down produces the right labels at the wrong cost. The test ladder is a sequence of four kinds of test, each run before the next, each catching a class of failure the rungs below it cannot see.
- Unit and contract tests. Functions, schemas and API behaviour checked on small synthetic inputs: validation rejects bad specs and labels, retries are idempotent, the UI never receives model names, an expired lease is reissued, the export contract holds. They run in seconds on every change. They catch wrong code. They cannot catch code that is wrong in the same way the test author assumed.
- Replay. A snapshot is a point-in-time copy of the production database. Replay re-runs the new export code against a frozen snapshot and compares its output, record by record, with the file that was actually shipped. If labels have not changed, the output must be identical; any difference must be explained by an intended change. Replay catches wrong data transformations: the position-mapping bug flips about half the records and is caught immediately. It costs minutes and needs no people.
- Shadow campaign. A shadow campaign runs a new interface, guideline or feedback type on the same prompts as a production campaign, labelled by internal staff or a small paid cohort, with its output never exported to training. Its labels are compared with production's. It catches changes that alter what humans do: a confusing new layout, a guideline that shifts the decision boundary. It costs paid hours but carries no training risk.
- Staged rollout. The change goes live for a stable, randomly chosen fraction of raters (a canary), first a few percent, then half, then all, with an automated comparison against the remaining raters (the control) at each stage. This follows the canarying practice described in the Google SRE Workbook, which defines a canary as a partial and time-limited deployment of a change evaluated against a control (Google SRE Workbook). It catches problems that appear only at real scale and with the real population. It is the most expensive rung because a bad canary produces labels that must be discarded.
Suppose a refactor of canonical() maps "left" to model a regardless of left_is_a. Unit tests that only use items with the candidate on the right pass. Replay against the last shipped W1 export reports that about 50% of records changed (in the chapter's test run, 139 of 264 records, 52.7%, change; the test asserts between 30% and 70%), and the change is blocked. Had it reached production, nothing would have failed: the export would have shipped about 18,400 well-formed pairs, half of them reversed.
Compared with ordinary software release. Unit tests and canaries are standard; replay and shadow campaigns are the rungs specific to data platforms. Replay exists because transformations of human labels must be bit-reproducible, and shadow campaigns exist because the "users" are also the instrument that produces the data.
What you would actually do. Run rungs 1 and 2 on every change in continuous integration. Require rung 3 for any change to what raters see or read (interface, guideline, feedback type). Require rung 4 for those same changes at full campaign scale. Changes to export code need rungs 1 and 2 only, because they can be fully verified on frozen data.
Each rung has a quantitative question: how many records may change, how much agreement to expect, and how many judgments a canary needs before it can decide anything.
Replay: the expected difference is zero. If the export is deterministic (records sorted by their serialised form) and labels are unchanged, two exports of the same snapshot have the same SHA-256. The gate is therefore exact: zero added, removed or changed records unless the change is intended, in which case the changed fraction is predicted in the change description and checked. For a position-mapping bug on randomised items, the expected changed fraction is the share of items with the candidate on the left whose majority is not a tie, close to 0.5.
Shadow: the expected agreement is not one. Two independent raters each correct with probability \(p\) on a binary choice agree with probability
\[ A = p^2 + (1-p)^2. \]A shadow campaign that changes nothing should reproduce production's own inter-rater agreement, not 100%. Solving for \(p\) gives \(p = \tfrac{1}{2}\big(1 + \sqrt{2A - 1}\big)\).
W1's pairwise agreement on overlap items is 72%. Under this symmetric model, \(p = \tfrac12(1+\sqrt{0.44}) \approx 0.83\): a typical W1 rater matches the majority truth about 83% of the time. A shadow campaign that labels the same prompts once each should therefore agree with production about 72% of the time. With 300 shadow items, the 95% half-width is \(1.96\sqrt{0.72\times0.28/300} \approx 0.051\), so the shadow can detect a fall to about 0.65 but not a fall to 0.70. (The chapter's simulated raters are 90% accurate, so their expected agreement is \(0.81 + 0.01 = 0.82\), and the test asserts > 0.75.)
Canary: how many gold judgments per arm. The canary compares gold accuracy in the canary arm with the control arm. To detect a drop from \(p_1\) to \(p_2\) with a two-sided 5% test and 80% power, a standard approximation for two proportions gives, per arm,
\[ n \approx \frac{(z_{0.975} + z_{0.8})^2\,\big(p_1(1-p_1) + p_2(1-p_2)\big)}{(p_1 - p_2)^2}, \quad z_{0.975} = 1.96,\ z_{0.8} = 0.84. \]| Control gold accuracy | Canary accuracy to detect | Gold judgments per arm | Assignments per arm at 5% gold |
|---|---|---|---|
| 0.86 | 0.83 (3-point drop) | ≈ 2,281 | ≈ 45,600 |
| 0.86 | 0.81 (5-point drop) | ≈ 862 | ≈ 17,200 |
| 0.86 | 0.76 (10-point drop) | ≈ 238 | ≈ 4,750 |
The whole W1 campaign has about 26,447 assignments. A 3-point gate would need 45,600 assignments in the canary arm alone, more than the campaign: it cannot be decided within one campaign. A 5% canary is about 7–8 of 150 raters, who see roughly 8 × 16.3 ≈ 130 gold items over the full campaign, not enough even for the 10-point gate. The practical design is a gate on large drops (10 points, 240 gold per arm) combined with a raised gold rate inside the canary arm during the stage, or a larger canary (20%, about 30 raters × 16.3 ≈ 490 gold). Smaller effects are measured afterwards from shadow data or across campaigns, not gated in real time.
Time per task is a more sensitive canary signal than gold accuracy because every label carries it: median seconds is compared as a ratio, and a ratio outside [0.75, 1.33] halts the stage. A large speed-up is as suspicious as a slow-down, because it often means raters have found a way to skip reading.
What you would actually do. Gate replay exactly. Gate shadow campaigns against production's own agreement, with a sample sized for the drop that matters. Gate canaries only on effects they have the power to detect, and say in the rollout plan which smaller effects are left to later measurement.
Four pieces of code implement rungs 2–4, plus the simulator that lets every rung run without people. The simulator calls the WSGI application in process (no socket) and drives simulated raters through the real API; oracle computes the correct on-screen side for each item from information real raters never see.
"""In-process HTTP client and simulated raters, for tests and shadow campaigns."""
from __future__ import annotations
import io, json, random, uuid
from wsgiref.util import setup_testing_defaults
def call(app, method: str, path: str, body=None, headers=None) -> tuple[int, object]:
"""Invoke a WSGI app without a socket; returns (status, decoded JSON or None)."""
env: dict = {}
setup_testing_defaults(env)
data = json.dumps(body).encode() if body is not None else b""
env.update(REQUEST_METHOD=method, PATH_INFO=path.split("?")[0], CONTENT_LENGTH=str(len(data)),
QUERY_STRING=path.partition("?")[2], **{"wsgi.input": io.BytesIO(data)})
for k, v in (headers or {}).items():
env["HTTP_" + k.upper().replace("-", "_")] = v
out = {}
raw = b"".join(app(env, lambda s, h: out.setdefault("s", int(s.split()[0]))))
return out["s"], (json.loads(raw) if raw else None)
def oracle(conn, campaign_id: str, better) -> dict[str, str]:
"""Simulator-only ground truth: prompt text -> correct on-screen side.
better(prompt_id) -> 'a' | 'b' says which model truly wrote the better response."""
out = {}
for payload, gold in conn.execute("SELECT payload_json, gold_json FROM items WHERE campaign_id=?",
(campaign_id,)):
it = json.loads(payload)
best = json.loads(gold) if gold else better(it["prompt_id"])
out[it["prompt"]] = "left" if (best == "a") == it["left_is_a"] else "right"
return out
class SimRater:
"""kind: 'good' (accurate, ~4.5 min), 'spammer' (random, fast), 'left' (always left)."""
def __init__(self, rater_id: str, kind: str, accuracy: float = 0.9, seed: int = 0):
self.id, self.kind, self.acc, self.rng = rater_id, kind, accuracy, random.Random(seed)
def answer(self, view: dict, hidden: dict) -> tuple[dict, float]:
t = hidden[view["prompt"]]
if self.kind == "good":
choice = t if self.rng.random() < self.acc else ("right" if t == "left" else "left")
return {"choice": choice, "strength": "clear"}, self.rng.uniform(150, 390)
if self.kind == "spammer":
return {"choice": self.rng.choice(["left", "right"]), "strength": "slight"}, self.rng.uniform(8, 25)
return {"choice": "left", "strength": "clear"}, self.rng.uniform(60, 120)
def run(app, campaign_id: str, raters: list[SimRater], hidden: dict, max_rounds: int = 10_000) -> int:
"""Round-robin raters through the real API until no rater gets work. Returns labels posted."""
posted, idle = 0, 0
for k in range(max_rounds):
r = raters[k % len(raters)]
st, task = call(app, "GET", f"/api/campaigns/{campaign_id}/next", headers={"X-Rater-Id": r.id})
if st == 204:
idle += 1
if idle >= len(raters):
break
continue
idle = 0
label, secs = r.answer(task["item"], hidden)
key = str(uuid.UUID(int=r.rng.getrandbits(128)))
st, _ = call(app, "POST", "/api/labels", {"assignment_id": task["assignment_id"],
"payload": label, "seconds": secs}, {"X-Rater-Id": r.id, "Idempotency-Key": key})
assert st == 201, st
posted += 1
return posted
Replay and shadow. snapshot uses SQLite's VACUUM INTO to write a consistent copy of a live database. diff_exports keys records by item id and ignores metadata (code version changes are expected); shadow_agreement compares majority choices between two campaigns over the prompts they share. The module's command-line entry point is what continuous integration calls.
"""Replay and shadow comparisons: rungs 2 and 3 of the test ladder."""
from __future__ import annotations
import json
from collections import Counter
from fbp.ftypes import REGISTRY
def snapshot(conn, path: str) -> None:
"""Consistent point-in-time copy of the live database (SQLite >= 3.27)."""
conn.execute("VACUUM INTO ?", (path,))
def diff_exports(old: list[dict], new: list[dict]) -> dict:
"""Compare two exports of the same labels, keyed by item id."""
key = lambda r: r["meta"]["item_id"]
strip = lambda r: {k: v for k, v in r.items() if k != "meta"}
o, n = {key(r): strip(r) for r in old}, {key(r): strip(r) for r in new}
changed = sorted(k for k in o.keys() & n.keys() if o[k] != n[k])
return {"added": sorted(n.keys() - o.keys()), "removed": sorted(o.keys() - n.keys()),
"changed": changed, "changed_frac": len(changed) / max(1, len(o.keys() & n.keys()))}
def shadow_agreement(conn, prod_cid: str, shadow_cid: str) -> tuple[float, int]:
"""Agreement of majority canonical choices between a production campaign and a
shadow campaign (new UI or guideline) labelling the same prompts."""
ft = REGISTRY["pairwise"]
def majority(cid):
votes: dict[str, Counter] = {}
for item, label in conn.execute("""SELECT i.payload_json, l.payload_json FROM labels l
JOIN items i USING(item_id) WHERE l.campaign_id=? AND i.is_gold=0""",
(cid,)):
it = json.loads(item)
votes.setdefault(it["prompt_id"], Counter())[ft.canonical(it, json.loads(label))] += 1
return {p: c.most_common(1)[0][0] for p, c in votes.items()}
a, b = majority(prod_cid), majority(shadow_cid)
common = a.keys() & b.keys()
return sum(a[p] == b[p] for p in common) / max(1, len(common)), len(common)
if __name__ == "__main__": # CI: python -m fbp.replay --snapshot ... --shipped ...
import argparse, sys
from fbp import store
from fbp.export import export_campaign
import fbp.rubric # noqa: F401
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot"); ap.add_argument("--shipped"); ap.add_argument("--campaign")
ap.add_argument("--max-changed", type=float, default=0.0)
a = ap.parse_args()
shipped = [json.loads(line) for line in open(a.shipped)]
fresh, _ = export_campaign(store.connect(a.snapshot), a.campaign)
d = diff_exports(shipped, fresh)
print(json.dumps({k: (v if k == "changed_frac" else len(v)) for k, v in d.items()}))
sys.exit(1 if d["changed_frac"] > a.max_changed or d["added"] or d["removed"] else 0)
Staged rollout. Canary membership is a hash of a salt and the rater id, so a rater stays in one arm for a whole stage and different rollouts (different salts) choose independent canaries. verdict returns wait until each arm has 240 gold judgments, the 10-point-drop sample size from the Design level.
"""Staged rollout of a UI, guideline or feedback-type change: rung 4 of the test ladder."""
from __future__ import annotations
import hashlib
STAGES = [("internal", 0.0), ("canary", 0.05), ("half", 0.50), ("full", 1.0)]
LIMITS = {"min_gold": 240, # gold judgments per arm before any verdict
"gold_acc_drop": 0.10, # detectable at ~240 gold per arm (see text)
"time_ratio": (0.75, 1.33), # median seconds, canary / control
"error_rate": 0.01} # failed submissions / attempts
def in_canary(rater_id: str, fraction: float, salt: str) -> bool:
"""Stable assignment: a rater stays in the same arm for the whole stage."""
h = int(hashlib.sha256(f"{salt}:{rater_id}".encode()).hexdigest()[:8], 16)
return h / 0xFFFFFFFF < fraction
def verdict(canary: dict, control: dict, limits: dict = LIMITS) -> tuple[str, list[str]]:
"""'wait' (not enough data), 'halt' (with reasons) or 'advance'."""
if min(canary["gold_seen"], control["gold_seen"]) < limits["min_gold"]:
return "wait", [f"need {limits['min_gold']} gold judgments per arm"]
why = []
if control["gold_acc"] - canary["gold_acc"] > limits["gold_acc_drop"]:
why.append(f"gold accuracy {canary['gold_acc']:.3f} vs {control['gold_acc']:.3f}")
lo, hi = limits["time_ratio"]
r = canary["median_seconds"] / control["median_seconds"]
if not lo <= r <= hi:
why.append(f"median time ratio {r:.2f} outside [{lo}, {hi}]")
if canary["error_rate"] > limits["error_rate"]:
why.append(f"submit error rate {canary['error_rate']:.3%}")
return ("halt", why) if why else ("advance", [])
The ladder's tests. The replay test is the one to read closely: it exports, snapshots, re-exports with an identical hash, then monkey-patches canonical with the plausible "simplified" version and shows the diff flags about half the records.
import random
from fbp import quality, rollout, sampler, store
from fbp.export import export_campaign
from fbp.ftypes import Pairwise
from fbp.launch_check import preflight
from fbp.replay import diff_exports, shadow_agreement, snapshot
from fbp.simulate import SimRater, call, oracle, run
from tests.helpers import build, candidate_wins, w1_small
def labelled(tmp_path):
app, spec, clock = build(tmp_path)
raters = [SimRater(f"good{i}", "good", seed=i) for i in range(6)] + [SimRater("left1", "left", seed=9)]
run(app, "w1-test", raters, oracle(app.conn, "w1-test", candidate_wins))
quality.apply_removals(app.conn, quality.rater_report(app.conn, "w1-test"))
return app, spec, clock
def test_replay_reproduces_export_and_catches_position_bug(tmp_path, monkeypatch):
app, _, _ = labelled(tmp_path)
shipped, m1 = export_campaign(app.conn, "w1-test")
snapshot(app.conn, str(tmp_path / "snap.db"))
snap = store.connect(str(tmp_path / "snap.db"))
again, m2 = export_campaign(snap, "w1-test")
assert m1["sha256"] == m2["sha256"] and diff_exports(shipped, again)["changed"] == []
# a refactor "simplifies" canonical() and forgets the left/right randomisation
monkeypatch.setattr(Pairwise, "canonical", staticmethod(
lambda item, label: {"left": "a", "right": "b", "tie": "tie"}[label["choice"]]))
broken, _ = export_campaign(snap, "w1-test")
d = diff_exports(shipped, broken)
assert 0.3 < d["changed_frac"] < 0.7 # about half the pairs silently flip
def test_shadow_campaign_agrees_with_production(tmp_path):
app, spec, clock = labelled(tmp_path)
shadow = {**w1_small(), "campaign_id": "w1-shadow", "guideline_version": "w1-guide-1.3-draft"}
assert call(app, "POST", "/api/campaigns", shadow)[0] == 201
prompts = [{"prompt_id": f"p-{i:05d}", "text": f"Write a function for task {i}"} for i in range(300)]
models = {"a": sampler.StubModel("ckpt-current"), "b": sampler.StubModel("ckpt-candidate")}
sampler.fill_buffer(app.conn, shadow, prompts, models, n=300, now=clock[0], seed=99, sleep=lambda s: None)
run(app, "w1-shadow", [SimRater(f"staff{i}", "good", seed=50 + i) for i in range(4)],
oracle(app.conn, "w1-shadow", candidate_wins))
agree, n = shadow_agreement(app.conn, "w1-test", "w1-shadow")
assert n == 300 and agree > 0.75 # two 90%-accurate labels agree ~82%
def test_canary_assignment_is_stable_and_sized():
ids = [f"rater{i}" for i in range(10_000)]
arm = [rollout.in_canary(r, 0.05, "rubric-ui-v2") for r in ids]
assert 0.04 < sum(arm) / len(ids) < 0.06
assert arm == [rollout.in_canary(r, 0.05, "rubric-ui-v2") for r in ids]
def test_canary_verdicts():
ctl = {"gold_seen": 2500, "gold_acc": 0.86, "median_seconds": 240, "error_rate": 0.002}
assert rollout.verdict({**ctl, "gold_seen": 120}, ctl)[0] == "wait"
assert rollout.verdict({**ctl, "gold_seen": 260, "gold_acc": 0.83, "median_seconds": 255}, ctl)[0] == "advance"
v, why = rollout.verdict({**ctl, "gold_seen": 260, "gold_acc": 0.74, "median_seconds": 150}, ctl)
assert v == "halt" and len(why) == 2 # accuracy drop and suspicious speed-up
def test_preflight_passes_then_catches_unbalanced_gold(tmp_path):
app, _, _ = build(tmp_path)
assert all(ok for _, ok, _ in preflight(app.conn, "w1-test")), preflight(app.conn, "w1-test")
app.conn.execute("""UPDATE items SET payload_json=json_set(payload_json,'$.left_is_a',json('true'))
WHERE is_gold=1""")
failed = [name for name, ok, _ in preflight(app.conn, "w1-test") if not ok]
assert failed == ["gold answer position balanced"]
def test_runway_gauge_counts_open_slots(tmp_path):
from fbp.metrics import gauges
app, spec, clock = build(tmp_path, n_gold=0, overlap_fraction=0.0)
raters = [SimRater(f"good{i}", "good", seed=i) for i in range(3)]
hidden = oracle(app.conn, "w1-test", candidate_wins)
for k in range(60): # 60 labels spread over 15 minutes
r = raters[k % 3]
_, task = call(app, "GET", "/api/campaigns/w1-test/next", headers={"X-Rater-Id": r.id})
label, _ = r.answer(task["item"], hidden)
call(app, "POST", "/api/labels", {"assignment_id": task["assignment_id"], "payload": label,
"seconds": 200}, {"X-Rater-Id": r.id, "Idempotency-Key": f"k{k}"})
clock[0] += 15
g = gauges(app.conn, "w1-test", clock[0])
assert g["label_slots_open"] == 300 - 60 and g["labels_per_min"] == 4.0
assert g["runway_min"] == 60.0 and 0.3 < g["left_share"] < 0.7
Client tests. The browser client's retry logic is tested in Node with a fake fetch: network errors and 5xx responses are retried with the same idempotency key, and a 422 is not retried.
// Run: node --experimental-strip-types --test test/api.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import { submitLabel } from "../src/api.ts";
type Call = { key: string | null };
function fakeFetch(script: Array<number | "network">, calls: Call[]) {
return async (_url: string, init: { headers: Record<string, string> }) => {
calls.push({ key: init.headers["Idempotency-Key"] ?? null });
const step = script.shift()!;
if (step === "network") throw new TypeError("fetch failed");
return new Response(JSON.stringify(step < 300 ? { label_id: "lb-1", replayed: false } : { error: "bad" }),
{ status: step });
};
}
test("retries 5xx and network errors with the same idempotency key", async () => {
const calls: Call[] = [];
(globalThis as any).fetch = fakeFetch(["network", 503, 201], calls);
const r = await submitLabel("r1", "as-1", { choice: "left", strength: "clear" }, 200, "key-1");
assert.equal(r.label_id, "lb-1");
assert.deepEqual(calls.map((c) => c.key), ["key-1", "key-1", "key-1"]);
});
test("does not retry a 422 validation error", async () => {
const calls: Call[] = [];
(globalThis as any).fetch = fakeFetch([422, 201], calls);
await assert.rejects(submitLabel("r1", "as-1", { choice: "left" }, 200, "key-2"), /bad/);
assert.equal(calls.length, 1);
});
Continuous integration. Rungs 1 and 2 run on every pull request. The replay step needs a snapshot and the shipped export from the last production run; the exit code is non-zero if any record was added, removed or changed. (This workflow file is provided as configuration; its commands were run locally for this chapter, not in a hosted CI service.)
# .github/workflows/fbp.yml — rungs 1 and 2 run on every change; rung 2 needs the frozen snapshot.
name: fbp
on: [pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: {python-version: "3.13"}
- uses: actions/setup-node@v4
with: {node-version: "22"}
- run: pip install pytest
- run: python -m pytest # rung 1: unit, API, contract; rung 2 on fixtures
- run: cd ui && npm install @types/react@18 typescript && npx tsc -p .
- run: cd ui && node --experimental-strip-types --test test/api.test.ts
- name: replay against the last shipped export # rung 2 on production data
run: python -m fbp.replay --snapshot snapshots/w1.db --shipped exports/w1.jsonl --campaign w1-coding-pref-v1
Debugging tips. If replay reports changes on an unmodified codebase, the export is not deterministic: look for dictionary iteration order, timestamps or random ids inside records. If shadow agreement is far above production's own agreement, the shadow raters may be seeing production labels (for example, through a shared review screen). If every canary stage waits forever, the gold rate in the canary arm is too low for the gate's sample size.
The ladder becomes an operational process with owners, artefacts and stop rules. Each rung produces an artefact that the next rung's reviewer reads: test results, a replay diff, a shadow report, a canary verdict log.
| Rung | Required for | Pass criterion | Artefact |
|---|---|---|---|
| 1 Unit/contract | every change | all tests pass, type-check clean | CI log |
| 2 Replay | every change touching store, ftypes, export | 0 changed records, or exactly the predicted change | diff summary in the pull request |
| 3 Shadow | interface, guideline, feedback type | agreement with production ≥ production's own agreement minus the pre-set margin; median time within ±25% | shadow report: agreement, time, rater comments |
| 4 Canary | same as rung 3, at scale | verdict = advance at each stage | stage log with metrics per arm |
Change. W1 guideline 1.3 adds a rule that "a response that does not run is always worse" and a new layout that puts both responses in tabs instead of side by side. It passes rungs 1 and 2 (no code path to data changed) and a 300-item shadow campaign with staff, whose agreement with production is 0.70 (production's own agreement is 0.72, inside the 0.051 half-width).
Canary. At the 5% stage the gold rate inside the canary arm is raised to 20% so each arm reaches 240 gold judgments. After 240 gold per arm, gold accuracy is 0.85 in the canary and 0.86 in control (within 0.10), but median time per label is 151 s in the canary versus 240 s in control, a ratio of 0.63, outside [0.75, 1.33]. verdict returns halt.
Diagnosis. Per-rater left-tab dwell time (instrumented in the new layout) shows that canary raters spend a median 12 s on the second tab: with tabs, many raters read one response and skim the other. Gold accuracy did not move because gold pairs contain an obvious bug that can be spotted in either tab. Staff in the shadow campaign read both tabs because they knew they were evaluating the layout.
Remedy and cost. Revert the layout, keep the guideline rule, and repeat the canary. Reaching 240 gold judgments at a 20% gold rate took the canary arm (about 7 raters) roughly 1,200 assignments, about $3,600 at $3.00 per assignment; its roughly 960 real labels are excluded from export (the canary arm's labels are tagged with the stage id) and their items re-queued, about 3.6% of W1's 26,447 assignments.
Validation. The diagnosis is supported if the repeated canary with the side-by-side layout shows a time ratio near 1.0 with the same guideline. It is weakened if the time ratio stays low, which would point at the guideline rule itself (raters checking only whether code runs).
Runbook: a canary stage halts.
- Stop assigning the canary variant (set the rollout fraction to 0). Raters in the canary arm receive control tasks on their next request.
- Tag all labels from the canary arm with the stage id; exclude them from export until the investigation is closed.
- Read the halt reasons from
verdict. If the reason is gold accuracy, inspect which gold items the canary missed. If it is time ratio, compare per-rater distributions, not just medians: a few very fast raters can move a median. - Decide: revert (default), fix and re-run from rung 3, or accept with a written rationale if the halt was a known, intended effect (for example, a new rule that is meant to make tasks slower).
- If labels were excluded, re-queue their items so the campaign still reaches its target.
Launch and run: first campaigns, on-call, the incidents to expect
What launching means here. Launching a campaign is the moment paid people start producing data that will be trained on. Before it, every mistake is cheap: a spec can be edited, a guideline rewritten, a bug fixed. After it, mistakes cost rater hours, and mistakes that reach export cost model quality. Launch is therefore an ordered sequence of gates, each of which must pass before more people and more money are committed.
The ordered steps.
- Preflight. Automated checks that the campaign can run: the spec validates and fits the budget; the item buffer is filled; the gold pool is large enough that no rater sees the same gold twice and balanced so that the correct answer is on the left about half the time; gold prompts do not also appear as real prompts; an export dry run passes the data contract; model endpoints and the label API respond.
- Internal pilot. A few staff members who know the research goal label a small batch, typically a few hundred items with overlap. The goal is not data; it is finding guideline gaps (items where staff disagree for reasons the guideline does not address) and interface defects. Guidelines are revised and the pilot repeated until staff disagreements are about genuinely hard items.
- Calibration with the real population. A small cohort of the actual raters labels a batch with a high gold rate. Their gold results calibrate the threshold (is 80% achievable by careful raters on this gold set?) and expose gold that is too easy (everyone at 100%) or ambiguous (careful raters split).
- Open the pool with gold warm-up. All raters start; each receives gold at a raised rate until judged. Removal decisions start as soon as raters have enough gold.
- Steady state. Daily quality review, daily (or more frequent) export, continuous dashboards, and an on-call person who owns rater-facing availability and data correctness.
What on-call owns. On a data platform, on-call covers two kinds of failure. Availability failures stop raters working: the task endpoint is slow or failing, the buffer is empty, a model endpoint is down. They are urgent because idle raters cost money by the minute. Correctness failures let raters work while producing bad data: a broken position mapping, leaked gold answers, a guideline misunderstanding spreading through a vendor team. They are less urgent by the minute but more expensive in total, because bad data can reach training.
The incidents to expect. Teams that run first campaigns tend to meet the same set: gold that fails preflight because every correct answer is on one side; low agreement in the pilot from guideline gaps; raters who always choose the same side, caught by gold; gold so easy that every rater scores 100%, which makes removal meaningless; a surge of task requests at shift start; an empty buffer when a model endpoint fails; gold answers shared among raters; and an export that breaks a downstream contract after a schema change. Each has a detection signal and a first response, listed at the Operate level.
W1's preflight checks a buffer of 2,000 items, a gold pool of at least 54 items (three times a conservative bound of 18 gold items per rater: 10 warm-up gold plus 160 real labels × 5%; the exact expected exposure from the first section's Design level is 16.3), and gold with the correct answer on the left close to half the time. The internal pilot labels 200 items × 3 staff. Calibration runs one vendor team at a raised gold rate. Opening the pool lets 150 raters work with 20% gold until each has seen 10 gold items. Collection then needs about 1,984 rater-hours against a pool of 3,000 per week.
Compared with a software launch. A software launch can usually be rolled back and its users barely notice. A campaign launch cannot be fully rolled back: labels produced under a broken setup are paid for and must be discarded, and raters who learned a wrong rule must be retrained. This is why the pilot and calibration steps exist and why they use people who are cheaper to correct (staff) or fewer (a cohort).
What you would actually do. Never skip preflight or the pilot, even for a repeat campaign; most first-day incidents come from gold and guidelines, which change every campaign. Rehearse the two availability incidents (endpoint outage, shift-start surge) before launch, because they are the ones that need action within minutes.
Collection capacity. Collection time is total assignment time divided by pool capacity. For W1 this is a sizing check, not a schedule: the pool must be large enough that collection does not dominate request-to-mix latency.
Capacity. W1's 26,447 assignments × 4.5 min ≈ 1,984 rater-hours (1,895 for the baseline plan plus 89 for gold warm-up), against 3,000 rater-hours per week: about 0.66 of a week of the pool.
Gold exposure and leak risk. Total gold assignments are about 1,263 (5% of the baseline) plus 1,184 (warm-up) ≈ 2,447. With the minimum pool of 54 gold items, each gold item is shown to about 2,447 / 54 ≈ 45 different raters. If one rater posts a gold item's answer in a team chat, up to 45 raters could recognise it. With a pool of 300 gold items, each is shown about 8 times, and a single leak is worth far less.
Buffer runway. At shift start, suppose 120 of the 150 raters are active at once (an assumption; vendor shift patterns vary). They issue 120 / 4.5 ≈ 26.7 assignments per minute, of which 95% are real: 25.3 real labels per minute. W1's 2,000-item buffer holds about 2,000 × 1.2 = 2,400 label slots (overlap items take three labels), so runway is 2,400 / 25.3 ≈ 95 minutes if generation stops. (Chapter 11's 60-minute figure for the same buffer counts one label per pair at the full 150-rater rate of 33.3 per minute; counting overlap slots and 120 active raters gives the longer runway here.)
Runway formula. Let \(S\) be open label slots, \(r\) active raters, \(t\) mean minutes per label and \(g\) the gold rate. Real labels are consumed at \(c = r(1-g)/t\) per minute and the runway is \(T = S / c\). The buffer target follows from the outage the platform must ride out: \(S_{\text{target}} = c_{\text{peak}} \times T_{\text{outage}}\). For a 4-hour outage at W1's peak (an assumption for the outage duration), \(S = 25.3 \times 240 \approx 6{,}070\) slots, about 5,060 items, two and a half times the current buffer.
The cost of a large buffer. Pre-generated items are tied to the checkpoints that produced them. If the candidate checkpoint is replaced, unlabelled items from the old checkpoint become off-policy, and the campaign must either discard them or label them knowing they describe an older model (Chapter 4). A buffer of about 5,000 items (6,000 label slots) that turns over in about 4 hours of peak consumption loses little; one that sits for days loses much more.
Request-to-mix. W1's baseline request-to-mix latency is 21 days: scoping 3, guidelines and pilot 4, collection 6, QA 3, pipeline and export 2, reward-model retraining and mix inclusion 3. The minimal platform attacks the stages that are platform work: the spec template and preflight shorten scoping; continuous gold-based quality runs during collection instead of after it; contract-checked export removes the separate pipeline stage. The 7-day target follows the plan of record from Chapter 8's value-stream analysis: scoping 0.5 day from a template, a 1-day pilot (here including calibration), collection 4.0 days with about 10.5% more scheduled rater-hours (about 474 a day instead of 429), QA and export streaming behind collection and finishing a quarter-day each after it, and a pre-booked 1-day retraining slot, 7.0 days in total. The gold warm-up of this chapter adds about 89 rater-hours (1,984 instead of 1,895), which at 474 rater-hours a day lengthens collection to about 4.2 days unless roughly 5% more hours are scheduled (about 496 a day). The collection figure assumes the pool's capacity is available to this campaign; retraining time is outside this platform and must shrink separately.
| Launch decision | Default | Deviate when |
|---|---|---|
| Gold pool size | ≥ 3 × a rater's expected gold exposure, and large enough that each item is seen by few raters | raters work in tight teams that share notes: enlarge and rotate |
| Buffer target | peak consumption × the outage duration to survive | checkpoints change faster than the buffer turns over |
| Pilot size | a few hundred items with overlap, staff only | repeat campaign with an unchanged guideline: a smaller pilot |
| Export cadence | daily, with manifest | researchers need early signal: more frequent partial exports |
What you would actually do. Size the buffer from the outage you intend to survive, size the gold pool from exposure, and budget collection from rater-hours rather than calendar time.
Launch is driven by three pieces of code: preflight checks, operational gauges, and alert rules over those gauges. The preflight function returns one line per check; every check must pass before the campaign status moves to live. The gold-position check exists because a gold set whose correct answers are all on the left would let an always-left rater pass every gold item.
"""Pre-launch checks. Every check must pass before a campaign goes live."""
from __future__ import annotations
import json
from fbp.export import ContractError, export_campaign
from fbp.ftypes import REGISTRY
from fbp.spec import CampaignSpec, validate
def preflight(conn, campaign_id: str, health=lambda: True) -> list[tuple[str, bool, str]]:
raw = json.loads(conn.execute("SELECT spec_json FROM campaigns WHERE campaign_id=?",
(campaign_id,)).fetchone()[0])
spec, out = CampaignSpec(**raw), []
add = lambda name, ok, detail: out.append((name, bool(ok), detail))
errs = validate(spec, set(REGISTRY))
add("spec valid", not errs, "; ".join(errs) or "ok")
n_items = conn.execute("SELECT count(*) FROM items WHERE campaign_id=? AND is_gold=0",
(campaign_id,)).fetchone()[0]
need = min(spec.buffer_target, spec.target_items)
add("buffer filled", n_items >= need, f"{n_items} of {need} items ready")
golds = [json.loads(r[0]) | {"answer": json.loads(r[1])} for r in conn.execute(
"SELECT payload_json, gold_json FROM items WHERE campaign_id=? AND is_gold=1", (campaign_id,))]
per_rater = spec.min_gold_seen + spec.labels_needed() / spec.expected_raters * spec.gold_rate
add("gold pool size", len(golds) >= 3 * per_rater,
f"{len(golds)} gold items; need >= {3 * per_rater:.0f} (3x a rater's expected exposure)")
if spec.feedback_type == "pairwise" and golds:
left = sum((g["answer"] == "a") == g["left_is_a"] for g in golds) / len(golds)
add("gold answer position balanced", 0.4 <= left <= 0.6,
f"{left:.0%} of gold answers on the left (an always-left rater would score this)")
real = {r[0] for r in conn.execute("""SELECT json_extract(payload_json,'$.prompt') FROM items
WHERE campaign_id=? AND is_gold=0""", (campaign_id,))}
leaked = sum(g["prompt"] in real for g in golds)
add("gold prompts distinct from real", leaked == 0, f"{leaked} gold prompts also in the real pool")
try:
_, m = export_campaign(conn, campaign_id)
add("export dry run", True, f"{m['n_records']} records pass the contract")
except ContractError as e:
add("export dry run", False, str(e))
add("endpoints healthy", health(), "model endpoints and label API respond")
return out
The gauges are computed from the store and published by a small exporter each minute: open label slots, real labels per minute over the last 15 minutes, runway in minutes, and the share of left choices.
"""Operational gauges computed from the store; an exporter publishes these every minute."""
from __future__ import annotations
import json
def gauges(conn, campaign_id: str, now: float, window_s: float = 900) -> dict:
slots = conn.execute("""
SELECT coalesce(sum(i.target_labels), 0) - (SELECT count(*) FROM assignments a
JOIN raters r USING(rater_id) JOIN items j USING(item_id)
WHERE a.campaign_id=:c AND j.is_gold=0 AND a.status IN ('open','done') AND r.status='active')
FROM items i WHERE i.campaign_id=:c AND i.is_gold=0""", {"c": campaign_id}).fetchone()[0]
recent = conn.execute("""SELECT count(*) FROM labels l JOIN items i USING(item_id)
WHERE l.campaign_id=? AND i.is_gold=0 AND l.submitted_at>=?""",
(campaign_id, now - window_s)).fetchone()[0]
per_min = recent / (window_s / 60)
sides = [json.loads(p).get("choice") for (p,) in conn.execute(
"SELECT payload_json FROM labels WHERE campaign_id=? AND submitted_at>=?", (campaign_id, now - window_s))]
lr = [s for s in sides if s in ("left", "right")]
return {"label_slots_open": slots, # labels still to be issued
"labels_per_min": round(per_min, 2),
"runway_min": round(slots / per_min, 1) if per_min else None,
"left_share": round(lr.count("left") / len(lr), 3) if lr else None}
The test for the gauges (in tests/test_ladder.py) posts 60 labels over 15 simulated minutes and checks 240 open slots, 4.0 labels per minute and a runway of 60.0 minutes.
Alert rules. Expressed in Prometheus rule syntax over the gauges and over API counters (fbp_next_seconds, fbp_submit_total by status code) that the service must export; the minimal service does not yet emit those counters, so adding them is part of launch preparation.
# Prometheus-style alert rules over the gauges in fbp/metrics.py and API status counters.
groups:
- name: fbp-campaign
rules:
- alert: BufferRunwayLow # raters will run out of work
expr: fbp_runway_min < 60 and fbp_labels_per_min > 1
for: 5m
labels: {severity: page}
- alert: TimeToFirstSampleSlow
expr: histogram_quantile(0.95, rate(fbp_next_seconds_bucket[10m])) > 5
for: 10m
labels: {severity: page}
- alert: SubmitErrors # 5xx share of label submissions
expr: sum(rate(fbp_submit_total{code=~"5.."}[5m])) / sum(rate(fbp_submit_total[5m])) > 0.01
for: 5m
labels: {severity: page}
- alert: PositionMappingSuspect # balanced items should split near 50/50 by screen side
expr: abs(fbp_left_share - 0.5) > 0.15
for: 30m
labels: {severity: ticket}
- alert: ConflictSpike # clients re-sending answers with new keys
expr: sum(rate(fbp_submit_total{code="409"}[15m])) / sum(rate(fbp_submit_total[15m])) > 0.02
for: 15m
labels: {severity: ticket}
- alert: ExportStale
expr: time() - fbp_last_export_timestamp > 86400
labels: {severity: ticket}
Launch sequence as commands. With the service running, an operator launches a campaign in this order:
# 1. create the campaign from its spec (422 with reasons if invalid)
curl -s -X POST localhost:8080/api/campaigns -H 'Content-Type: application/json' --data @w1_campaign.json
# 2. fill the buffer and load gold (sampler.fill_buffer, store.add_item with gold=...)
# 3. preflight: every line must be PASS
python3 -c "from fbp import store; from fbp.launch_check import preflight; import fbp.rubric
for n, ok, d in preflight(store.connect('w1.db'), 'w1-coding-pref-v1'): print('PASS' if ok else 'FAIL', n, d)"
# 4. pilot and calibration: staff, then one vendor cohort; review GET /api/campaigns/<id>/quality
# 5. open the pool; export daily with export_campaign(..., out_path) and keep each manifest
The end-to-end run in demo.py (output shown in the first section) exercises steps 1–5 on the scaled-down campaign: all seven preflight checks pass, the two bad raters are removed, their items are relabelled and the export covers every item.
Debugging tips. A runway gauge that reads None means no labels arrived in the window: either raters are idle (check task latency and 204 responses) or the window started before the shift. A left-share near 0.5 overall with one rater near 1.0 is a single position-biased rater, not a mapping bug; a mapping bug moves the exported chosen-side share, not raters' click share.
SLOs for a live campaign.
| Objective | Target (W1) | Alert | Owner action |
|---|---|---|---|
| Time to first sample | p50 ≤ 2 s, p95 ≤ 5 s | p95 > 5 s for 10 min | page; check task query and endpoint health |
| Submit success | ≥ 99.95% excluding 422 | 5xx > 1% for 5 min | page; raters' answers are held in the browser meanwhile |
| Buffer runway | ≥ 60 min during shifts | < 60 min for 5 min | page; runbook below |
| Data correctness | left share 0.5 ± 0.15; 409 rate < 2% | ticket | investigate before next export |
| Export freshness | < 24 h, 0 contract errors | ticket | re-run export; fix contract break |
Timeline (illustrative). The W1 candidate checkpoint's endpoint starts returning 503 at 09:00, just as the morning shift brings 120 raters online. Buffer fill stops; raters keep working from the buffer's 2,400 label slots at 25.3 real labels per minute.
Detection. Runway falls below 60 minutes when about 1,520 slots remain, (2,400 − 1,520) / 25.3 ≈ 35 minutes into the outage; the BufferRunwayLow alert fires after its 5-minute hold, around 09:40. Without the alert, the first signal is raters receiving 204 responses when the buffer empties at about 10:35.
Cost if nothing is done. If the endpoint recovers at 12:20, raters have no work for 105 minutes: 120 × 105 / 60 = 210 rater-hours, about $8,400 at $40/h if the vendor bills staffed idle time (contracts differ; this is an assumption). Refill after recovery takes further time because generation must catch up with demand.
Remedies, in order of preference.
- Fail over the endpoint. If a second replica of the candidate checkpoint exists, point the sampler at it. Cost: the standby capacity. Best when outages are host failures.
- Serve a reserve buffer. Keep a separate pool of items generated from the previous candidate checkpoint, tagged
reserve, used only when runway drops below 30 minutes. Exports carry the tag so researchers can weight or drop these pairs. Cost: some off-policy data and generation compute. - Release raters early. Tell the vendor by the time runway reaches about 30 minutes, under the contract's notice terms. Cost: lost collection time, but no idle billing.
Lasting fix. Resize the buffer from the outage the platform intends to survive (the Design level computed about 6,070 slots for 4 hours at peak) and add the reserve pool. Cost: about 3,060 more pre-generated pairs and their staleness risk if the candidate changes.
Validation. Rehearse the outage in staging: stop the stub candidate endpoint for 2 hours while the simulator drives 120 raters. The fix is supported if runway never reaches zero and the alert fires at least 55 minutes before the buffer would have emptied; it is weakened if runway still reaches zero, which would mean consumption at shift start is higher than the 25.3 per minute used for sizing.
The first incidents and their first responses.
| Incident | Detection signal | First response |
|---|---|---|
| Unbalanced gold | preflight "gold answer position balanced" fails | re-randomise gold sides before launch |
| Guideline gaps | pilot agreement well below expectation; disagreements cluster in one item type | add a rule and examples; repeat pilot |
| Position-biased raters | per-rater left share above about 0.8; gold Wilson upper bound below threshold | remove via quality; their items are re-queued |
| Gold too easy | nearly all raters at 100% gold | replace with gold that careful raters get about 85–95% right |
| Shift-start surge | p95 time to first sample rises at shift boundaries | pre-fill buffer before shifts; check task query latency |
| Buffer drain | runway alert | runbook above |
| Gold leak | one gold item's accuracy jumps toward 100% while real-item agreement does not rise | retire the item; enlarge and rotate the pool; re-check affected raters |
| Duplicate submissions | 409 rate rises | check the client keeps one idempotency key per answer |
| Contract break | export raises ContractError | hold export; fix the producer, never the check |
Runbook: buffer runway alert.
- Check model endpoint health for both checkpoints. If one is failing and a replica exists, fail over; go to step 5.
- If generation is healthy but runway is falling, consumption exceeds generation: raise generation concurrency.
- If generation is down with no replica, enable the reserve buffer when runway drops below 30 minutes.
- If no reserve exists, notify the vendor contact with the expected empty time and agree release terms.
- After recovery, confirm runway rises above 60 minutes, record the outage duration (it feeds the next buffer sizing), and mark any reserve-served labels in the campaign log.
Landscape
The earlier chapters described a human-data platform in general terms: campaigns, sampling, interfaces, quality, pipelines and the path into the training mix. This chapter is the reference record of the outside world that platform sits in, as of 9 November 2026. It has four parts. The first covers the companies that supply annotators and experts. The second covers the annotation software a team can adopt rather than build. The third covers what model developers have published about how they collect and use human data. The fourth covers the public datasets that a team can study, use for a warm start or use for a pilot. Each part ends with what the record implies for a team designing its own platform.
Every fact comes from a page fetched for this chapter, and the source is linked where the fact appears. Claims carry one of five labels, stated or obvious from context. Vendor-stated: the company's own website, press release, filing or dataset card. Vendor marketing claims (pool sizes, "trusted by" statements, quality promises) are reported as claims and never as facts. Filed: a statutory filing such as an ASX results announcement. Reported: independent journalism (Forbes, TechCrunch, TIME, Reuters as carried by Yahoo Finance). Revenue and valuation figures for private companies are almost always reported from unnamed sources; they are given as reported, with the date. Analyst estimate: research firms such as Sacra or Dealroom, which mix sourced reporting with modelling. Inference: the author's reasoning from the cited facts. Private-company numbers move fast and are often gross figures (customer spend before contractor pay); treat every revenue figure here as dated and approximate. Six further vendors (micro1, Snorkel AI, iMerit, TELUS Digital, SuperAnnotate and Encord) get shorter entries after the main table; they are not placed in the grid figure.
Data vendors and expert networks
A frontier post-training team rarely employs all of its annotators. It buys labour, and often labelling software and project management with it, from vendors. Those vendors differ along two axes that matter to a platform designer. The first is the workforce tier: an open panel of screened members of the public, a managed workforce of trained raters, or credentialed experts (lawyers, physicians, PhD scientists, senior engineers) qualified by domain tests. The second is the delivery model. In a self-serve model the buyer designs the task, sets the pay and runs quality control on a vendor's marketplace. In a managed model the vendor sources, trains and reviews workers and delivers finished data against a statement of work. The grid below places the main vendors covered here on those two axes.
How the money works. Most of these companies report gross revenue, the full amount customers pay, of which the larger part passes through to contractors. Dealroom reports that Mercor pays 60–70% of its topline to contractors and that Handshake's contractor costs run at the same 60–70% of gross (Dealroom, 2026a; Dealroom, 2026b). Two consequences follow for a buyer (inference). First, a vendor's price per hour is roughly 1.4–1.7 times what the worker receives (1 ÷ 0.70 ≈ 1.43; 1 ÷ 0.60 ≈ 1.67). Second, the vendor's own margin is thin, so its incentives favour volume and repeat projects. Revenue is also concentrated: Sacra, an analyst firm, estimates that Surge AI's 2024 revenue of about $1.2B came mainly from about a dozen frontier labs (Sacra, 2025). When one buyer can move a large share of a vendor's revenue, ownership and neutrality become commercial issues, as the Scale AI entry shows.
| Vendor | Model and tier | Public numbers (date, source type) | Notable events and controversies |
|---|---|---|---|
| Scale AI (founded 2016, San Francisco) | Managed data labelling, with crowd platforms (Remotasks, Outlier) and enterprise/government applications | Revenue just under $1B in 2025, up from $870M in 2024; company expects above $1B in 2026; about 1,300 full-time staff (reported, Forbes, May 2026) | Meta bought 49% for about $14B (June 2025); several lab customers paused; former Google Cloud COO Francis deSouza named CEO (July 2026, reported); $12.5M worker-misclassification settlement, preliminarily approved (law-firm summary, 2026) |
| Surge AI (founded 2020) | Managed RLHF and expert data; work platform DataAnnotation | Over $1B revenue in 2024 (reported via Reuters, July 2025); about 50,000 expert contractors and 130 staff (analyst estimate, Sacra) | Bootstrapped; sought first outside round of up to $1B in July 2025 (reported); worker-misclassification class action (May 2025); two leaked internal guideline documents (July 2025) |
| Mercor | Expert marketplace billing labs for contractor time | Gross run rate above $2B in June 2026; implied net about $600–800M after the reported 60–70% contractor share; 30,000+ weekly active contractors (reported, Dealroom, July 2026); $10B valuation in Oct 2025 (reported) | Data breach via compromised LiteLLM package (31 March 2026); Meta paused contracts; five contractor lawsuits (reported); Scale AI trade-secret suit settled January 2026 (reported) |
| Handshake (founded 2013) | College career network that added an AI-training expert business | AI-training gross run rate nearly $1B (April 2026), up from $550M (January 2026); net near $300M (reported, Dealroom) | Customer concentration noted by the same report |
| Toloka (Amsterdam) | Crowd platform that moved into expert data, red-teaming and agent evaluation | $72M led by Bezos Expeditions (May 2025); Nebius gave up majority voting control but kept most of the economic stake (vendor-stated and reported); 200,000+ annotators and professionals in 40+ languages (reported) | Parent Nebius was formerly Yandex's parent (reported) |
| Prolific (UK) | Self-serve research panel plus managed AI-data service | 300,000+ active participants; platform fee typically 42.8% (corporate) or 33.3% (academic) on top of participant pay; minimum pay $8/h, recommended $12/h (vendor-stated, pricing page) | Publishes participant-verification statistics: 55% pass rate at onboarding (vendor-stated) |
| Appen (ASX: APX) | Long-standing crowd data company, now weighted to generative-AI projects | FY2025 revenue $230.8M; China $102.9M (+75%); Global $127.9M (−21% excluding Google); 1M+ contractors claimed (filed, Feb 2026) | Google contract terminated, affecting FY2024 (filed) |
| Turing (founded 2018) | Coding and STEM expert data for labs; enterprise AI applications | $111M Series E at $2.2B valuation, $167M annualised revenue run rate at pricing (March 2025, reported); 4M+ engineers and experts in network (vendor claim) | None found in fetched sources |
| Invisible Technologies | Expert RLHF data plus workflow software (Neuron, Atomic, Synapse) | $100M at over $2B valuation (Sept 2025; reported, SiliconANGLE citing Bloomberg); revenue $134M in 2024 (reported, SiliconANGLE) | None found in fetched sources |
| Labelbox | Labelling software plus Alignerr expert network; now markets RL environments and evaluations | "2.6M+ skill-tested experts" and use by "over 90%" of leading US labs (vendor marketing claims, unverified) | None found in fetched sources |
| Sama (historical case) | Managed workforce in Kenya, Uganda and India | OpenAI contracts of about $150–200K (2021–2022) at $12.50/h paid to Sama; worker take-home about $1.32–2/h (reported, TIME, 2023) | Toxic-content labelling for a safety classifier; Sama ended the work early and later exited NLP and content moderation (March 2023) |
Scale AI. Founded in May 2016, Scale became one of the leading managed-labelling vendors to model developers. In June 2025 Meta bought 49% of the company for about $14B, and co-founder and CEO Alexandr Wang left to lead Meta's superintelligence lab. Forbes reports that Meta agreed to pay Scale at least $450M a year for five years, or more than half of its annual AI spend, whichever is less. It also reports that OpenAI was the most significant customer lost and that Google dropped Scale and then resumed work a few months later (Nieva, Forbes, 2026). In July 2025 Reuters reported that OpenAI and Google were moving work away from Scale over concerns that Meta could see their research priorities (Reuters via Yahoo Finance, 2025). Scale's revenue was just under $1B in 2025, and the company says data labelling is still the "vast majority" of it. It also cut about 200 full-time staff, about 14% of its workforce, and ended work with 500 contractors from its corporate contract workforce rather than its per-task labellers. Reporting at the time dates the cut to mid-July 2025, about a month after the Meta deal, while the Forbes account places it in August (Verdict, 2025; Nieva, 2026). Jason Droege, previously chief strategy officer, led the company as interim CEO after Wang left. In July 2026 Scale named Francis deSouza, formerly chief operating officer of Google Cloud, as CEO; the company says its enterprise and government applications business will overtake data within about 18 months (Axios, 2026). On labour practice, the U.S. Department of Labor examined Scale's compliance with the Fair Labor Standards Act and dropped the investigation in May 2025 (TechCrunch, 2025). A California class action, McKinney v. Scale AI, alleged that contributors were misclassified as contractors. A summary by a plaintiff-side law firm reports a $12.5M settlement with preliminary approval, covering California contributors from December 2020 to February 2026; Scale denies the allegations. The same summary notes a separate suit by Outlier workers over exposure to disturbing prompts without adequate psychological safeguards (King & Siegel, 2026).
Surge AI. Founded in 2020 by Edwin Chen, Surge positions itself on quality for RLHF, RL environments and language data. Reuters reported over $1B in 2024 revenue, ahead of Scale's reported $870M, and a first fundraise of up to $1B at a valuation above $15B, sought in July 2025 (Reuters via Yahoo Finance, 2025). Bloomberg later reported talks at a valuation of at least $25B; the sources fetched here do not confirm that the round closed (Wikipedia, citing Bloomberg; Sacra, 2025). Reporting summarised on Wikipedia links Surge to several work platforms, including DataAnnotation, and to a May 2025 class action alleging that annotators were deliberately misclassified as contractors. In July 2025 two internal documents leaked: a set of training and safety guidelines, and a list of websites contractors could and could not use when working on one lab's models (Wikipedia, citing Inc. and Business Insider). Sacra estimates contractor pay at 30–40 cents per working minute, or about $18–24 per hour (analyst estimate).
Mercor. Mercor runs a two-sided marketplace: labs and enterprises pay for time from domain experts who write questions, answers, rubrics and other specialised data. Dealroom reports a gross annualised run rate above $2B in June 2026, double the rate at the start of the year, with 30,000+ weekly active contractors and more than $2M paid out per day. It raised $350M at a $10B valuation in October 2025 (Dealroom, 2026a). On 31 March 2026 Mercor disclosed a breach. A popular open-source LLM proxy, LiteLLM, briefly shipped credential-harvesting malware, and stolen credentials were used to reach further systems. A hacker group claimed to have taken 4 TB of data; Mercor had not confirmed the volume or authenticity of that claim. Wired reported that Meta paused its Mercor contracts indefinitely, and Business Insider reported five contractor lawsuits (TechCrunch, 2026a). Forbes reports that Scale's lawsuit against Mercor, over a former Scale employee who allegedly took trade secrets, settled in January 2026 (Nieva, 2026).
Handshake started in 2013 as a career network for college students and graduates and added an AI-training business that supplies lawyers, PhDs and physicians to labs. Its AI-training gross run rate reportedly went from $5–10M shortly after launch to nearly $1B by April 2026 (Dealroom, 2026b). Toloka began as a crowdsourcing platform and now sells expert datasets, red-teaming and agent-safety evaluation. In May 2025 Bezos Expeditions led a $72M investment. Nebius, the former parent of Yandex, gave up majority voting control while keeping a significant majority of the economic stake. Toloka names Amazon, Anthropic, Microsoft, poolside, Recraft and Shopify as customers (Nebius, 2025; SiliconANGLE, 2025a). Turing raised $111M at a $2.2B valuation in March 2025 and reported a $167M annualised run rate at the time. It works with labs on coding and reasoning data and claims a network of more than four million engineers and STEM experts (Pulse 2.0, 2025). Invisible Technologies raised $100M at a valuation above $2B in September 2025. It reported $134M in 2024 revenue and sells expert RLHF data alongside workflow software (SiliconANGLE, 2025b).
Prolific is the clearest self-serve option. A researcher sets participant pay (minimum $8/h, recommended at least $12/h) and pays a platform fee on top, usually 42.8% for companies and 33.3% for academic customers. Prolific also offers managed RLHF and evaluation collection (Prolific, 2026). It publishes unusually specific integrity statistics, all vendor-stated. New participants pass more than 50 identity and behavioural checks, with a 55% pass rate. Periodic video-selfie checks continue after onboarding. A free authenticity check flags AI-generated text with 98.7% precision; no recall figure is given. More than 11,000 participants are designated "AI taskers." Its HUMAINE leaderboard collected over 100,000 comparisons from nearly 27,000 evaluators (Prolific, 2025). Appen is the only vendor here with audited public accounts. It reported FY2025 revenue of $230.8M, with growth in China driven by LLM projects and a 21% decline outside China excluding the terminated Google contract (Appen, 2026). Its revenue is a useful reality check: the largest listed incumbent is a fraction of the reported size of the private expert-data companies above (inference from the cited figures). Labelbox now describes itself as a builder of RL environments and evaluations for labs, with an expert network called Alignerr; the network size and lab-adoption figures on its homepage are marketing claims (Labelbox, 2026).
Sama is included as a case that shaped welfare norms across the industry. TIME reported that in 2021–2022 Sama workers in Kenya labelled tens of thousands of text passages, including graphic content, to train a toxicity detector for OpenAI. OpenAI's contracts paid Sama $12.50 per hour; workers took home about $1.32–2 per hour by TIME's account, or $1.46–3.74 after tax by Sama's. Sama ended the work eight months early and in January 2023 announced it would leave natural-language and content-moderation work (TIME, 2023). Three practices common in later lab papers answer this case directly. One is a policy of paying at least a living wage for the worker's location. Another is letting workers skip sensitive tasks without penalty. A third is setting data budgets for harmful topics; the Sparrow paper states all three (Glaese et al., 2022, below).
Other vendors in brief. Six more companies recur in lab procurement and in reporting on the sector. The entries are shorter because less is public; every figure is as reported or vendor-stated, with the date.
| Vendor | Model and tier | Public numbers (date, source type) | Notable events |
|---|---|---|---|
| micro1 (founded 2021, Palo Alto) | Expert marketplace for lab training data, with AI-run screening of domain experts; also building simulated-workplace RL environments and robotics data | About $7M annual revenue in early 2025 from an earlier business; above $100M annualised by December 2025; $500M gross run rate in August 2026 (reported, Forbes citing TechCrunch); about $1B annualised by October 2026 (analyst estimate, Sacra) | $35M Series A at $500M valuation (Sept 2025); a round of more than $100M at a $4B valuation (Sept 2026, reported from two unnamed sources; the company declined to comment) |
| Snorkel AI (Stanford spin-out; commercial since 2019) | Moved in 2025 from labelling-automation software to delivering finished expert datasets and environments ("Expert Data-as-a-Service", launched Sept 2025), mixing synthetic data with subject-matter experts | $350M Series E at $3.5B, led by Insight Partners and S32; run rate above $375M, more than 18× in under a year (Sept 2026, vendor-stated and reported) | Says expert pay is booked as cost of goods sold, so its revenue figure is not directly comparable with marketplace gross run rates (reported, TechCrunch) |
| iMerit | Managed annotation workforce plus the Ango Hub software; "Scholars", an invite-only expert network for generative-AI tuning | "Thousands" of specialists, many with advanced degrees (vendor-stated, July 2025); no revenue disclosed | None found in fetched sources |
| TELUS Digital (Vancouver) | Customer-experience outsourcer whose AI-data unit grew from the Lionbridge AI acquisition (agreed 2020, US$935M); managed collection, annotation, red-teaming and expert post-training data | 1M+ contributor community, 500+ languages and dialects, 2B+ labels a year (vendor claims); taken private by parent TELUS for about US$539M (completed 31 Oct 2025) | Breach confirmed March 2026 after an extortion group claimed nearly 1 PB of data and demanded $65M (reported) |
| SuperAnnotate (San Francisco) | Platform for building and evaluating training datasets, with a marketplace of annotation teams | $36M Series B led by Socium Ventures with Nvidia and Databricks Ventures; just over $53M raised in total; about 100 customers (Nov 2024, reported) | None found in fetched sources |
| Encord | Data platform for curating, annotating and evaluating multimodal data, aimed at physical AI (robots, vehicles, drones) | $60M Series C led by Wellington Management; $110M raised in total; 300+ AI teams (Feb 2026, reported and vendor-stated) | None found in fetched sources |
micro1 is the fastest-growing entrant in the reported record. Forbes reports that it moved in 2025 from its earlier business to supplying expert-created training data for frontier labs, using an AI system to screen engineers, physicians, lawyers and other experts, and that it is building "RL gyms", simulated workplaces built from enterprise data. Its run rate went from about $7M in early 2025 to above $100M by December 2025 and a reported $500M gross by August 2026. The round at a $4B valuation, about eight times its September 2025 valuation, comes from two unnamed sources; micro1 declined to comment (Tong, Forbes, 2026). Sacra estimates about $1B annualised by October 2026 and describes revenue as a markup on expert labour plus vetting, workflow, quality-assurance and payroll services (Sacra, 2026). Snorkel AI came out of a Stanford research project on programmatic labelling and sold labelling-automation software until 2025. It now sells finished datasets, benchmarks and agentic environments to labs. In September 2026 it raised $350M at $3.5B, nearly triple its valuation 17 months earlier, and said its run rate exceeded $375M (TechCrunch, 2026b; Snorkel AI, 2026). The same TechCrunch report sets Snorkel's figure beside the gross run rates of Mercor, Handshake and micro1, which pass 60–70% to experts, and notes Snorkel's statement that expert pay sits in its cost of goods sold. A buyer comparing vendors by size should therefore ask whether a figure is gross billings or revenue net of pass-through pay (inference). iMerit launched Scholars in July 2025: an invite-only network of subject-matter experts for model tuning, run on the Deep Reasoning Lab module of its Ango Hub software, which links automated pipelines, model evaluators and expert judgment (iMerit, 2025). TELUS Digital is the largest outsourcing group in this list. Its AI-data business traces to the 2020 Lionbridge AI acquisition and the 2021 purchase of Playment (Wikipedia, Telus Digital). Parent TELUS completed its purchase of the shares it did not already own on 31 October 2025 (TELUS, 2025). Its AI-data pages claim a community of more than a million contributors and more than two billion labels a year (TELUS Digital, 2026). In March 2026 it confirmed unauthorised access to "a limited number of systems" after the ShinyHunters group claimed nearly a petabyte of data and demanded $65M. The group said it had used Google Cloud credentials found in the 2025 Salesloft Drift breach; that path was not independently verified (TechRadar, 2026). SuperAnnotate and Encord sell platforms rather than workforces. SuperAnnotate began as labelling software, now covers dataset building, evaluation and fine-tuning workflows, and offers a marketplace of annotation teams (TechCrunch, 2024). Encord targets multimodal and physical-AI data (video, sensor data, 3D point clouds) across curation, annotation, evaluation and alignment (Pulse 2.0, 2026).
Patterns. (1) The spend is moving to the expert tier. Every fast-growing company in the two tables sells credentialed experts or expert-built datasets, and the reported growth figures for Mercor, Handshake, micro1 and Snorkel are measured in months. The crowd tier remains, but it is where Appen's revenue sits (inference from the cited figures). (2) Neutrality is a procurement requirement. The Scale–Meta deal showed that a vendor which sees a lab's prompts, rubrics and failure taxonomies is a channel for that lab's research priorities, and buyers reacted within weeks. (3) Classification and pay are live legal risks. Scale and Surge both faced misclassification suits; Scale's was settled for $12.5M. (4) Vendors are part of the security perimeter. The Mercor breach came through a third-party dependency, not a targeted attack on the lab, yet it exposed data about the work done for labs. The TELUS Digital breach, by the attackers' account, used cloud credentials taken in an earlier breach of another supplier. (5) Quality claims are mostly unaudited. Apart from Prolific's verification statistics and Appen's filings, the numbers vendors publish are pool sizes and adoption claims, not measured agreement or accuracy.
W1 (20,000 coding comparisons, 25,260 assignments at a mean of 4.5 minutes, about 1,895 rater-hours) budgets a managed vendor at $40/h, or about $75,780 in labour. Against a self-serve panel at the recommended $12/h plus a 42.8% fee, the same hours would cost 1,895 × $12 × 1.428 ≈ $32,470. The cheaper line omits what the $40 buys: pre-trained raters, a vendor reviewer tier and a single contract. It also assumes the panel can sustain the same 4.5-minute time per label on coding prompts, which the W1 pilot would have to show. The comparison is illustrative arithmetic, not a quote from either kind of vendor.
W2 (expert transcript review at $120/h billed) through a marketplace that passes 60–70% of gross to contractors implies expert pay of about $72–84/h. If double-review disagreement on the first failing step stays at the W2 baseline (exact 58%), raising pay is not the obvious lever. The guidelines and the step-navigation interface are, because agreement within ±2 steps is already 81%.
What a platform team does with this. Treat vendor choice as a multi-vendor routing problem, not a single contract. Run each new campaign as a small pilot with two vendors on the same gold set before committing volume. The due-diligence questions below follow directly from the public record above.
| Question to ask a vendor | Why (public event it answers) | Evidence that should satisfy it |
|---|---|---|
| Who owns you, and which model developers do you also serve? | Scale–Meta stake and the customer pauses that followed | Cap table disclosure; contractual firewall between customer projects; right to terminate on change of control |
| How are workers classified and paid, and what is the floor? | Misclassification suits against Scale and Surge; Sama pay reporting | Written pay floor per region; classification basis; who carries the legal risk |
| What protects workers from harmful content? | Sama; Outlier psychological-safeguards suit | Opt-out without penalty, exposure budgets, counselling access, content warnings |
| How are your build and runtime dependencies controlled? | Mercor breach via a compromised open-source package; TELUS Digital breach via cloud credentials reportedly taken from another supplier | Pinned and verified dependencies; secrets isolation; credential rotation after any supplier breach; incident-notification clause with a deadline |
| Can we get per-item, per-rater raw labels with timings? | Llama 2 found vendors differed markedly in downstream effect (see the labs section) | Export with stable rater IDs, timestamps, gold results; no pre-aggregated labels only |
| How do you detect AI-written or low-effort work? | Prolific's published authenticity tooling sets a reference point | Stated method, measured precision and recall, and what happens to flagged work |
Annotation tooling and open source
An annotation tool is the software that shows an item to a person, records the person's judgment in a structured form, and exports the result. Most widely used tools were built for classic supervised labelling: bounding boxes, spans, document classes. RLHF needs different task shapes. These include pairwise or k-way comparison with a strength scale, rubric scoring with per-item rationales, and editing a response into a better one. They also include multi-turn sessions against a live model and review of agent transcripts that run to tens of thousands of tokens. Tools differ most in how well they support those shapes, in where they run (self-hosted or cloud), and in licence.
| Tool | Licence and maintainer | Built for | Fit for LLM feedback | Deployment and status |
|---|---|---|---|---|
| Label Studio | Apache-2.0 (Community); HumanSignal, formerly Heartex. Paid editions exist. | Images, audio, text, HTML, time series, video | Configurable interfaces; an ML-backend SDK for pre-labelling, online learning and active learning. The README does not mention LLM or RLHF templates. | pip install label-studio (Python 3.10+) or Docker; about 28.6k GitHub stars at fetch |
| Argilla | Apache-2.0; announced it was joining Hugging Face | Text datasets for fine-tuning, RLHF and evaluation, with a Python SDK | Designed for LLM feedback (questions, text fields, AI suggestions); pairs with the distilabel AI-feedback library | Recommended on Hugging Face Spaces. The README now says the original authors have moved on and the project gets bug fixes only, with no new features planned. |
| Potato | GPL-3.0-or-later; academic (Potato 1.0 at EMNLP 2022, 2.0 at ACL 2026 demos) | NLP, agentic, GenAI and qualitative research; YAML-configured | Pairwise and best-worst scaling, Likert, spans. LLM label suggestions across several providers; active learning; a mode that hands off to LLM labelling as agreement improves; LLM-judge calibration. | pip install potato-annotation; deploy helpers for several clouds. The copyleft licence matters to a team that distributes a modified version. |
| doccano | MIT | Text classification, sequence labelling, sequence-to-sequence | Basic; no native comparison or ranking task described | pip, Docker, Docker Compose |
| CVAT | MIT (Community); cvat-ai | Image, video, audio, 3D point clouds | Not aimed at text feedback; relevant for multimodal and robotics data | Self-hosted; CVAT Online and Enterprise; also sells labelling services |
| Prodigy | Commercial, one-time ("lifetime") licence; Explosion (makers of spaCy) | Scriptable annotation for NLP, driven by Python "recipes" | Custom HTML/JS interfaces and LLM API integration through recipes (vendor-stated) | Runs locally; vendor states it never "phones home" and works air-gapped |
| Labelbox | Commercial platform | Formerly general labelling; now markets RL environments, evaluations and an expert network | Expert preference labels and rubrics as a service (vendor-stated) | Cloud; pricing not published |
Sources: Label Studio GitHub; Argilla GitHub and argilla.io; Potato GitHub; doccano GitHub; CVAT GitHub; Prodigy; Labelbox (2026). Star counts are as fetched in November 2026 and are a rough signal of community size, not quality.
What the tools leave to you. An RL human-data platform has six layers: the campaign spec, sampling from live models, assignment, the interface, quality and aggregation, and export into the training mix. The open-source tools above cover the interface well and offer some of assignment, quality and export. None of the projects' documentation describes pulling fresh samples from a live model checkpoint at assignment time, or a buffer that keeps time-to-first-sample low. None describes overlap-and-gold assignment policies of the kind the W1 campaign uses, or lineage from a label to a training-mix version. A team adopting one of these tools therefore still builds the sampler, the assignment service, the rater-quality models and the data contracts around it. In that design the tool becomes the rendering and recording layer (inference from the cited documentation).
How to choose. The decision is mostly about task shape and control, not features. (1) If the task is a short comparison or rating and the volume is modest, a configured open-source tool behind the platform's own assignment service is the fastest start; a permissive licence (Apache-2.0 or MIT) is preferable if the team will modify and distribute it. (2) If the task is a new shape, such as transcript review, rubric authoring or live multi-turn sessions, the interface is the product and the team will build it. Chapter 5 explains why: interface details move data quality, and the team needs to run experiments on them. (3) If a vendor supplies the workforce, the vendor's own tool is often contractually bundled. In that case, require raw per-rater exports so the platform's quality layer still works. (4) Check maintenance status before adopting. Argilla's README now says it receives bug fixes only, which is exactly the kind of fact that changes a multi-year platform decision.
W2 asks experts to find the first failing step in 60-step, roughly 25,000-token agent transcripts, label the failure type and write a corrected continuation of about 400 words, with a render target of 1.5 s and jump-to-step navigation. None of the tool documentation reviewed here describes a transcript viewer with tool-output replay. A span-annotation tool can mark the failing step, but it cannot replay the state at that step. The practical design is a custom React viewer for the transcript, with the step index and failure label written to the same feedback schema the rest of the platform uses. An off-the-shelf tool can still serve the simpler W1 pairwise task in the same platform.
What labs have published about their human-data practice
Model developers publish less about human data than about architectures, but a handful of papers carry most of what is known in public. Read together, they describe how many people labelled, how those people were selected, what they were asked, how much data came back, how consistent it was, and what the authors changed as a result. The table collects those facts. The timeline after it shows the shift from human-labelled signals toward AI feedback seeded or audited by humans.
| Publication | Who labelled and how they were selected | Signal and volume | Quality facts disclosed | Lesson for a platform |
|---|---|---|---|---|
| InstructGPT (OpenAI; Ouyang et al., 2022) | About 40 contractors via Upwork and Scale AI, admitted by a screening test on sensitive prompts; a held-out labeller group without screening | Prompts: about 13k SFT, 33k reward-model, 31k PPO (unlabelled). Rankings of K = 4–9 responses, giving K-choose-2 pairs. | Agreement 72.6 ± 1.5% (training labellers), 77.3 ± 1.3% (held-out). Most comparisons single-labelled for cost. | Ranking K outputs amortises reading cost. Expect agreement in the low 70s on open-ended helpfulness. |
| HH-RLHF (Anthropic; Bai et al., 2022a) | MTurk (about 80% of data) and Upwork; about 20 prolific workers formed a "select" group chosen on dialogue sophistication, not agreement | Binary choices at each turn of an open-ended chat. Helpful: 44k base, 52k rejection-sampled, 22k online. Red-team: 42k base, 2k rejection-sampled. | Researcher–crowdworker agreement about 63%. Hourly pay on Upwork made quality easier to incentivise than per-task MTurk pay. | Online collection on roughly weekly model updates. Pay structure shapes effort. |
| Sparrow (DeepMind; Glaese et al., 2022) | Paid raters under ethics review; policy of at least a living wage for the location; skip without penalty; well-being survey | Per-turn best-of-4 preferences; adversarial probing against 23 rules; evidence-support ratings | Krippendorff's α 0.53 for "any specific rule violated", 0.37 for the general harm rule. Re-rating of 1,078 dialogues, 2 raters each. | Narrow, single-rule questions gave more consistent labels than one broad harm question (inference from the two α values). |
| Constitutional AI (Anthropic; Bai et al., 2022b) | No human labels for harmfulness; humans supply a list of principles | Self-critique and revision for SFT; AI preference labels train the preference model (RLAIF) | Not applicable | Human effort moves from labelling items to writing and auditing principles. |
| PRM800K (OpenAI; Lightman et al., 2023) | Labellers credited to Scale. Admitted after 30 screening questions with at least 75% agreement with gold; 10–20 hidden quality-control items per generation. | About 800K step labels (−1/0/+1) over 75K solutions to 12K MATH problems; 1,085,590 labels before filtering | Active learning on "convincing wrong-answer" solutions estimated 2.6× more data-efficient than uniform selection | Process labels are affordable when labellers stop at the first error and the queue is chosen by the current model. |
| Llama 2 (Meta; Touvron et al., 2023) | Vendor annotators; helpfulness and safety under separate guidelines | 1,418,091 binary comparisons with a four-level strength rating; weekly batches from the latest model; 27,540 SFT annotations | Different vendors produced markedly different downstream results; 1,000 examples per batch held out | Measure vendors by downstream effect, not only by agreement. A few thousand high-quality SFT examples beat millions of third-party ones. |
| Llama 3 (Meta; Llama Team, 2024) | Annotators; not further described in the sections fetched | Pairs from two different models, four-level strength, then an edit step (edited > chosen > rejected); six post-training rounds; mean 3.8 turns and 1,042 tokens per example | Only "significantly better" or "better" pairs used for reward modelling and DPO; model-based quality and difficulty filters; semantic deduplication | Edits turn a comparison into a demonstration. Use the strength field to filter, not only to weight. |
| RLAIF vs RLHF (Google; Lee et al., 2023) | Off-the-shelf LLM as labeller | Summarisation, helpful and harmless dialogue | RLAIF comparable to RLHF on all three; direct RLAIF (LLM reward during RL) better still | AI labels are a credible first pass where the task is well specified. |
| LLM critics (OpenAI; McAleese et al., 2024) | Contractors reviewing code, with and without a trained critic model | Natural-language critiques of real assistant code | Model critiques preferred over human critiques 63% of the time; human–critic teams hallucinated fewer bugs than the critic alone | Assistance raises recall, and a human in the loop is what keeps precision up. |
| Rule-Based Rewards (OpenAI; Mu et al., 2024) | Small human set; LLM grader applies written rules | Safety behaviours such as non-judgmental refusals | F1 97.1 for RBR against 91.7 for a human-feedback baseline on safety-behaviour accuracy | For specifiable behaviours, human data buys the rules and the test set, not every label. |
| Tülu 3 (AI2; Lambert et al., 2024) | No human preference annotation described; GPT-4o judge on four aspects | DPO mixes of 271,409 (8B) and 334,302 (70B) pairs; on-policy plus off-policy responses from a 22-model pool; RLVR on 29,946 verifiable prompts | 8-gram decontamination at a 2% threshold; HelpSteer2 dropped over ShareGPT prompt provenance | A fully open recipe can reach strong results without human preferences, given good prompts and decontamination. |
| HelpSteer2 / 3 (NVIDIA; Wang et al., 2024) | Scale AI (English); a translation vendor for multilingual data in HelpSteer3; about 7,000 annotators in 80+ regions for HelpSteer3 | Five-attribute Likert ratings (HelpSteer2); −3…+3 preferences with written justifications, feedback and edits (HelpSteer3) | 3 to 5 annotators per item; the 3 most agreeing released | About 10k high-quality pairs trained a reward model scoring 92.0% on RewardBench (June 2024). |
Cross-cutting findings. (1) Agreement on open-ended preference sits near 63–77%. InstructGPT reports 72.6–77.3% labeller–labeller agreement and HH reports about 63% researcher–crowd agreement. Sparrow's α of 0.37–0.53 sits on a different scale but tells the same story. A campaign whose agreement falls in this range is behaving normally. A sudden drop below it is the signal to investigate. (2) Collection is iterative and on-policy. HH updated models roughly weekly, Llama 2 collected weekly batches from the latest model, and Llama 3 ran six rounds. A platform that cannot sample from a fresh checkpoint each round cannot reproduce these recipes. (3) Selection beats volume. InstructGPT screened labellers, PRM800K gated on 75% gold agreement, Llama 2 stopped at 27,540 SFT examples, and HelpSteer2 trained a leading reward model on about 10k pairs. (4) Vendors are not interchangeable. Llama 2 reports markedly different downstream results by vendor; only per-vendor ablations reveal this. (5) Humans move up the stack. Constitutional AI, RLAIF, rule-based rewards and Tülu 3 replace item-level human labels with principles, rules, judges and verifiers. Humans then write the rules, label the seed and test sets, and audit the judges. The critic study shows humans paired with models outperform either alone on precision. (6) Disclosure has narrowed. The detailed numbers above come mostly from 2022–2024 papers. Among the documents fetched for this chapter, the most recent frontier reports say less about who labelled, at what pay and with what agreement than InstructGPT and HH did (inference; absence of disclosure is not evidence about practice).
W1 reports 72% pairwise agreement on its 2,000 triple-labelled items and an 8% tie rate. That sits inside the published band (InstructGPT 72.6–77.3%; HH about 63%), so it does not by itself indicate a quality problem. The more useful comparison is method. Following Llama 2 and Llama 3, W1 could add a four-level strength field and train the reward model only on "better" and "significantly better" pairs. The test is whether reward-model accuracy on a held-out gold set rises when weak-preference pairs are removed. A rise supports filtering. A fall means W1's weak pairs carry real signal, and the field should be used for weighting instead.
Public preference and process datasets and what they teach
Public feedback datasets serve three purposes for a platform team. They are schema references: each encodes a decision about what a label is, such as a binary choice, a strength scale, per-attribute scores, a step label or a battle with ties. They are baselines and warm starts: a reward model pre-trained on public pairs and then fine-tuned on campaign data needs fewer campaign labels, although that saving is a hypothesis each team must test. They are cautionary tales about licensing, provenance and noise. The table lists the datasets most often used for reward modelling and process supervision, with sizes and licences as shown on their cards when fetched.
| Dataset (publisher, year) | Size and unit | Format | Label source | Licence (as on card) | What it teaches |
|---|---|---|---|---|---|
| HH-RLHF (Anthropic, 2022) | 169,352 pairs (161k train, 8.55k test) plus red-team transcripts | Two full dialogue strings, chosen and rejected | MTurk and Upwork crowdworkers | MIT | The card warns against using it for SFT: it is for preference models only. Storing whole transcripts instead of prompt plus response makes reuse awkward. |
| WebGPT comparisons (OpenAI, 2021) | 19,578 pairs | Two answers with quotes; scores in [−1, 1] summing to 0; 0 treated as a soft 50% label | Paid labellers | Not stated on fetched card | Ties as soft labels; keeping retrieved evidence alongside the answer |
| OASST1 (OpenAssistant, 2023) | 161,443 messages in 10,000+ trees; 461,292 quality ratings; 35 languages (paper) | Message trees with ranks and per-message labels | 13,500+ volunteers | Apache-2.0 | Volunteer data at scale is possible but uneven in quality. A tree format captures alternatives at every turn. |
| SHP (Stanford, 2022) | About 386k comment pairs, 18 domains | Two Reddit comments on one post, with scores and timestamps | Implicit: Reddit upvotes | Not confirmed in the fetched view | Implicit votes mix quality with popularity and timing; the card's score ratio and time gap let you filter. |
| UltraFeedback (OpenBMB; Cui et al., 2023) | 63,967 prompts × 4 responses from a 17-model pool; about 1M possible pairs | Per-aspect ratings with rationales (instruction-following, truthfulness, honesty, helpfulness) | GPT-4 | MIT | Fine-grained AI feedback scales cheaply; the card notes GPT-4 annotations contain mistakes. It became the template for the Tülu 3 pipeline. |
| HelpSteer2 (NVIDIA, 2024) | 21,362 rated responses (about 10k pairs); HelpSteer2-Preference adds −3…+3 preferences with justifications | Five 0–4 Likert attributes per response | Scale AI annotators, up to 3 per item | CC-BY-4.0 | Small, carefully rated data can train a top reward model. Its prompts come mostly from ShareGPT, which some open recipes exclude. |
| HelpSteer3 (NVIDIA, 2025) | 40,476 preference, 40,821 feedback, 14,461 edit, 3,274 edit-quality, 33,905 principle samples | −3…+3 preference; written feedback; edits; general, STEM, code, multilingual | Scale AI and a translation vendor; about 7,000 annotators; 3–5 per item, 3 most agreeing released | CC-BY-4.0 | The closest public analogue to a modern multi-signal campaign: preference, critique and edit on the same item. |
| Chatbot Arena conversations (LMSYS, 2023) | 33k battles, 20 models, about 13k unique IPs (Apr–Jun 2023) | Two model conversations plus user vote; moderation tags | Site users | Prompts CC-BY-4.0; outputs CC-BY-NC-4.0; gated | Real user prompts with mixed licences. The non-commercial outputs licence binds downstream use. |
| Arena human-preference-140k (LMArena, 2025) | 135,634 battles, 53 models, Apr–Jul 2025 | Winner ∈ {model_a, model_b, tie, both_bad}; category tags; 126 language values | Site users | Prompts CC-BY-4.0; outputs under each provider's terms | Recording "both bad" separately from "tie" carries real information. The Arena paper reports crowd votes in good agreement with experts. |
| PKU-SafeRLHF (PKU, 2024) | 82.1k pairs (default subset) | Separate better and safer response IDs; per-response safety flag, harm categories, severity 0–3 | Not confirmed in the fetched view | CC-BY-NC-4.0 | Decoupling helpfulness from harmlessness in one record, as Llama 2 did in its guidelines |
| PRM800K (OpenAI, 2023) | About 800K step labels, 75K solutions, 12K problems | JSONL per solution; each step rated −1/0/+1; finish_reason ∈ {found_error, solution, bad_problem, give_up}; screening and QC flags; time spent | Vendor labellers (Scale credited) | MIT | The best public schema for process labels. QC and screening items are kept in the data with flags, which makes quality auditable. |
| Math-Shepherd (Wang et al., 2023) | 444,655 solutions | Step markers with +/− labels | Automatic: a step is "good" if any of N = 8 completions from it reach the correct answer | Not stated on fetched card | Process labels without humans for verifiable domains. The authors report about 86% accuracy against human labels on a 160-step sample (at N = 4). |
| Tülu 3 preference mixes (AI2, 2024) | 271,409 (8B) / 334,302 (70B) pairs | Chosen/rejected from 1–5 ratings on four aspects | GPT-4o judge | Paper states all curated data have clear licences | Mixing on-policy responses into an otherwise off-policy pool; decontamination as a pipeline stage |
What the datasets teach, taken together.
Schema. The field-level choices recur, and each has a cost. A binary choice is cheapest to collect but discards strength. Strength scales appear as four levels (Llama 2 and 3), −3…+3 (HelpSteer3) and continuous [−1, 1] (WebGPT). Ties appear as an explicit option (Arena), a zero score (WebGPT) or not at all (HH, whose comparisons were binarised). Among the datasets here, "both bad" is a distinct outcome only in the Arena data, yet it is the outcome that tells a campaign its sampled pair is uninformative. Process labels need a stop reason: PRM800K's finish_reason separates "found an error" from "bad problem" and "gave up". A platform's own schema (Chapter 7) should carry all of these as optional fields so that a new campaign does not need a migration.
Provenance and licence. Licences on preference data are layered. Prompts, model outputs and human labels can each carry different terms. Both Arena releases license prompts under CC-BY-4.0 but put outputs under non-commercial or provider terms. PKU-SafeRLHF is non-commercial. Tülu 3 excluded ShareGPT-derived data, and with it HelpSteer2, over provenance concerns even though HelpSteer2's own licence is permissive. Record licence and prompt provenance per item, not per dataset.
Noise and label source. Label sources differ in kind, not only in quality. Upvote-derived pairs (SHP) reward early and popular comments. Arena votes reflect the users who visit the site. AI-judge data (UltraFeedback, Tülu 3) inherits the judge's errors, which the UltraFeedback card acknowledges. Automatic process labels (Math-Shepherd) are only as good as the completer model and the answer check. Keep the label source as a first-class field and evaluate reward models separately by source.
Size is not the lever it appears to be. HelpSteer2's roughly 10k pairs, which its authors describe as an order of magnitude fewer than HH-RLHF, trained a reward model that scored 92.0% on RewardBench in June 2024. The lab record above points the same way. Quality controls, strength filtering and on-policy collection matter more per label than raw count.
A normaliser you can run. The function below maps four of these formats into one record shape: a prompt, a list of responses, a preference with optional strength and tie or both-bad flags, step labels, and label source and licence. It is the import path a platform needs to use public data as a pilot baseline or warm start. The asserts run on rows that follow each card's documented fields.
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class FeedbackRecord:
source: str # dataset id
prompt: str
responses: list # candidate texts, in display order
preferred: Optional[int] # index into responses; None for tie / both_bad / no pair
strength: Optional[float] # signed strength in [-1, 1] toward responses[1]; None if unknown
tie: bool = False
both_bad: bool = False
step_labels: list = field(default_factory=list) # process labels, e.g. [1, 1, -1]
label_source: str = "human" # human | ai_judge | implicit_vote | automatic
licence: str = "unknown"
def split_hh(text):
"""HH-RLHF stores whole transcripts; the final 'Assistant:' turn is the response."""
i = text.rfind("\n\nAssistant:")
return text[:i], text[i + len("\n\nAssistant:"):].strip()
def from_hh(row):
p, a = split_hh(row["chosen"]); p2, b = split_hh(row["rejected"])
assert p == p2, "chosen/rejected must share the context"
return FeedbackRecord("hh-rlhf", p, [a, b], 0, None, licence="MIT")
def from_helpsteer3(row):
s = row["overall_preference"] # -3..3; negative favours response1
pref = None if s == 0 else (0 if s < 0 else 1)
return FeedbackRecord("helpsteer3", row["context"], [row["response1"], row["response2"]],
pref, s / 3.0, tie=(s == 0), licence="CC-BY-4.0")
def from_arena(row):
w = row["winner"]
pref = {"model_a": 0, "model_b": 1}.get(w)
return FeedbackRecord("arena-140k", row["prompt"], [row["a"], row["b"]], pref, None,
tie=(w == "tie"), both_bad=(w == "both_bad"),
label_source="implicit_vote", licence="prompts CC-BY-4.0; outputs provider terms")
def from_prm800k(row):
steps = row["label"]["steps"]
labels = [s["completions"][s["chosen_completion"] or 0]["rating"] for s in steps]
return FeedbackRecord("prm800k", row["question"]["problem"], [], None, None,
step_labels=labels, licence="MIT")
# --- tests on rows shaped like each card's documented fields ---
r = from_hh({"chosen": "\n\nHuman: sort a list?\n\nAssistant: use sorted(xs)",
"rejected": "\n\nHuman: sort a list?\n\nAssistant: no idea"})
assert r.preferred == 0 and r.responses[0] == "use sorted(xs)"
r = from_helpsteer3({"context": "q", "response1": "A", "response2": "B", "overall_preference": 2})
assert r.preferred == 1 and abs(r.strength - 2/3) < 1e-9 and not r.tie
r = from_arena({"prompt": "q", "a": "A", "b": "B", "winner": "both_bad"})
assert r.preferred is None and r.both_bad and r.label_source == "implicit_vote"
r = from_prm800k({"question": {"problem": "2+2?"}, "label": {"steps": [
{"completions": [{"rating": 1}], "chosen_completion": 0},
{"completions": [{"rating": -1}], "chosen_completion": None}]}})
assert r.step_labels == [1, -1]
print("normaliser OK")
Field names follow the cards fetched for this chapter (chosen/rejected for HH-RLHF; winner values for Arena; steps, completions, rating and chosen_completion for PRM800K). The HelpSteer3 field names context, response1, response2 and overall_preference are an assumption about the release, so check them against the card before use. Arena rows store full conversations, which an adapter must flatten to prompt, a and b first. When a PRM800K step's chosen_completion is null (as can happen on the step where a labeller stopped), this code falls back to the first completion's rating. That fallback is an assumption; confirm the semantics against the repository README before training on it.
W1. Before its 20,000-comparison campaign, W1 can warm-start its coding reward model on the code subset of HelpSteer3, which is CC-BY-4.0 and English-only for code. Pairs labelled "both bad" from Arena-style data belong in the evaluation set, not the training set. The test of the warm start is whether reward-model accuracy on W1's own gold items reaches the from-scratch model's accuracy with fewer campaign labels. A from-scratch model trained on 18,400 useful comparisons is the baseline. If the warm-started model matches it at, say, half the labels, the remaining collection budget can shift toward harder prompts.
W3. No public dataset contains expert-written rubrics for legal drafting with per-item weights, which is what W3 needs. The nearest public structures are HelpSteer3's feedback and principle subsets, and the separate better and safer fields of PKU-SafeRLHF as a pattern for scoring several criteria in one record. W3 is therefore a case where the platform must define a new schema and collect from scratch. Public data contributes only format precedent.
Connections. The vendor record feeds the workforce and vendor-integration designs of Chapter 10. The tooling coverage figure is the build-versus-adopt input to Chapters 5 and 12. The lab publications calibrate the quality expectations of Chapter 6, and the dataset schemas are the test cases for the data model of Chapter 7. The playbooks in Chapter 14 turn the due-diligence table and the schema lessons into checklists.
Playbooks and Checklists
This chapter is the working reference of the book. The earlier chapters explain how an RL data platform turns a research need into feedback that lands in a training mix; this one condenses that into four tools a team can apply to a live project without re-reading the theory:
- Campaign scoping questions and a launch checklist, where every checklist item states why it exists and which artifact or test proves it passed.
- Six incident runbooks (live endpoint outage, quality collapse, annotator fraud ring, schema break, sensitive-data leak, vendor SLA miss), each with detection signals, severity, numbered steps with decision points, communications and post-incident checks.
- A metric catalogue: definition, formula, running-example value, default target, dashboard panel and alert rule for each metric the platform should publish.
- Design sketches for five recurring platform projects: an expert transcript-review interface, cutting time-to-first-sample, a no-code campaign launcher, low-effort and LLM-assisted work detection, and adding a new feedback type. Each gives the problem, constraints, an architecture sketch, a data model, the key decisions with defaults, the metrics that show success, and an ordered rollout.
Three conventions run through the chapter. Default targets are recommended starting points chosen to be consistent with the reference workloads, not industry standards; tune them to the platform's own baseline after a few campaigns. Severity follows the common SEV-1 (worst) to SEV-5 scale, adapted to data incidents in the runbook section. And every checklist item says how to verify it, because an item that cannot be checked by a test or an artifact becomes a promise, and promises do not stop a bad dataset from reaching a reward model.
All workload numbers are illustrative. W1 is a pairwise preference campaign on coding helpfulness: 20,000 comparisons (10,000 prompts × 2 pairs) for a reward model, two responses per comparison from live endpoints (current checkpoint vs candidate), a pre-generated buffer of 2,000 pairs, a time-to-first-sample (TTFS) target of p50 ≤ 2 s and p95 ≤ 5 s, 10% of items triple-labelled, 5% gold assignments (≈ 25,260 assignments), 150 vendor raters at 20 h/week, mean 4.5 min per label (≈ 1,895 rater-hours), $40/h (≈ $75,780), 8% QA rejects (≈ 18,400 useful comparisons, ≈ $4.12 each), gold threshold 80%, overlap agreement 72%, 8% ties, 4% of raters flagged for low effort, and a request-to-mix time of 21 days against a 7-day target. W2 is expert review of 2,000 long agentic transcripts (mean 60 steps, ~25,000 tokens) by 40 experts at $120/h, ≈ $70 per transcript, with exact agreement on the first failing step of 58% (81% within ±2 steps). W3 is a new rubric feedback type for legal drafting: 3,000 prompts, mean 10 weighted items per rubric, AI-applied as the RL reward with a human–AI item agreement target of at least 0.8.
The code and configuration in this chapter (a campaign spec, a spec linter with sizing arithmetic, a collusion screen, a burn-rate helper, a rubric reward exporter and the tests for all of them) were run as shown; the tests assert the W1 numbers above.
Campaign launch checklist and scoping questions
What this section is for. A campaign is one bounded data collection: a task, a feedback type, a population of raters or experts, a source of model samples, quality controls, a budget and a stopping rule, all written down in a campaign spec that the platform executes. Most of the cost of a bad campaign is fixed before the first label: a vague purpose produces data nobody consumes, a missing consumer contract produces an export nobody can load, and a guideline that leaves ties undefined produces disagreement that no aggregation model can repair. This section gives two instruments that catch those failures early. The scoping questions turn a research request into a spec and tell the platform team when to push back. The launch checklist is the gate list a spec must pass before it consumes rater time.
Scoping questions
Ask these in the first conversation with the requesting researcher, in this order. The order matters: questions 1–4 decide whether to run a campaign at all, 5–10 decide its shape, 11–16 decide its size and controls, and 17–20 decide whether it can leave the platform. A good answer is specific enough to put into a spec field; an answer that cannot be written down is a signal to push back.
| # | Question | Why it matters | A good answer looks like | Push back when |
|---|---|---|---|---|
| 1 | Which model behaviour should change, and how will you know it changed? | Data without a target behaviour cannot be valued or stopped. | A named capability gap and an eval that measures it (for example a coding-helpfulness eval with a baseline score). | "We want more preference data" with no eval. Offer a pilot sized to test the hypothesis instead. |
| 2 | Who consumes the data, in what format, at which pipeline stage? | An export nobody can load is the most expensive failure mode: all the cost, none of the value. | A named consumer (reward-model training, SFT, RL reward service), an export schema version and the consumer's owner. | No owner on the consumer side. Do not launch until one signs the export contract. |
| 3 | Could existing data, an AI judge or a verifier answer this instead? | Human labels are the slowest and most expensive signal; reserve them for what judges and verifiers cannot do. | A reason: non-verifiable domain, expert judgment, a judge with measured bias on this slice (LLM judges show position, verbosity and self-enhancement bias; Zheng et al., 2023). | A verifier exists (unit tests for code correctness) and humans would only re-check it. |
| 4 | What decision will be made with the result, and by when? | Sets the latency budget and whether a partial dataset is useful. | "Include in the next reward-model retrain; a 60% dataset is still useful." | The decision date is earlier than the campaign can deliver; scope down rather than rush guidelines. |
| 5 | Which feedback type: pairwise, rating, rubric, critique, correction, step-level label? | Each type becomes a different training signal and needs a different interface and aggregator. | One registered type, or a request to add one (see the new-feedback-type design sketch below). | The researcher wants several types in one task; split into campaigns or a multi-part task with separate exports. |
| 6 | Where do prompts come from, and what distribution must they cover? | Coverage and difficulty drive data value more than volume. | A versioned prompt set, a deduplication rule and target slice proportions. | Prompts overlap with eval sets; require decontamination before launch. |
| 7 | Which models produce the samples, and must they be on-policy? | Off-policy samples are cheaper and can be pre-generated; on-policy samples track the current checkpoint but couple the campaign to endpoint uptime. | Named checkpoints per arm and whether a checkpoint change invalidates queued samples. | "Whatever is latest": the comparison target must be pinned or the labels describe a moving mixture. |
| 8 | What does a rater see, and what must they produce? | The interface defines the data; ambiguous outputs cannot be aggregated. | A mock or template with every field, its type and whether it is required. | Free-text outputs with no structure where a structured field would do. |
| 9 | How are ties, refusals, broken samples and unsafe content handled? | Undefined edge cases show up as disagreement and as skipped items. | Explicit options ("tie", "both bad", "cannot judge", "report content") and what each exports as. | The guideline says "use judgment". |
| 10 | What known biases must the design control? | Preference data inherits length and position effects; reward models then amplify length (Singhal et al., 2023). | Position randomisation, length reporting per slice, rubric items that separate length from quality. | No plan to measure length preference on the collected data. |
| 11 | Who is qualified to judge, and how will you test it? | Expertise is the expensive constraint; a mismatched pool produces confident noise. | A population, a qualification test with gold items and a pass threshold. | "Any rater" for expert content (legal, medical, security). |
| 12 | What agreement do you expect, and what will you do with disagreement? | Sets overlap rate and aggregation. Published pairwise agreement among trained labelers sits in the 70s per cent (Ouyang et al., 2022 report 72.6 ± 1.5% among training labelers and 77.3 ± 1.3% among held-out labelers). | An expected agreement band and an aggregation method (majority, Dawid and Skene, 1979, or keeping disagreement as soft labels). | An expectation of near-perfect agreement on a subjective task; recalibrate before pricing overlap. |
| 13 | How many useful labels, and how was the number chosen? | Sizing drives budget, time and stop rule. | A target tied to a learning curve or an earlier ablation; an explicit QA reject allowance. | A round number with no rationale; offer a staged target with a checkpoint ablation. |
| 14 | What is the budget ceiling and the cost per useful label you will accept? | Unit cost is the comparison across sources (vendor, expert, AI). | A ceiling and a target unit cost after rejects. | No ceiling. The platform should refuse open-ended spend. |
| 15 | When does collection stop? | Without a stop rule, campaigns run past usefulness or stop on a calendar date. | Target reached, or a quality floor breached, or the learning curve flattens. | "When the money runs out." |
| 16 | What is the policy on rater use of AI tools? | Crowd workers use LLMs at scale when not prevented; 33–46% did on one summarisation task (Veselovsky et al., 2023a). | Allowed, allowed with disclosure, or prohibited, plus the interface controls and detectors that back it. | A prohibition with no enforcement or no measurement. |
| 17 | Does any prompt, sample or tool output contain personal or confidential data? | Raters are an exposure surface; vendors are processors under most privacy regimes. | A data classification and a scan (for example with Presidio) plus a manual sample review. | Production user data shown to external raters without a legal basis and a redaction step. |
| 18 | Is any content harmful to view, and what welfare controls apply? | Exposure to disturbing content has a human cost and drives attrition. | Content warnings, opt-out, exposure caps per rater-day, and access to support. | Red-team or abuse content routed to a general pool. |
| 19 | How long is the data kept, and who may access it? | Retention and access set governance and incident blast radius. | A retention period, an access group and a deletion path. | "Forever, everyone." |
| 20 | What does the datasheet for this dataset say? | Downstream users need provenance, intended use and known limitations (Gebru et al., 2021). | A datasheet draft that the export job completes automatically (counts, versions, agreement). | Nobody owns documentation. |
Table 14.1. Twenty scoping questions. Questions 1–4 decide whether to run a campaign at all; a "push back" on any of them means the right output of the conversation is a smaller pilot or a different signal source, not a launch.
When to push back, in general. Three patterns justify refusing or reshaping a request rather than executing it. First, no consumer: data with no named consumer and export contract has no path into the mix, so its value is zero regardless of quality. Second, no measurement: if nobody can say how the target behaviour will be measured, the campaign cannot be sized, stopped or valued; the right response is a pilot whose output is the measurement. Third, mismatched signal: if a verifier, an existing dataset or a calibrated AI judge answers the question, human time should go elsewhere. Pushing back works best as an offer: a pilot of a few hundred items, a judge-first design with human audit, or a narrower slice.
From answers to a spec, with the arithmetic
The scoping answers become fields in a versioned spec. Encoding the spec as data rather than a document is what makes the checklist enforceable: a linter can derive the sizing (labels, assignments, rater-hours, labour cost, gold items per rater) and block launches that violate rules. The derived numbers follow from five inputs. With \(C\) comparisons, overlap fraction \(f\) with \(r\) raters per overlapped item, and gold fraction \(g\) of assignments:
\[ L = fCr + (1-f)C, \qquad A = \frac{L}{1-g}, \qquad H = \frac{A\,\bar t}{60}, \qquad \$ = H \cdot w, \]
where \(L\) is labels, \(A\) assignments, \(\bar t\) the mean minutes per assignment, \(H\) rater-hours and \(w\) the hourly rate. Gold items per rater is \(gA/N\) for a pool of \(N\) raters. That last number is the one most often missed: a per-rater gold accuracy threshold is only meaningful if each rater sees enough gold items for the estimate to be tight. The 95% Wilson score interval for a proportion \(\hat p = k/n\) is
\[ \frac{\hat p + \frac{z^2}{2n}}{1+\frac{z^2}{n}} \pm \frac{z}{1+\frac{z^2}{n}}\sqrt{\frac{\hat p(1-\hat p)}{n} + \frac{z^2}{4n^2}}, \quad z = 1.96. \]
In W1, \(C\) = 20,000, \(f\) = 0.10, \(r\) = 3, \(g\) = 0.05, \(\bar t\) = 4.5 min, \(w\) = $40/h, \(N\) = 150. Then \(L\) = 2,000 × 3 + 18,000 = 24,000 labels; \(A\) = 24,000 / 0.95 ≈ 25,263 assignments (≈ 25,260); \(H\) ≈ 1,895 rater-hours, or 0.63 weeks of a 3,000 rater-hour/week pool; labour ≈ $75,790 (the reference sheet's ≈ $75,780 rounds assignments to 25,260 first). Gold assignments ≈ 1,263, so each rater sees only about 8.4 gold items. A rater who gets 6 of 8 right (75%) has a 95% interval of roughly 0.41–0.93: the 80% threshold cannot separate that rater from a good one. With 50 gold items, 40 correct gives 0.67–0.89; with 100, 80 correct gives 0.71–0.87. The fix that does not inflate collection cost is to move most gold into a qualification test (40 items in the spec below) and use in-campaign gold for drift detection at the pool level, where 1,263 items give a tight estimate.
The spec below encodes W1. Field names map one-to-one to checklist items.
# w1_campaign.yaml: campaign spec checked by campaign_lint.py (illustrative W1 values)
campaign_id: w1_coding_pref_v1
owner: researcher@example.org
consumer: {kind: reward_model, name: w1_rm, needs_by_stage: rm_retrain}
task:
feedback_type: pairwise_preference # registered feedback type
allow_ties: true
rationale_required: false
guidelines_version: g1.3
items:
prompts: 10000
pairs_per_prompt: 2
prompt_source: {dataset: w1_coding_prompts, version: v4, dedup: minhash_0.8}
generation:
arms: [{checkpoint: current}, {checkpoint: candidate}]
mode: buffered # buffered | on_demand
buffer_pairs: 2000
pin_checkpoints: true # refuse samples from other checkpoints
ttfs_slo_s: {p50: 2.0, p95: 5.0}
population:
pool: vendor_a_trained
raters: 150
hours_per_week_each: 20
qualification: {gold_items: 40, min_accuracy: 0.80}
quality:
overlap: {fraction: 0.10, raters_per_item: 3}
gold_fraction: 0.05
gold_min_accuracy: 0.80
min_gold_per_rater: 30 # below this the 80% check is noise
low_effort_median_s: 40
randomize_position: true
budget:
rate_usd_per_hour: 40
minutes_per_label_mean: 4.5
max_usd: 85000
stopping:
target_useful_comparisons: 18000
stop_if_gold_accuracy_below: 0.75 # pool-wide, rolling 500 gold items
export:
schema: pairwise_preference.v3
destination: rm_training_bucket/w1
governance:
pii_scan: presidio_default
content_warning: none
retention_days: 365
The linter derives the sizing and emits BLOCK (launch refused) or WARN (launch allowed with sign-off) findings. Five rules are shown; a production linter carries one rule per automatable checklist item.
"""campaign_lint.py: derive sizing from a campaign spec and flag launch blockers.
Usage: python3 campaign_lint.py w1_campaign.yaml"""
import math, sys, yaml
def wilson(k, n, z=1.96):
"""95% Wilson score interval for k successes out of n trials."""
if n == 0:
return (0.0, 1.0)
p = k / n
d = 1 + z * z / n
c = (p + z * z / (2 * n)) / d
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
return (c - h, c + h)
def derive(s):
comps = s["items"]["prompts"] * s["items"]["pairs_per_prompt"]
ov = s["quality"]["overlap"]
multi = round(comps * ov["fraction"])
labels = multi * ov["raters_per_item"] + (comps - multi)
assignments = labels / (1 - s["quality"]["gold_fraction"])
hours = assignments * s["budget"]["minutes_per_label_mean"] / 60
pool_h = s["population"]["raters"] * s["population"]["hours_per_week_each"]
gold = assignments - labels
return dict(comparisons=comps, labels=labels, assignments=round(assignments),
rater_hours=round(hours), pool_weeks=round(hours / pool_h, 2),
labour_usd=round(hours * s["budget"]["rate_usd_per_hour"]),
gold_per_rater=round(gold / s["population"]["raters"], 1))
def lint(s):
d, out = derive(s), []
if d["labour_usd"] > s["budget"]["max_usd"]:
out.append(("BLOCK", f"labour ${d['labour_usd']:,} exceeds budget ${s['budget']['max_usd']:,}"))
if d["gold_per_rater"] < s["quality"]["min_gold_per_rater"]:
n = round(d["gold_per_rater"])
lo, hi = wilson(round(0.8 * n), n)
out.append(("WARN", f"{d['gold_per_rater']} gold items per rater; 95% CI at {round(0.8 * n)}/{n} correct is "
f"[{lo:.2f}, {hi:.2f}]; add qualification gold or raise gold_fraction"))
if s["generation"]["mode"] == "buffered" and not s["generation"].get("pin_checkpoints"):
out.append(("BLOCK", "buffered generation without pinned checkpoints can serve stale samples"))
if not s["quality"].get("randomize_position"):
out.append(("BLOCK", "pairwise task without position randomization"))
if s["consumer"].get("kind") is None:
out.append(("BLOCK", "no named consumer for the data"))
return d, out
if __name__ == "__main__":
spec = yaml.safe_load(open(sys.argv[1]))
derived, findings = lint(spec)
print(derived)
for f in findings:
print(*f)
Running it on the W1 spec prints:
{'comparisons': 20000, 'labels': 24000, 'assignments': 25263, 'rater_hours': 1895, 'pool_weeks': 0.63, 'labour_usd': 75789, 'gold_per_rater': 8.4}
WARN 8.4 gold items per rater; 95% CI at 6/8 correct is [0.41, 0.93]; add qualification gold or raise gold_fraction
The tests that pin this behaviour (sizing matches the reference workload; thin gold is a warning, not a block; Wilson widths as stated) are in the test file at the end of the runbook section.
Launch checklist
Every item has an ID so that a launch review can cite it ("blocked on Q3"), a reason, and a verification that produces an artifact. Items marked auto should be linter rules or dry-run assertions; the rest need a named human sign-off. The groups follow the lifecycle figure above.
Purpose and consumer
| ID | Item | Why | How to verify |
|---|---|---|---|
| P1 | A named consumer and owner accept the export schema version. | Unconsumed data is pure cost. | Consumer owner's sign-off on the spec; consumer field non-empty (auto). |
| P2 | The target behaviour has an eval and a baseline. | Needed to value and stop the campaign. | Link to eval run with the baseline score in the spec. |
| P3 | The stop rule is machine-checkable. | Campaigns without one overrun. | stopping block present with a numeric target and a quality floor (auto). |
| P4 | Budget ceiling ≥ derived labour × (1 + reject allowance). | Prevents mid-campaign stops for money. | Linter sizing vs max_usd (auto). |
Task and guidelines
| ID | Item | Why | How to verify |
|---|---|---|---|
| T1 | Guidelines are versioned and frozen for launch. | A guideline edit mid-campaign silently changes the label distribution. | guidelines_version pinned; edits create a new version and a change-point marker on dashboards (auto). |
| T2 | Every edge case has an explicit option and an export mapping (tie, both bad, cannot judge, report). | Undefined cases become disagreement or skips. | Export schema has an enum value for each; dry run exercises each option (auto). |
| T3 | Guidelines include at least five worked examples with rationale, including hard cases. | Examples calibrate raters faster than rules. | Reviewer checks the guideline document. |
| T4 | Pilot completed and read in full by the researcher. | Reading the pilot is where ambiguity is found. | Pilot report: item count, agreement, list of guideline changes made. |
| T5 | Bias controls are in the design (position randomised; length reported). | Position and length effects otherwise enter the reward model. | randomize_position: true (auto); dry-run export carries per-item length and display order. |
Samples and endpoints
| ID | Item | Why | How to verify |
|---|---|---|---|
| S1 | Checkpoints for every arm are pinned and recorded on each sample. | Unpinned arms produce labels about an unknown mixture. | Each sample row carries checkpoint IDs; linter blocks buffered mode without pinning (auto). |
| S2 | Buffer size covers at least the endpoint's worst recent outage at peak consumption. | The buffer is the outage shock absorber. | Runway calculation (runbook 1) using the peak concurrency from the last campaign. |
| S3 | Sample validity checks run before items enter the buffer. | Empty, truncated or identical pairs waste rater time and corrupt labels. | Dry run injects each defect; all are rejected (auto). |
| S4 | Prompts are deduplicated and decontaminated against eval sets. | Training on eval prompts inflates the eval that values the data. | Decontamination report attached; overlap count = 0 above threshold. |
| S5 | TTFS SLO defined and load-tested. | Slow first samples cost paid idle time and rater patience. | Load test at expected concurrency meets p50/p95 targets. |
Population and assignment
| ID | Item | Why | How to verify |
|---|---|---|---|
| A1 | Qualification test with gold and a threshold. | Removes unqualified raters before they produce labels. | Pass rate and score distribution from the qualification run. |
| A2 | Overlap items are assigned to distinct raters, not the same rater twice. | Self-agreement inflates agreement metrics. | Assignment invariant test in dry run (auto). |
| A3 | Per-rater caps on share of items (for example ≤ 2% of the campaign). | Limits the damage any single rater, or fraud ring, can do. | Cap set in assignment config; dry run with a fast bot confirms it is enforced (auto). |
| A4 | Capacity covers the plan: pool hours ≥ derived rater-hours ÷ planned collection weeks. | Under-capacity stretches request-to-mix latency. | Linter sizing vs vendor's committed hours (auto). |
Quality and integrity
| ID | Item | Why | How to verify |
|---|---|---|---|
| Q1 | Gold set exists, is reviewed by two experts, and is large enough per rater (or front-loaded in qualification). | A per-rater threshold on 8 gold items is noise (W1 callout above). | Gold count per rater ≥ min_gold_per_rater, or qualification gold covers it (auto warn). |
| Q2 | Gold items are indistinguishable from regular items in the interface. | Recognisable gold measures attention to gold, not quality. | Diff of rendered payloads: no field, ordering or timing differs (auto in dry run). |
| Q3 | Overlap fraction and aggregation method chosen and recorded. | Sets how disagreement is measured and resolved. | Spec fields; aggregation job runs on dry-run output (auto). |
| Q4 | Low-effort and AI-use detectors are enabled with thresholds. | Detectors must run from the first label, not after a problem is noticed. | Detector config present; dry run with a scripted fast bot triggers a flag (auto). |
| Q5 | Pool-level quality floor auto-pauses the campaign. | A collapse should stop intake before thousands of labels accrue. | Alert rule exists and targets the pause switch; tested by forcing a gold failure in staging. |
Data path, governance and welfare
| ID | Item | Why | How to verify |
|---|---|---|---|
| D1 | Dry-run export loads in the consumer's pipeline. | Catches schema mismatches before collection. | Consumer's loader run on the dry-run export; row count and field checks pass (auto). |
| D2 | Lineage links every label to sample, prompt, checkpoint, rater, guideline and spec version. | Incident scoping and retraction depend on it. | Lineage query on dry-run labels returns all six keys (auto). |
| D3 | PII and secrets scan on prompts and samples, plus a manual sample. | Automated scanners miss some sensitive data; Presidio's own documentation says it cannot guarantee finding all of it (Presidio). | Scan report with hit count; reviewer read of a random 100 items. |
| D4 | Vendor access is scoped to this campaign and expires. | Limits exposure and simplifies offboarding. | Access-group membership listing; expiry date set. |
| D5 | Content warnings, opt-out and exposure caps configured where content can be harmful. | Welfare and attrition. | Spec content_warning field; cap visible in assignment config. |
| D6 | Runbook owner and on-call named for the campaign window. | Incidents need an owner before they happen. | On-call schedule link in the spec. |
Table 14.2. Launch checklist, 29 items in six groups. Seventeen (about 60%) are marked auto, as lint rules or dry-run assertions; the rest need a named sign-off.
The go/no-go rule. Launch requires zero open BLOCK findings, every non-automatable item signed by a named person, and the dry run's export loaded by the consumer (D1). WARN findings may launch with a written acceptance. Ramp in stages (5% of the pool, then 25%, then all) and advance only when the dashboards in the metric catalogue are green for the stage; the first stage exists to catch problems that only appear with real raters, such as an option that most raters misread.
In W1, the 21-day request-to-mix baseline splits into scoping 3 days, guidelines and pilot 4, collection 6, QA 3, pipeline and export 2, and reward-model retrain plus mix inclusion 3. The checklist attacks the non-collection stages: a spec template with defaults shortens scoping; the dry run (D1) moves export debugging before collection, which is where most of the 2 pipeline days go; continuous QA from the first label (Q4, Q5) overlaps the 3 QA days with collection. Collection itself is the constraint: 1,895 rater-hours is 0.63 weeks, about 4.4 days, of the full pool. The plan of record is the value-stream plan of Chapter 8: QA and export overlap collection, and about 10.5% more scheduled rater-hours (about 22 instead of 20 hours a week from the same 150 raters) bring collection to 4.0 days, for 7.0 days from request to mix at unchanged labour cost.
Incident runbooks
Why a data platform needs its own runbooks. A runbook is a pre-written procedure for one class of incident: numbered steps, decision points, who to tell and what to check afterwards, so the responder follows a path instead of inventing one under pressure. RL data platforms differ from ordinary services in three ways that shape the procedure. First, bad output looks like good output: a mislabelled preference is a well-formed row, so many incidents are detected by statistics (gold accuracy, agreement, distribution shifts) rather than by errors. Second, damage propagates downstream and later: labels exported today train a reward model next week, so the key branch in every runbook is whether affected data has left the platform, and the key capability is retracting a dataset version. Third, people are in the loop: raters wait, get paid, get suspended or are exposed to content, and vendors have contracts, so containment and communication involve humans outside the engineering team.
Severity for data-platform incidents
The scale adapts PagerDuty's public severity definitions, including the rule that when unsure between two levels, responders assume the higher one and settle the classification in the postmortem (PagerDuty).
| Severity | Data-platform definition | Response |
|---|---|---|
| SEV-1 | Personal data, credentials or confidential content exposed to unauthorised parties; or corrupted or tainted data confirmed inside a training run that feeds a release decision. | Page the incident commander. Notify privacy, legal and security at once. Pre-authorised: pause all affected campaigns and exports. |
| SEV-2 | Bad data exported and consumed (a retrain started on it); a confirmed fraud ring across campaigns or vendors; all campaigns unable to serve items. | Page the incident commander. Freeze exports. Notify consumer owners. |
| SEV-3 | One campaign halted or degraded, or a quality problem contained before export. | High-urgency page to the platform on-call; campaign owner informed. |
| SEV-4 | Degradation absorbed by buffers or within tolerance; a vendor behind plan without a dated consumer at risk. | Ticket and investigation in working hours. |
| SEV-5 | Cosmetic interface issues. | Backlog. |
Table 14.3. Severity scale. The escalators are exposure (did sensitive data reach someone who should not see it), propagation (did affected labels leave the platform) and breadth (how many campaigns, vendors or raters share the cause).
Roles and when to declare. For SEV-1 and SEV-2, split the roles the Google SRE book describes: an incident commander who holds the overall picture and assigns work, an operations lead who is the only person changing the system, a communications lead who sends periodic updates, and a planning role that tracks follow-ups and what was changed from normal so it can be reverted (Beyer et al., 2016). The same chapter gives a practical trigger for declaring: a second team is needed, the impact is visible outside the team, or the issue is unsolved after an hour of focused work. Data incidents nearly always need a second team (model serving, a vendor, a consumer), so declare early.
Prerequisites. Every runbook below assumes four capabilities exist before the first incident: (1) pause switches at campaign, rater, vendor and export level, each callable by on-call without a deploy; (2) lineage from every label to its sample, prompt, checkpoint, rater, guideline version, spec version and every dataset version that includes it (launch item D2); (3) a quarantine flag on labels that excludes them from aggregation and export without deleting them, so a mistaken quarantine is reversible; and (4) communication templates for raters (through the vendor where applicable), vendors, requesting researchers and consumer owners.
Runbook 1 · Live model endpoint outage or degradation
| Scenario | An endpoint serving one arm of a campaign errors, times out, is overloaded or is undeployed. On-demand generation stalls, the pre-generation buffer drains, and raters see slow or empty item fetches. A quieter variant: the endpoint keeps answering but returns truncated responses or is serving a different checkpoint than the spec pins. |
|---|---|
| Detection signals | TTFS burn-rate alert (metric catalogue M1); endpoint error or timeout rate; buffer runway below 60 minutes (M3); "no item available" responses to raters; a checkpoint-registry undeploy event for a pinned checkpoint; rising share of samples whose finish reason is not a normal stop. |
| Severity | SEV-4 if the buffer absorbs it. SEV-3 when raters on a campaign are idle or the runway will run out before recovery. SEV-2 if all campaigns are affected, or samples from the wrong checkpoint were served. |
| Containment levers | Open the circuit breaker on the on-demand path so the campaign serves only from the buffer; cap client retries; release raters to other campaigns' queues; pause the campaign. |
- Identify the failing arm and the kind of failure. Check the checkpoint registry first: an undeploy is a planning failure, not an outage, and the fix is a decision about the spec, not a retry.
- Stop amplifying. Open the circuit breaker on on-demand generation for the affected campaign. Confirm clients use capped exponential backoff with jitter; synchronised retries make an overloaded endpoint worse, and jitter spreads them out (Brooker, 2015).
- Compute runway: buffer items ÷ (concurrent raters ÷ minutes per item). Decision: runway exceeds the serving team's recovery estimate → keep serving from the buffer and go to step 5. Otherwise → step 4.
- Shed load gracefully. When runway reaches 30 minutes, release raters to other qualified campaigns rather than leave them polling an empty queue. Do not silently substitute another checkpoint; changing an arm is a spec change that needs the researcher.
- Check data correctness. Query samples generated in the incident window by checkpoint ID and finish reason. Quarantine any pair with a truncated response, an error payload rendered as text, or a checkpoint ID that does not match the spec, together with any labels already collected on them.
- Recover in order. Move the breaker to half-open (a small fraction of calls), refill the buffer to its target before releasing the full pool back, then close the breaker.
- Account for idle time. Record rater-minutes spent waiting; vendor contracts often pay for it, and it is part of the incident's cost.
Comms. Raters (through the vendor): "Items for this campaign are temporarily unavailable; you have been moved to another queue; no action needed." Researcher: arms affected, labels quarantined, revised completion estimate. Serving team: the campaign's dependency and peak demand, so it is considered in their capacity plans.
Post-incident checks. Buffer target covers the observed outage duration at peak consumption (launch item S2); an undeploy hook notifies the platform before a pinned checkpoint goes away; a synthetic probe fetches an item every minute per active campaign; quarantined labels are relabelled or written off in the cost report.
Assume (illustrative) that 60 W1 raters work concurrently at peak. Consumption is 60 ÷ 4.5 ≈ 13.3 pairs per minute, so the 2,000-pair buffer gives a runway of about 150 minutes (the buffer_runway_min helper and its test reproduce this). The candidate endpoint starts returning 503 errors at 10:00, and serving estimates 3.5 hours to recover. The circuit opens at 10:04; at 12:00 (runway 30 minutes) on-call moves 60 raters to another campaign's queue. On recovery at 13:30 the buffer is refilled before raters return. The correctness check finds 140 pairs (illustrative) generated just before the breaker opened in which the candidate response was cut off by a timeout; they and their labels are quarantined. Severity: SEV-3. Without the release at 12:00, about one hour of 60 raters' time (60 rater-hours, $2,400 at $40/h) would have been spent waiting. Follow-up: raise the buffer target to cover 4 hours at peak, about 13.3 × 240 ≈ 3,200 pairs, weighed against staleness (every pair in the buffer is discarded if the candidate checkpoint is replaced).
Runbook 2 · Quality collapse
| Scenario | Pool-level quality metrics move sharply: gold accuracy falls, overlap agreement drops, or a label distribution shifts (tie rate, left-choice rate, share of "cannot judge"). Common causes: a guideline edit; a new rater cohort; an interface deploy that changes what raters see or how answers are recorded; a sample defect (identical or truncated pairs); an error in the gold key; a vendor substituting untrained staff. |
|---|---|
| Detection signals | Rolling pool gold accuracy below the spec's floor (M8); overlap agreement down more than 10 points from the campaign baseline (M9); tie rate or left-choice rate outside its band (M10, M11); a change point that lines up with a deploy, guideline version, cohort start or checkpoint change on the dashboard's event track. |
| Severity | SEV-3 if caught before export. SEV-2 if affected labels were exported and a retrain consumed them. |
| Containment levers | Auto-pause on the quality floor (launch item Q5); manual pause per campaign; export freeze. |
- Pause intake (if the auto-pause has not already) and freeze exports for the campaign.
- Find the change point. Plot the failing metric hourly and overlay the event track. A step change aligned with an event is far more informative than a slow drift.
- Slice to localise. Recompute the metric by rater cohort, interface version (client build), prompt slice, checkpoint and gold item. Decision: one cohort → coaching, or runbook 3 if the pattern looks coordinated; one client build → interface bug (step 5); one slice or checkpoint → sample defect (runbook 1 step 5 query); every slice at once but only on gold → suspect the gold key (step 4).
- Test the gold. Have two experts independently re-label the 50 most-failed gold items. If they side with the raters, the gold is wrong: fix it and recompute rater scores before acting on any rater.
- Repair before relabel. If the interface recorded enough to reconstruct the truth (for example the order in which responses were actually rendered), repair labels deterministically and verify on a sample. Otherwise quarantine labels from the change point, limited to the affected slice.
- Relabel what cannot be repaired, prioritising overlap and gold-adjacent items so that quality metrics recover fastest.
- Resume at 10% of the pool and compare gold accuracy and agreement against the pre-incident baseline before ramping.
- If labels were exported, publish a corrected dataset version, mark the old one withdrawn, and give consumer owners the list of affected item IDs so they can decide whether a retrain must be repeated.
Comms. Raters: a short guideline clarification if a cohort or guideline caused it; nothing accusatory. Researcher and consumer owners: what changed, how many labels are affected, repaired versus relabelled, and the new dataset version.
Post-incident checks. The interface logs a render receipt (what was actually shown, in what order) with every label; interface deploys run a canary cohort with gold-accuracy comparison before full rollout; the gold set has a second-expert review; a dashboard event track exists for deploys, guideline versions and cohort changes.
Illustrative. At 14:00 an interface deploy changes the side-by-side layout on narrow screens to stacked, which reverses the visual order of the two responses on those screens. The client still records the intended order, so labels from narrow screens map to the wrong response. The left-choice rate stays near 50% because position randomisation is intact, so the position metric does not fire. About a quarter of raters use narrow screens and their gold accuracy drops to about 16%, roughly the mirror image of normal, so the pool's true accuracy falls from 86% to about 69%. The alert, however, uses a rolling window of the last 500 gold items; at 60 concurrent raters (the assumption from runbook 1) the campaign produces about 800 labels and 40 gold items per hour, so the window crosses the spec's 0.75 floor only after about 63% of it has turned over, around 22:00, and the campaign auto-pauses. Slicing by client build and screen width isolates the cause. About 8 h × 800 × 0.25 ≈ 1,600 labels were affected. The deploy had shipped render receipts, so the labels are repaired by flipping them, and a two-expert audit of 100 repaired items confirms the repair. No relabelling is needed, and nothing was exported. Severity: SEV-3. Two changes follow: a short-window gold alert (the last 100 gold items, about 2.5 hours) alongside the long one, the same idea as multiwindow SLO alerting; and a canary cohort with a per-build gold comparison before full rollout, which would have caught the mirror-image accuracy within the first hour.
Runbook 3 · Annotator fraud ring
| Scenario | A group of accounts coordinates to earn pay with little effort: one worker answers and others copy, one person operates several accounts, answers come from a script or an LLM, or gold answers leak and are shared. Copying of this kind skews aggregate statistics even when the copied answers are reasonable (KhudaBukhsh et al., 2014). |
|---|---|
| Detection signals | High mean-centred answer similarity between accounts on shared items (M14); identical or near-identical free text; shared device fingerprints or network addresses; synchronised submission times; throughput above what reading the item allows; and the distinctive gold leak signature: gold accuracy far above agreement with the consensus on non-gold items. |
| Severity | SEV-3 for one group in one campaign. SEV-2 across campaigns or vendors, or if the group's labels were exported. SEV-1 if accounts were used to extract confidential prompts or samples (go to runbook 5). |
| Containment levers | Suspend assignment for the accounts; quarantine their labels across all campaigns via lineage; rotate the gold set. |
- Do not alert the accounts before evidence is preserved. Snapshot labels, interaction telemetry, device and network logs for the suspected group and a matched control group.
- Corroborate with independent signals. Decision: at least two independent signals (for example answer similarity plus shared device, or similarity plus the gold leak signature) → step 3. One signal only → put the accounts on a watchlist with targeted audit items; do not suspend on a single detector.
- Suspend all accounts in the group at once, so remaining members cannot shift behaviour.
- Quarantine every label from the group across all campaigns and dataset versions, using lineage.
- Check for a gold leak. If gold accuracy in the group is high while consensus agreement is low, assume the gold set leaked: retire it, issue a fresh gold set, and recompute every rater's gold accuracy on the new items before relying on it.
- Check for exfiltration. Compare items viewed with items submitted per account. Many views with few submissions on confidential content is a leak, not just fraud: go to runbook 5.
- Re-aggregate and relabel. Re-fit the aggregation model without the group (for example Dawid–Skene) for multi-labelled items; relabel single-labelled items that the group touched.
- Hand over to the vendor under the contract: evidence pack, the vendor's own investigation, an appeal path for workers, and pay decisions per contract terms. Removal decisions should be reviewable by a human who did not build the detector.
Comms. Vendor: factual evidence and the contract clause; no public naming. Researcher and consumers: count of quarantined labels and relabel plan. Other raters: nothing, unless guidelines change.
Post-incident checks. The collusion screen runs nightly on densely shared item sets; the gold set rotates on a schedule and per-rater gold is drawn from a pool large enough that no two raters see the same sequence; per-rater share caps (launch item A3) are enforced; device and network signals feed the detector with privacy review.
Where to run the screen matters. In W1, random overlap gives 2,000 items × 3 rater-pairs = 6,000 pair-slots spread over 150 × 149 ÷ 2 = 11,175 rater pairs, about 0.54 shared items per pair, too few for a similarity test. The qualification set, which every rater completes (40 items in the spec), and the in-campaign gold items, which many raters see, are dense enough. Illustrative incident: the nightly screen on qualification and gold answers links five accounts with pairwise similarity 0.91–0.97 (threshold 0.85, as in find_colluders). Their gold accuracy is 97%, but their agreement with the non-group majority on overlap items is 51%: the gold leak signature. Two accounts also share a device fingerprint, which is the second, independent signal. The five accounts contributed 1,150 labels. All are quarantined; relabelling costs 1,150 × 4.5 min ≈ 86 rater-hours, about $3,450. The gold set is rotated, and two other raters whose gold accuracy drops by more than 15 points on fresh gold go to targeted audit. Severity: SEV-3, since nothing had been exported.
Runbook 4 · Schema break
| Scenario | A producer (the interface, a feedback-type plugin, a vendor connector) emits records that the export or a consumer cannot read (a hard break), or can read with a changed meaning (a silent break): a renamed field read as null, an enum value mapped to a default, a boolean turned into a graded score, a unit change. |
|---|---|
| Detection signals | Schema-validation rejects at ingest above 0.1% (M17); export job failures; consumer loader row-count mismatch; distribution checks on exported fields (mean reward per prompt, tie rate, weight sums) moving at a producer deploy. |
| Severity | SEV-4 if rejected at ingest into a dead-letter queue. SEV-3 if export is blocked. SEV-2 if a silent change was exported and consumed. |
| Containment levers | Export freeze, with consumers pinned to the last good dataset version; producer rollback; dead-letter queue (DLQ) for rejected records. |
- Freeze exports and pin consumers to the last dataset version that passed checks.
- Find the producer version and the first bad record by joining records to the client or service build that wrote them.
- Decision: hard or silent? Hard → records are in the DLQ and nothing bad was stored; go to step 4. Silent → records were accepted; list every dataset version that includes them (lineage) and treat each as suspect.
- Restore compatibility: roll back the producer, or ship a reader that handles both versions explicitly.
- Migrate with version awareness. Replay the DLQ and backfill silent records with an explicit, tested migration keyed on the producer version. Never infer the old meaning from the value alone.
- Re-run distribution checks on the repaired data and compare with the last good version.
- Publish a new dataset version, withdraw affected versions, and tell consumers which runs read them.
- Close the gap: register the schema with a compatibility mode, add a producer–consumer contract test, and add a semantic check (ranges, units, sums) that a type checker cannot do.
Choosing a compatibility mode. Schema registries check each new schema version against earlier ones. In Confluent Schema Registry the default, BACKWARD, checks only against the latest version and means consumers are upgraded first; FORWARD means producers upgrade first; FULL allows only adding or removing optional fields, so either side can upgrade independently; *_TRANSITIVE variants check against all earlier versions (Confluent). Feedback datasets are read long after they are written (reward-model retrains, ablations, audits), so a reasonable default for feedback records is FULL_TRANSITIVE, relaxed to BACKWARD_TRANSITIVE when a field must become required. No mode catches semantic changes such as units; those need value-level checks.
Comms. Consumer owners: affected versions, which runs read them, the corrected version. Producer team: the contract test that failed or was missing.
Post-incident checks. Contract tests run in the producer's CI against every registered consumer; the registry rejects incompatible versions; distribution checks gate every export.
Illustrative. Interface v2 for W3 rubrics replaces the boolean met on each rubric item with a three-level score (0 not met, 1 partly met, 2 met), and writes JSON directly to storage without going through the registry. The exporter treats any non-zero value as met, so "partly met" becomes full credit. Mean rubric reward per response rises from 0.55 to 0.71 at the deploy, which the export's distribution check flags at a threshold of ±0.05. Lineage shows 2,400 graded responses written by v2, none yet exported. Fix: the exporter reads score / 2 for v2 records and met for v1, keyed on the schema version field; the schema is registered under FULL_TRANSITIVE with the new field optional; a contract test asserts that the reward for a partly met item lies strictly between 0 and its weight. Severity: SEV-4. Had the export run, every RL step using those rewards would have over-rewarded partial compliance.
Runbook 5 · Sensitive-data leak
| Scenario | Sensitive data reaches people or places it should not: personal data, credentials or confidential content in prompts, model samples or agent tool outputs shown to raters without clearance; an export written to the wrong destination or shared with a vendor outside its agreement; or accounts extracting content. |
|---|---|
| Detection signals | PII or secret-scanner hits on served items (M19); a rater's "report content" action; access anomalies (views far above submissions); data-loss-prevention alerts on exports; a vendor report. |
| Severity | SEV-1 if personal data or credentials reached unauthorised parties. SEV-2 if exposure was limited to authorised raters but outside the approved classification. SEV-3 if caught by the scanner before serving. |
| Containment levers | Pull items from queues, buffers and caches; revoke exposed credentials; suspend vendor access; freeze exports. |
- Stop serving the affected items: remove them from queues, the sample buffer, render caches and offline caches.
- Rotate credentials immediately if any secret was exposed. Rotation does not wait for scoping.
- Bring in privacy and legal now, not after scoping. Under the GDPR, a controller must notify the supervisory authority within 72 hours of becoming aware of a personal-data breach unless it is unlikely to pose a risk to individuals, and a processor must notify the controller without undue delay (GDPR Art. 33). The clock starts at awareness, so the timestamp of the first report is evidence.
- Scope the exposure: which items, which fields, which accounts viewed them and when (access logs), and which exports or copies contain them.
- Purge copies: exports, caches, analytics logs, vendor systems. Request written deletion confirmation from vendors.
- Fix the filter at ingest, then rescan the whole campaign and any other campaign fed by the same source. Treat automated scanners as one layer: Presidio states it cannot guarantee finding all sensitive information (Presidio), so add source-specific rules and a manual sample.
- Resume only with the new scan as a hard gate at ingest.
Comms. Owned by privacy and legal: regulators, affected individuals and data owners as required. Raters who viewed the content: instructions not to retain or share it, through the vendor. Researcher: affected items and replacement plan.
Post-incident checks. Secret and PII scanning at ingest for every source, with source-specific patterns (environment dumps, API key formats); classification on every campaign (launch item D3); access logs retained long enough to scope an incident; deletion attestations on file.
Illustrative. An expert reviewing a W2 transcript uses "report content" on step 37: a tool call printed the environment of the agent's sandbox, including an API key and two personal email addresses. On-call pulls the transcript, rotates the key within the hour, and rescans all 2,000 transcripts with an added environment-dump pattern: 14 transcripts contain credentials and 31 more contain email addresses. Access logs show 9 experts viewed affected steps. Privacy and legal are engaged at the first report; their assessment decides notification. The 45 transcripts are re-rendered with redaction and returned to the queue; review time already spent on them (45 × 35 min ≈ 26 hours, about $3,150 at $120/h) is kept because redaction does not change the steps under review. Severity: SEV-2 pending the privacy assessment, SEV-1 if the key or addresses belong to real third parties.
Runbook 6 · Vendor SLA miss
| Scenario | A vendor delivers fewer rater-hours than committed, misses turnaround times, or falls below the contracted quality level, putting a dated consumer at risk. |
|---|---|
| Detection signals | Delivered versus committed hours per week (M6); queue age and turnaround p90; active raters per day; vendor-level gold accuracy against the contract threshold. |
| Severity | SEV-4 normally. SEV-3 when a dated consumer (a scheduled retrain) is at risk. |
| Containment levers | Shift share to a second qualified vendor; reduce scope to a partial dataset the consumer accepts; extend the timeline. |
- Measure against the contract's definitions: hours as submitted or accepted, turnaround from assignment or from release. Disputes start with mismatched definitions.
- Rule out platform causes before escalating. Check task starvation (empty queues, TTFS incidents), interface outages, qualification or onboarding backlogs on the platform side, and task difficulty: if actual minutes per label exceed the estimate, effective pay per task falls and raters move to other work.
- Decision: platform-caused shortfall → fix it and tell the vendor; vendor-caused → step 4.
- Escalate with data under the contract and ask for a recovery plan with weekly numbers.
- Reroute part of the volume to a second vendor already qualified on the task. A second vendor only helps if qualification was done before it was needed.
- Re-plan with the consumer: a partial dataset by the date, or the full dataset later.
- Apply contract remedies (credits) and record the miss in the vendor scorecard.
Comms. Vendor: numbers against definitions. Researcher and consumer owner: revised dates and options. Finance: credits and cost impact.
Post-incident checks. A second vendor qualified for each campaign class; capacity dashboards show committed versus delivered hours; qualification throughput is monitored as a platform metric.
Illustrative. The vendor commits 3,000 rater-hours per week and delivers 1,900 in the first week. At that rate the 1,895 rater-hours of collection take about one week instead of 0.63, about 2.6 extra days on the request-to-mix path. Step 2 finds that 40 of the 150 raters never started: their qualification tests sat in a platform-side expert review queue. That accounts for 40 × 20 = 800 of the 1,100 missing hours, and it is a platform cause. Fixing the review queue (auto-grading the objective qualification items, human review only for borderline scores) recovers it. The remaining 300-hour shortfall is the vendor's and is handled under the contract. Severity: SEV-4.
Tested helpers used by the runbooks
The runway calculation, the collusion screen, the burn-rate formula used by the alerts in the metric catalogue, and the rubric reward exporter used in the design sketches:
"""ops14.py: small operational helpers used by the Chapter 14 runbooks and design sketches."""
from dataclasses import dataclass
import numpy as np
def buffer_runway_min(buffer_items, concurrent_raters, minutes_per_item):
"""Minutes until a pre-generated buffer empties if generation stops entirely."""
consumption_per_min = concurrent_raters / minutes_per_item
return buffer_items / consumption_per_min
def find_colluders(R, thr=0.85):
"""Collusion screen after KhudaBukhsh et al. (2014): centre each item's column,
take cosine similarity between raters, link pairs above thr, return connected groups.
R: raters x items matrix of numeric labels on a shared item set (overlap or gold)."""
X = R - R.mean(axis=0, keepdims=True)
n = np.linalg.norm(X, axis=1, keepdims=True)
X = X / np.where(n == 0, 1, n)
S = X @ X.T
m = R.shape[0]
adj = {i: {j for j in range(m) if j != i and S[i, j] > thr} for i in range(m)}
seen, groups = set(), []
for i in range(m):
if i in seen or not adj[i]:
continue
stack, g = [i], set()
while stack:
k = stack.pop()
if k in g:
continue
g.add(k); stack.extend(adj[k] - g)
seen |= g; groups.append(sorted(g))
return groups
def burn_rate(bad, total, slo):
"""Error-budget burn rate: observed bad fraction divided by the allowed bad fraction."""
return (bad / total) / (1 - slo)
@dataclass
class RubricItem:
criterion: str
weight: float # positive weight, relative scale
met: bool # grader verdict for this response
def export_rubric_reward(items):
"""Weighted fraction of rubric items met, in [0, 1]: the scalar sent to the RL reward service."""
w = sum(i.weight for i in items)
assert w > 0, "rubric needs positive total weight"
return sum(i.weight for i in items if i.met) / w
Tests for these helpers and for the spec linter; all pass as shown:
"""Tests for the Chapter 14 artifacts. Run: python3 -m pytest -q test_ch14.py (or python3 test_ch14.py)."""
import os, yaml, numpy as np
from campaign_lint import derive, lint, wilson
from ops14 import buffer_runway_min, find_colluders, burn_rate, export_rubric_reward, RubricItem
HERE = os.path.dirname(os.path.abspath(__file__))
W1 = yaml.safe_load(open(os.path.join(HERE, "w1_campaign.yaml")))
def test_w1_sizing_matches_example_sheet():
d = derive(W1)
assert d["labels"] == 24000
assert abs(d["assignments"] - 25260) <= 5
assert abs(d["rater_hours"] - 1895) <= 2
assert abs(d["labour_usd"] - 75780) <= 100
assert d["pool_weeks"] == 0.63
def test_w1_lint_flags_thin_gold():
_, f = lint(W1)
assert [x for x in f if x[0] == "BLOCK"] == []
assert any("gold items per rater" in m for _, m in f)
def test_wilson_width():
lo, hi = wilson(40, 50)
assert 0.66 < lo < 0.68 and 0.88 < hi < 0.90
def test_buffer_runway():
# 2,000 pairs, 60 concurrent raters at 4.5 min/label -> 150 min
assert round(buffer_runway_min(2000, 60, 4.5)) == 150
def test_find_colluders():
rng = np.random.default_rng(0)
R = rng.integers(1, 6, size=(20, 60)).astype(float) # 20 raters x 60 items, 1-5 scale
R[3] = R[7]; R[11] = R[7] + rng.normal(0, 0.1, 60) # raters 3, 7, 11 copy each other
groups = find_colluders(R, thr=0.85)
assert {3, 7, 11} in [set(g) for g in groups]
def test_burn_rate():
# SLO: 95% of item fetches within 5 s -> budget 5%; 72% slow fetches in the window = 14.4x
assert abs(burn_rate(bad=720, total=1000, slo=0.95) - 14.4) < 1e-9
def test_rubric_export():
items = [RubricItem("cites statute", 3.0, True), RubricItem("no hedging", 1.0, False),
RubricItem("correct party names", 2.0, True)]
r = export_rubric_reward(items)
assert abs(r - 5 / 6) < 1e-9
if __name__ == "__main__":
for k, v in list(globals().items()):
if k.startswith("test_"):
v(); print("ok", k)
$ python3 test_ch14.py
ok test_w1_sizing_matches_example_sheet
ok test_w1_lint_flags_thin_gold
ok test_wilson_width
ok test_buffer_runway
ok test_find_colluders
ok test_burn_rate
ok test_rubric_export
Metric catalogue
How to read the catalogue. Each metric has an ID (M1–M23) that the runbooks and alert rules cite, a definition precise enough to implement, a formula, its value in W1 where one exists, a default target, the dashboard panel where it lives and the alert, if any. Three rules shaped the list. First, every metric answers a question someone acts on; a metric with no owner and no action is removed. Second, speed, quality, integrity and cost metrics are reported per campaign and per slice (rater cohort, vendor, prompt slice, checkpoint, client build), because averages hide the incidents in runbooks 2 and 3. Third, at most one alert per metric, and only page on conditions that need action within the hour.
Speed and capacity
| ID | Metric | Definition and formula | W1 value | Default target | Dashboard | Alert |
|---|---|---|---|---|---|---|
| M1 | Time-to-first-sample (TTFS) | Time from a rater's request for the next item to the item being fully rendered. SLI: share of fetches served within 5 s. | Target p50 ≤ 2 s, p95 ≤ 5 s | SLO 95% of fetches ≤ 5 s | Speed row: p50/p95 lines per campaign | Burn rate 14.4 over 1 h and 5 min, or 6 over 6 h and 30 min: page |
| M2 | Request-to-mix latency | Days from an accepted request to the dataset version being included in a training mix, split by stage. | 21 days (3 + 4 + 6 + 3 + 2 + 3) | 7 days | Stacked stage bars per campaign | None; weekly review. Stage over its budget: ticket |
| M3 | Buffer runway | Buffer items ÷ current consumption per minute: minutes until empty if generation stops. | ≈ 150 min at 60 concurrent raters (assumed) | ≥ the longest endpoint outage seen at peak; ≥ 240 min after the W1 incident | Speed row | < 60 min for 5 min: page |
| M4 | Oldest queued item age | Age of the oldest released, unassigned item. | Not specified | < 1 h for single-label tasks | Speed row | > 4 h: ticket |
| M5 | Launch lead time | Request accepted → first production label. | 7 days (scoping 3 + guidelines and pilot 4) | ≤ 2 days for campaigns built from a template | Platform overview | None |
| M6 | Delivered vs committed hours | Rater-hours delivered ÷ committed, per vendor, rolling 7 days, using the contract's definition of an hour. | Plan 3,000 h/week | ≥ 95% | Capacity panel per vendor | < 85% over 7 days: ticket |
| M7 | Labels per rater-hour | Submitted labels ÷ active rater-hours. | 60 ÷ 4.5 ≈ 13.3 | Within ±30% of the pilot rate | Capacity panel | None (input to M15 and planning) |
Quality
| ID | Metric | Definition and formula | W1 value | Default target | Dashboard | Alert |
|---|---|---|---|---|---|---|
| M8 | Gold accuracy | Correct gold answers ÷ gold items answered. Per rater (cumulative, with Wilson interval) and pool (last 100 and last 500 gold items). | Rater threshold 80%; pool ≈ 86% (illustrative) | Rater ≥ 80% with ≥ 30 gold items; pool floor 75% | Quality row | Pool < 75% in either window: page and auto-pause |
| M9 | Overlap agreement | Share of rater pairs on the same multi-labelled item who give the same label; also Cohen's κ \(=(p_o-p_e)/(1-p_e)\) or Krippendorff's α for more than two raters. | 72%; κ ≈ 0.51 (see note) | Within 10 points of pilot | Quality row, with κ beside it | Drop > 10 points vs campaign baseline: ticket |
| M10 | Tie rate | Ties ÷ labels. | 8% | Within ±5 points of pilot | Label-distribution panel | Outside band for 6 h: ticket |
| M11 | Left-choice rate | Non-tie choices for the response displayed first ÷ non-tie choices, using the render receipt. | ≈ 50% (randomised) | Pool 50% ± 3 points; per rater flagged if \(|z|>3\) with ≥ 100 choices (outside 35–65%) | Quality row | Pool outside band: ticket |
| M12 | Longer-response preference | Non-tie choices for the longer response ÷ non-tie choices, per slice. | Not specified | No fixed target; compare with pilot and with a length-controlled audit | Label-distribution panel | None; reviewed before export |
| M13 | QA reject rate | Labels rejected in QA ÷ labels reviewed. | 8% | ≤ 10% | Quality row | > 15% in a day: ticket |
Integrity
| ID | Metric | Definition and formula | W1 value | Default target | Dashboard | Alert |
|---|---|---|---|---|---|---|
| M14 | Collusion groups | Connected groups of raters whose mean-centred answer vectors on shared items have cosine similarity above 0.85 (after KhudaBukhsh et al., 2014). | 0 (runbook 3 incident: 1 group of 5) | 0 | Integrity row | Any group: ticket to integrity review |
| M15 | Low-effort flag rate | Raters whose median time per item is below a floor (W1: 40 s), ÷ active raters. | 4% (6 of 150) | < 5% | Integrity row | None; feeds the review queue |
| M16 | AI-use signal rate | Free-text submissions with a large paste, typing cadence inconsistent with the text, or a high AI-text score, ÷ free-text submissions. | n/a (no free text in W1); applies to W2 continuations | Trend only | Integrity row | None; never a sole basis for action |
Pipeline, governance, cost and adoption
| ID | Metric | Definition and formula | W1 value | Default target | Dashboard | Alert |
|---|---|---|---|---|---|---|
| M17 | Schema reject rate | Records rejected at ingest ÷ records received. | 0% | < 0.1% | Pipeline panel | > 0.1% over 15 min: ticket |
| M18 | Lineage completeness | Exported rows with all lineage keys (sample, prompt, checkpoint, rater, guideline, spec) ÷ exported rows. | 100% required | 100% | Export report | < 100%: export blocked |
| M19 | Sensitive-data hits on served items | Scanner or rater-report hits on items already shown to raters. | 0 | 0 (hits at ingest are blocked and not counted here) | Governance panel | Any: page |
| M20 | Cost per useful label | Total cost (labour + platform + generation) ÷ labels surviving QA. | $75,780 ÷ 18,400 ≈ $4.12 per useful comparison (labour only) | At or below the spec's target | Cost row | Forecast > budget ceiling: ticket |
| M21 | Rework rate | Labels relabelled or repaired ÷ labels collected. | Runbook 3 incident: 1,150 of 24,000 ≈ 4.8% | < 5% | Cost row | None |
| M22 | Researcher self-serve rate | Campaigns launched and inspected without a platform-engineer change ÷ campaigns launched. | Not specified | Rising quarter on quarter | Platform overview | None |
| M23 | Harmful-content exposure | Minutes per rater-day on items tagged as potentially harmful. | n/a for W1 | Below the campaign's cap | Welfare panel | Cap reached: assignment stops for that rater-day |
Table 14.4. Metric catalogue. W1 values are illustrative; "not specified" means the reference workload does not fix a value. Default targets are starting points to be replaced by each platform's own baseline.
Raw pairwise agreement depends on how often raters would agree by chance. Assume (illustrative) W1 label marginals of 46% A, 46% B and 8% tie. Chance agreement is \(p_e = 0.46^2 + 0.46^2 + 0.08^2 \approx 0.43\), so the observed 72% gives \(\kappa = (0.72 - 0.43)/(1 - 0.43) \approx 0.51\). The 72% is close to the 72.6% that Ouyang et al. (2022) report among their trained labelers, which is a useful sanity anchor, while κ ≈ 0.51 is the number to compare across campaigns whose tie rates differ. If the tie rate rose to 20% with A and B at 40% each, \(p_e\) would be 0.36 and the same 72% would be κ ≈ 0.56. Read the other way, raters of unchanged quality (κ ≈ 0.51) would then show raw agreement of 0.36 + 0.51 × 0.64 ≈ 69%, so an agreement change without a κ change usually means the label distribution moved, not rater quality.
Notes on specific metrics. M1 uses the multiwindow, multi-burn-rate pattern from the Google SRE Workbook, which gives burn rate 14.4 over 1 hour (with a 5-minute short window) and 6 over 6 hours (with a 30-minute short window) as page thresholds and burn rate 1 over 3 days as a ticket (Google SRE Workbook). Because the W1 latency target is a p95, the SLO is 95% of fetches within 5 s and the error budget is 5%, so the fast-burn page fires when about 72% of fetches in both windows are slow: in practice an outage, not a slowdown. Slowdowns surface on the p95 panel and as tickets. M8 uses two windows for the same reason: the last 500 gold items give a tight estimate but react slowly; the last 100 react within a few hours (runbook 2). M11 needs the render receipt, not the intended order, which is the lesson of runbook 2. M12 has no fixed target because some length preference is legitimate, but it should be inspected before export: reward models trained on preference data readily learn length, and a length-only reward can reproduce much of the measured RLHF gain on some tasks (Singhal et al., 2023). M16 is trend-only because AI-text detectors are unreliable under paraphrasing (Sadasivan et al., 2023); see the detection design sketch below.
Alert rules
The rules below implement the alerts in the catalogue as Prometheus-style rules. Metric names are illustrative; the file parses as YAML, and the thresholds match the table.
# alerts.yaml: Prometheus-style rules for the metric catalogue (metric names are illustrative).
# TTFS SLI: share of item fetches served within 5 s; SLO 95% (matches the W1 p95 <= 5 s target),
# so the error budget is 5%. Burn-rate pairs follow the Google SRE Workbook's starting points.
groups:
- name: rl-data-platform
rules:
- alert: TTFSFastBurn # M1, page
expr: |
(1 - sum(rate(item_fetch_le_5s_total[1h])) by (campaign) / sum(rate(item_fetch_total[1h])) by (campaign)) > 14.4 * 0.05
and
(1 - sum(rate(item_fetch_le_5s_total[5m])) by (campaign) / sum(rate(item_fetch_total[5m])) by (campaign)) > 14.4 * 0.05
labels: {severity: page, runbook: endpoint-outage}
- alert: TTFSSlowBurn # M1, page
expr: |
(1 - sum(rate(item_fetch_le_5s_total[6h])) by (campaign) / sum(rate(item_fetch_total[6h])) by (campaign)) > 6 * 0.05
and
(1 - sum(rate(item_fetch_le_5s_total[30m])) by (campaign) / sum(rate(item_fetch_total[30m])) by (campaign)) > 6 * 0.05
labels: {severity: page, runbook: endpoint-outage}
- alert: BufferRunwayLow # M3
expr: buffer_items / clamp_min(rate(items_served_total[15m]) * 60, 0.001) < 60
for: 5m
labels: {severity: page, runbook: endpoint-outage}
- alert: GoldAccuracyShortWindow # M8, last 100 gold items
expr: gold_accuracy_last_100 < 0.75
labels: {severity: page, action: auto_pause, runbook: quality-collapse}
- alert: GoldAccuracyLongWindow # M8, last 500 gold items
expr: gold_accuracy_last_500 < 0.75
labels: {severity: page, action: auto_pause, runbook: quality-collapse}
- alert: AgreementDrop # M9
expr: overlap_agreement_24h < overlap_agreement_campaign_baseline - 0.10
labels: {severity: ticket, runbook: quality-collapse}
- alert: CollusionGroupFound # M14
expr: collusion_groups_nightly > 0
labels: {severity: ticket, runbook: fraud-ring}
- alert: SchemaRejects # M17
expr: sum(rate(ingest_rejected_total[15m])) / sum(rate(ingest_records_total[15m])) > 0.001
labels: {severity: ticket, runbook: schema-break}
- alert: SensitiveDataServed # M19
expr: increase(scanner_hits_on_served_items_total[10m]) > 0
labels: {severity: page, runbook: data-leak}
- alert: VendorHoursShortfall # M6
expr: vendor_hours_delivered_7d / vendor_hours_committed_7d < 0.85
labels: {severity: ticket, runbook: vendor-sla}
Metric anti-patterns. Four recur. Paying or ranking raters on throughput (M7) rewards low effort; throughput is a planning input, never an incentive on its own. Treating agreement as quality on subjective tasks (M9) pushes guidelines toward easy, shallow criteria; disagreement on genuinely contested items is information, and aggregation methods that keep it, such as soft labels, are often better for reward models than forced consensus. Recognisable gold (launch item Q2) turns M8 into a measure of attention to gold. Campaign-level averages hide slice-level incidents: every quality and integrity panel needs a slice selector.
Design sketches for common platform projects
What a design sketch is. Each sketch below is the one-to-two-page design a platform team writes before building: the problem in measurable terms, the constraints that rule options out, an architecture sketch, the data model, the key decisions with a recommended default and when to deviate, the metrics that will show whether it worked, and an ordered rollout. The five projects recur on every RL data platform because they sit on the four north-star metrics: time-to-first-sample, request-to-mix latency, cost per useful label and label quality. The rollouts are ordered steps, not schedules.
Sketch 1 · Expert transcript-review interface
Problem. Experts review long agentic transcripts: they must find the first step where the agent went wrong, classify the failure, and write a corrected continuation from that step. This produces step-level (process) labels and correction data. Process supervision at scale has precedent: PRM800K collected 800,000 step-level human labels on model-generated maths solutions (Lightman et al., 2023). Agent transcripts are harder than maths solutions because steps include tool calls whose outputs change the state the next step sees. The interface is the main lever on cost, since expert time dominates, and on agreement, since locating "the first failing step" is ambiguous when an early, subtle mistake only shows its effect later.
Constraints. Transcripts are long (W2: mean 60 steps, about 25,000 tokens), and tool outputs can be large. Tool outputs must be shown exactly as the agent saw them: re-executing tools at review time is non-deterministic and can have side effects, so outputs are replayed from stored snapshots. Tool outputs may contain sensitive data (runbook 5). Expert minutes are expensive, so every navigation action matters.
Architecture. A render service pre-indexes each transcript once at ingest: per-step offsets, a one-line summary per step, token counts, tool name, automated error markers (non-zero exit codes, exceptions, empty results) and a redaction pass. The browser loads the step index first and renders the list immediately, then fetches step bodies on demand with the visible step's neighbours prefetched, so render time no longer grows with transcript length. The three-pane layout keeps the step list, the selected step's detail (model turn, tool call and arguments, replayed output, and a diff against expected output where one exists) and the review panel visible together. Public evaluation tooling uses the same pattern for browsing agent logs; Inspect, the UK AI Security Institute's open-source evaluation framework, includes a log viewer for inspecting sample transcripts (UK AISI, Inspect).
Data model.
Transcript { transcript_id, source_run_id, checkpoint_id, task_id, n_steps, redaction_version }
Step { transcript_id, idx, role, tool_name?, args_ref?, output_snapshot_ref?, tokens,
summary, auto_flags[] }
Review { review_id, transcript_id, reviewer_id, schema_version, guideline_version,
first_fail_step | null, -- null = no failure found
fail_type: enum(wrong_tool, wrong_args, misread_output, unjustified_claim,
gave_up, unsafe_action, other),
uncertain_range: [lo, hi]?, -- optional, lo <= first_fail_step <= hi
confidence: 1..3,
continuation: { from_step, turns[] } -- structured tool calls + text
steps_viewed[], active_ms, render_receipt_ref }
Adjudication{ transcript_id, review_ids[2], final_step, final_type, adjudicator_id, notes }
Key decisions.
| Decision | Options | Default | Deviate when |
|---|---|---|---|
| Rendering | Whole transcript at once; pre-indexed with lazy step bodies | Pre-index server-side, virtualised list, lazy bodies with neighbour prefetch | Transcripts are short (under ~20 steps) and whole rendering already meets the target |
| Tool outputs | Re-execute; replay snapshots | Replay stored snapshots | Never for side-effecting tools; re-execution only in a sandbox for an explicit "what if" experiment |
| Failing-step label | Single step; step plus uncertainty range | Single step plus optional range and a confidence | Agreement within ±2 is already high; drop the range to save time |
| AI pre-flags (suspected failing steps) | Hidden; shown up front; shown after an initial answer | Shown after the expert commits an initial answer, so the flag can correct misses without anchoring the first look | An A/B test shows no anchoring effect on agreement with adjudicated answers |
| Continuation editor | Free text; structured turns | Structured: tool calls validated against the tool schema, free text for messages | The domain has no tools (pure reasoning) |
| Disagreement | Average; adjudicate | Adjudicate when two reviews differ by more than 2 steps or in failure type | Disagreement is the signal of interest (keep both as soft labels) |
Metrics. Render p95 (target ≤ 1.5 s); minutes per transcript; agreement on first failing step, exact and within ±2; adjudication rate; QA acceptance of continuations; steps viewed before answering (a low count on long transcripts is a low-effort signal).
2,000 transcripts at a mean of 35 minutes is about 1,167 expert-hours, about $140,000 at $120/h, or $70 per transcript; double review of 10% adds about 117 hours (about $14,000). Each minute saved per transcript is worth 2,000 ÷ 60 ≈ 33 expert-hours, about $4,000. A target of 28 minutes (an assumption, to be checked in step 3 of the rollout) would save about 233 hours, about $28,000. On the 200 double-reviewed transcripts, the reported 81% agreement within ±2 steps means about 38 reviews differ by more than 2 steps, so at least 38 adjudications, more where the failure types also differ.
Rollout.
- Build the read-only viewer (index, list, detail with replayed outputs) and measure render p95 on the 50 longest transcripts.
- Add the review panel and continuation editor; validate continuations against tool schemas at submit.
- Run five experts on the same 40 transcripts; measure minutes per transcript and agreement, and compare with the previous tool on a matched set.
- A/B test the AI pre-flags (hidden vs shown after initial answer) on agreement with adjudicated answers.
- Turn on double review for 10% and the adjudication queue; ramp to the full expert pool.
Sketch 2 · Cutting time-to-first-sample
Problem. Time-to-first-sample (TTFS) is the delay between a rater asking for the next item and seeing it. When samples are generated on demand from live endpoints, TTFS includes model generation time for both responses, which for long coding answers can take many seconds and varies with endpoint load. Slow and variable first samples waste paid time, break concentration and inflate abandonment. W1 targets p50 ≤ 2 s and p95 ≤ 5 s.
Constraints. Arms are pinned to checkpoints, and checkpoints change; a pre-generated sample from a replaced checkpoint is no longer valid. Endpoint capacity is shared. Pre-generating costs compute for samples that may never be labelled (QA rejects, early stops, invalidation).
Architecture and the latency budget. Separate the fast path from generation. Generation workers fill a buffer keyed by campaign and checkpoint pair, run validity checks (non-empty, not truncated, not identical, no scanner hits) before an item becomes ready, and stamp the checkpoint IDs. The assignment service decides eligibility, overlap and gold injection when an item is released, so a fetch is a single indexed pop with a lease. The client prefetches the next item while the rater works on the current one; with 4.5 minutes per item, the next item is ready long before it is needed, so TTFS for every item after the first in a session is essentially render time. On the serving side, automatic prefix caching reuses the KV cache of shared prompt prefixes (system prompts, multi-turn context) across requests (vLLM docs), building on paged KV-cache memory management (Kwon et al., 2023), which shortens the slow path when it is taken.
The p95 target sets the buffer hit rate. If buffer hits are served in under a second and misses take longer than 5 s, then p95 ≤ 5 s requires a miss rate below 5%, so the hit rate must exceed 95%; target ≥ 99% for margin. Buffer size is set by outage coverage, not by refill speed: by Little's law the items needed to cover a refill lead time are consumption rate × lead time, which is small when generation is healthy, while covering an outage of length \(T\) needs consumption rate × \(T\).
-- Lease the next ready pair for a rater (PostgreSQL; illustrative, not executed here).
-- SKIP LOCKED lets many concurrent fetches pop distinct rows without blocking each other.
UPDATE sample_buffer SET state = 'leased', leased_by = $rater, lease_expires = now() + interval '15 min'
WHERE pair_id = (
SELECT pair_id FROM sample_buffer
WHERE campaign_id = $campaign AND state = 'ready'
AND checkpoint_a = $pinned_a AND checkpoint_b = $pinned_b
AND pair_id NOT IN (SELECT pair_id FROM labels WHERE rater_id = $rater)
ORDER BY priority DESC, generated_at
LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING pair_id, payload_ref, display_order;
Data model. BufferEntry { campaign_id, pair_id, prompt_id, checkpoint_a, checkpoint_b, generated_at, validity_checks, state: ready | leased | consumed | invalidated, display_order, payload_ref }; Lease { pair_id, rater_id, leased_at, expires }; an Invalidation event from the checkpoint registry moves all ready entries for that checkpoint to invalidated.
Key decisions.
| Decision | Options | Default | Deviate when |
|---|---|---|---|
| Sample source | On demand; buffered; hybrid | Hybrid: buffer for the fast path, on-demand fallback behind a circuit breaker | Strictly on-policy live sessions (the rater converses with the model), where only streaming and prefix caching help |
| Buffer size | Refill-based; outage-based | Outage-based: consumption at peak × longest recent outage | Checkpoints rotate faster than the buffer drains; then size for refill and accept outage risk |
| Client prefetch | Off; next item; next k | Next item, lease extended on view | Items are huge (long transcripts): prefetch the index only |
| Assignment timing | At fetch; at release | At release, so fetch is one indexed pop | Assignment depends on live state (adaptive selection); keep fetch-time logic under a latency budget |
| Stale samples | Serve; discard | Discard on checkpoint change (invalidate event) | The spec explicitly allows a checkpoint range |
Metrics. TTFS p50/p95 split into assignment, payload fetch and render; buffer hit rate (≥ 99%); buffer runway (M3); invalidation waste (pairs discarded ÷ pairs generated); generation cost per labelled pair.
With 60 concurrent raters (assumed) consumption is about 13.3 pairs per minute, about 800 per hour. A healthy refill lead time of a minute needs only about 14 pairs in the buffer; the 2,000-pair buffer exists to cover about 150 minutes of outage, and the post-incident 3,200-pair target covers 4 hours. The cost of that coverage is invalidation: if the candidate checkpoint is replaced while the buffer is full, up to 3,200 generated pairs are discarded, about 16% of the 20,000 comparisons the campaign needs. That is the trade-off to state in the spec: buffer target, expected checkpoint changes during the campaign, and the accepted waste.
Rollout.
- Instrument TTFS by component on the current path; establish the baseline p50/p95.
- Add client prefetch; it needs no backend change and removes most per-item waits.
- Add the buffer with validity checks and checkpoint stamping; run it in shadow (filled, not served) to measure fill rate and invalidation.
- Serve from the buffer for one campaign with the on-demand fallback; compare TTFS and label quality with a control campaign.
- Add the registry invalidation hook and runway alert; make buffered mode the default in the spec template.
Sketch 3 · No-code campaign launcher
Problem. Launching a campaign needs an engineer for configuration, interface wiring and export, so launch lead time (M5) is days and the platform team is the bottleneck. Most campaigns are variations on a small number of templates (pairwise, rating, rubric, critique, transcript review), so most launches should need no engineer.
Constraints. Self-serve must not mean unsafe: governance items (data classification, vendor access, welfare) still need sign-off. Every launch must be reproducible from a stored spec. Custom interfaces must remain possible as an escape hatch.
Architecture. The launcher is a pipeline over an immutable, versioned spec. A form (or the YAML itself, for researchers who prefer it) produces the spec from a template per feedback type. Validation checks structure and types against a schema. Lint encodes the launch checklist as rules and derives sizing (the linter in the campaign section). Preview renders real samples from the pinned checkpoints in the real interface, so the requester sees what raters will see. Dry run runs scripted bot raters through the whole path and loads the export into the consumer's pipeline. Declarative interface configuration has precedent in open tooling: Label Studio describes labelling interfaces in an XML configuration in which, for example, a Pairwise control tag links two text objects for a pairwise choice (Label Studio).
Bot raters make the dry run test the detectors. A dry run with one well-behaved bot only proves the happy path. Use a set of scripted policies, each expected to trip a specific check: an always-left bot must trigger the left-choice flag (M11); a fast bot must trigger the low-effort flag (M15); a random bot must fail gold (M8); a perfect-on-gold bot must pass; two copying bots must form a collusion group (M14); a bot that submits every edge-case option must produce every enum value in the export (launch item T2). If a detector does not fire in the dry run, it will not fire in production.
Data model. Template { feedback_type, ui_component, default_spec, lint_rules[] }; CampaignSpec { spec_id, version, parent_version, body (YAML), created_by }, immutable once launched; LaunchRecord { spec_id, version, lint_report, preview_signoff, dry_run_report, approvals[], ramp_stage }. Spec edits after launch create a new version and a change-point marker on the dashboards.
Key decisions.
| Decision | Options | Default | Deviate when |
|---|---|---|---|
| Spec language | Form only; YAML/JSON with form on top; code | YAML/JSON as the source of truth, form as an editor | Researchers need logic (adaptive sampling): allow a code hook reviewed like code |
| Interface | Fixed templates; declarative config; custom component | Templates with declarative options; custom components through the feedback-type registry (sketch 5) | A one-off study: a custom component without registry overhead, marked non-reusable |
| Approval | None; owner; owner plus reviewer | Owner for template campaigns with clean lint; plus a quality reviewer for WARNs; plus privacy for sensitive data classes | Never relax privacy sign-off |
| Ramp | All at once; staged | 5% → 25% → 100% of pool, advancing on green dashboards | Tiny campaigns (under ~500 items) where the first stage would be a handful of items |
Metrics. Launch lead time (M5); self-serve rate (M22); lint findings per launch and how many were fixed before launch; post-launch spec edits per campaign (should fall); incidents whose root cause is a spec error.
In W1, scoping (3 days) and guidelines plus pilot (4 days) are a third of the 21-day request-to-mix time, and pipeline and export take another 2. A W1-style pairwise campaign built from a template with defaults should need only the researcher's prompts, arms, guidelines and pilot. The dry run moves export debugging ahead of collection, where it no longer extends the critical path. The linter's sizing (25,263 assignments, about 1,895 rater-hours, about $75,790 of labour) and its thin-gold warning arrive in seconds instead of in a review meeting.
Rollout.
- Write the launch checklist as lint rules and run them in CI on a repository of specs; launches still go through engineers.
- Add preview with real samples, then the dry run with the bot set and consumer load test.
- Build templates for the two most common feedback types and let researchers launch them with owner approval.
- Add the form editor and staged ramp; extend templates as the registry grows.
Sketch 4 · Low-effort and LLM-assisted work detection
Problem. Some raters spend too little effort per item, and some delegate to an LLM, which turns "human" feedback into model feedback and recycles the model's own biases into its reward signal. The base rate can be high where nothing prevents it: Veselovsky et al. (2023a) estimated that 33–46% of crowd workers used LLMs on an abstract-summarisation task, combining keystroke data with a synthetic-text classifier. Prevention helps but does not eliminate it: in a follow-up, asking workers not to use LLMs and raising the cost of doing so (for example disabling copy-paste) roughly halved use (Veselovsky et al., 2023b).
Constraints. False positives harm honest workers and vendor relationships, so no single detector can justify removal. Text-only AI detectors are unreliable: recursive paraphrasing sharply lowers detection rates across watermarking, neural, zero-shot and retrieval-based detectors (Sadasivan et al., 2023). Telemetry is personal data and needs a privacy basis and minimisation. Detection is adversarial: published thresholds get gamed.
Signals.
| Signal | Catches | False-positive risk | Use |
|---|---|---|---|
| Time on item vs item length | Skimming, random clicking | Experts are fast on easy items | Normalise by item length and difficulty; compare with the rater's own history |
| Paste events, typing cadence, focus loss | Text written elsewhere (including by an LLM) | Drafting in an editor; accessibility tools | Strong when combined with text signals; record counts and sizes, not content |
| Gold accuracy and consensus agreement | Low quality regardless of cause | Contested items; wrong gold | The main outcome signal; requires enough gold per rater |
| Position bias per rater | Default clicking | Small samples | Flag only at \(|z|>3\) with ≥ 100 choices |
| AI-text score on rationales and continuations | Unedited model text | High; unreliable under paraphrase | Ranking feature only, never decisive |
| Answer similarity and shared devices | Copying, multi-accounting | Shared offices or networks | Collusion screen (M14); runbook 3 |
Combining evidence. Each signal becomes a per-rater rate, shrunk toward the pool rate when the rater has few items so that a rater with 3 fast items out of 10 does not outrank one with 30 out of 100. A simple, effective form is a beta-binomial posterior mean, \((k + a)/(n + a + b)\), where \(k\) of \(n\) items tripped the signal and \(a/(a+b)\) is the pool rate with prior strength \(a+b\). With a pool rate of 5% and prior strength 20 (\(a=1, b=19\)), 3 of 10 gives \((3+1)/(10+20) \approx 0.13\) and 30 of 100 gives \((30+1)/(100+20) \approx 0.26\): the second rater ranks higher, as it should. The ranked queue goes to trained reviewers, who see all signals together with sample items; decisions act on the account (coach, restrict to other tasks, remove, with appeal) and separately on its labels (quarantine, down-weight, relabel).
Data model. InteractionEvent { rater_id, item_id, kind: focus | blur | paste | key_burst | submit, ts, size } (no content); RaterDaySummary { rater_id, day, items, median_s, paste_events, left_rate, gold_n, gold_correct }; Flag { rater_id, signal, value, threshold, window, evidence_refs[] }; Decision { rater_id, reviewer_id, action, rationale, label_action, appeal_state }.
Key decisions. Prevent before detecting: state the AI-use policy in the task, disable paste where text should be original, and design tasks where AI help is visible (for example require references to specific steps). Detect to rank, not to judge. Separate label actions from account actions, because a rater's labels can be bad on one campaign while the rater is fine on others. Publish the policy, not the thresholds. Re-validate detectors on each new task type, since a threshold calibrated on 4-minute pairwise items means nothing on 35-minute transcript reviews.
Metrics. Precision of flags in review (share confirmed); time from flag to decision; appeal overturn rate (high means the detector or reviewers are miscalibrated); pool gold accuracy after removals; share of labels quarantined (M21).
In W1, 4% of raters, 6 of 150, have a median time below 40 s against a pool median of 4.0 min. At about 168 assignments per rater, their output is about 1,000 labels. Before acting, the review checks their gold accuracy and position rate: a fast rater with 90% on qualification gold and a 50% left rate is probably an expert on easy items, while one with 55% gold and a 70% left rate is clicking. Only the second kind has labels quarantined; relabelling 168 labels costs about 12.6 rater-hours, about $500, per removed rater.
Rollout.
- Ship the interaction telemetry with privacy review, recording counts and sizes only.
- Compute signals and the evidence score in shadow; have reviewers audit a random sample of flagged and unflagged raters to estimate precision and recall.
- Open the review queue with decisions limited to coaching and label quarantine.
- Add account actions with an appeal path once audit precision is acceptable; re-validate on each new task type.
Sketch 5 · Adding a new feedback type
Problem. Research needs a feedback type the platform does not support. The W3 case is rubric data for non-verifiable RL: experts write a weighted rubric per prompt, graders score responses against it, and an AI grader then applies the rubrics as the RL reward. Instance-specific rubrics used as rewards have published support: Rubrics as Rewards reports up to 31% relative improvement on HealthBench over Likert-style LLM-judge rewards (Gunjal et al., 2025). A new type touches every layer: schema, interface, validation, quality metrics, aggregation, export and the consumer.
Constraints. The schema will evolve, and old data must stay readable (runbook 4). Expert time is the budget. The AI grader is only a valid reward if it agrees with humans at the item level (W3 target ≥ 0.8). Rubrics themselves vary in quality and must be reviewed.
Architecture: a feedback-type registry. Make "feedback type" a plugin with seven parts, so the second new type costs much less than the first:
| Part | Contents | W3 rubric instance |
|---|---|---|
| Schema | Versioned record schema registered with a compatibility mode | rubric_grade.v1 below, FULL_TRANSITIVE |
| Interface component | Authoring and grading views, render receipt | Rubric editor (8–12 items with weights); grading view, one verdict per item per response |
| Validators | Structural plus semantic checks at submit and ingest | 8–12 items, positive weights, criterion length, every item has a verdict |
| Quality metrics | Agreement and gold definitions for this type | Item-level human–human and human–AI agreement; rubric review pass rate |
| Aggregator | How multiple labels combine | Majority per item verdict; adjudication on ties |
| Exporter | Conversion to the consumer's format | Weighted fraction of items met, in [0, 1], to the RL reward service |
| Migrations | Version-aware readers for every past schema version | v1 only at launch; any graded-score change is v2 with a tested reader |
Data model. The record schema, which rejects a non-boolean met (the silent break in runbook 4); it was checked with a JSON Schema validator against a valid instance and against one with met: 2, which is rejected:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "rubric_grade.v1",
"type": "object",
"required": ["schema_version", "prompt_id", "rubric", "grades"],
"properties": {
"schema_version": {"const": "rubric_grade.v1"},
"prompt_id": {"type": "string"},
"rubric": {
"type": "object",
"required": ["rubric_id", "author_id", "items"],
"properties": {
"rubric_id": {"type": "string"},
"author_id": {"type": "string"},
"items": {
"type": "array", "minItems": 8, "maxItems": 12,
"items": {
"type": "object",
"required": ["item_id", "criterion", "weight"],
"properties": {
"item_id": {"type": "string"},
"criterion": {"type": "string", "minLength": 10},
"weight": {"type": "number", "exclusiveMinimum": 0}
}
}
}
}
},
"grades": {
"type": "array", "minItems": 1,
"items": {
"type": "object",
"required": ["response_id", "grader_id", "grader_kind", "verdicts"],
"properties": {
"response_id": {"type": "string"},
"grader_id": {"type": "string"},
"grader_kind": {"enum": ["human", "ai"]},
"verdicts": {
"type": "array",
"items": {
"type": "object",
"required": ["item_id", "met"],
"properties": {"item_id": {"type": "string"}, "met": {"type": "boolean"}}
}
}
}
}
}
}
}
The exporter is export_rubric_reward in the helper module above: the weighted fraction of rubric items met. Normalising by total weight at export means authors can use any positive weight scale without changing the reward's range.
Key decisions.
| Decision | Options | Default | Deviate when |
|---|---|---|---|
| Item verdict | Binary; graded | Binary at first: easier to agree on and to check | Agreement data shows experts consistently need "partly met"; ship it as v2 with a migration |
| Weights | Fixed scale; free positive weights normalised at export | Free positive weights, normalised | The consumer needs absolute item weights (rare) |
| Authors vs graders | Same people; different people | Different people, so nobody grades against their own rubric | Expert supply is too thin; then add a second-grader sample |
| AI grader admission | Use immediately; gate on agreement | Gate: item-level human–AI agreement ≥ 0.8 on a human-graded holdout, checked per slice | Never skip; lower the bar only with the researcher's written acceptance |
| Rollout of the reward | Direct to training; shadow first | Shadow export to the reward service, logged but not used, until the agreement gate passes | None |
Metrics. Minutes per rubric and per graded response; rubric review pass rate; item-level human–human agreement; item-level human–AI agreement per slice; reward distribution per prompt (a reward pinned at 0 or 1 for all responses carries no signal); export schema rejects (M17).
3,000 prompts × 25 minutes ≈ 1,250 expert-hours of rubric writing; 3,000 prompts × 4 responses × 2 minutes ≈ 400 hours of grading. A holdout for the AI-grader gate of 300 prompts × 4 responses × 10 items gives 12,000 item verdicts. The naive 95% interval on an agreement of 0.80 at that size is about ±0.007, but verdicts within a prompt are correlated, so the effective sample size is closer to the number of prompts; treat 300 prompts as the unit and report the interval from a bootstrap over prompts. With the helper's example rubric (weights 3, 1, 2; the first and third met), the exported reward is (3 + 2) ÷ 6 ≈ 0.83, and the test pins it.
Rollout.
- Write the schema and validators; register the schema; write the exporter with tests, including a contract test against the reward service's loader.
- Build the authoring and grading views; run a pilot of 30 prompts with 5 experts; review rubrics and revise the guideline.
- Collect the human-graded holdout; measure human–human and human–AI item agreement per slice.
- Shadow-export AI-graded rewards for the full set while the gate is evaluated.
- Enable the reward for training once the gate passes; add the type's quality panels to the dashboard and its template to the launcher.
Open Problems
Each problem below is one the chapters ran into and could not close. Each links to where the evidence stands.
- Judges that stay calibrated while the policy moves. Routing works only as long as the judge's calibration holds, and every policy or checkpoint change can break it. In W1, a candidate whose answers grew 35% longer pushed audited agreement from 0.75 to 0.66 while the judge's confidence rose, and recalibration lowered coverage from 0.56 to 0.48. In W3, a grader upgrade fell from 0.84 to 0.74 item-level agreement while the RL reward kept climbing. Audits detect drift after the fact; there is no accepted way to predict which policy shifts will break a judge, or to size audits so that the compute spent on suspect checkpoints stays bounded (AI judges, Why human data still matters).
- Knowing a campaign's value before paying for it. Ablations, scaling curves and source-level Shapley values all measure value after collection and retraining; exact Shapley over four sources already needs 16 training runs. W1-b spent about $75,800 to learn that pairs from near-identical checkpoints carried almost no signal. Cheap predictors of value from a pilot, such as the low-margin share or ensemble disagreement, are plausible covariates, not validated forecasts (Data value, Prompt selection).
- Ground truth for agent process labels. Experts agree on W2's first failing step 58% of the time exactly and 81% within two steps, and the best automated attribution on a comparable public benchmark is far lower (Zhang et al. 2025). How to define a failing step when several steps contribute, how to train on a label that is really a distribution over positions, and how to scale review of 25,000-token transcripts without anchoring experts on AI suggestions remain open (Process supervision, Transcripts, Reward models).
- Checking the rubrics, not only the grader. The grader gate measures whether a model applies a rubric as humans do; nothing comparable measures whether the rubric captures what an expert would reward. A per-rubric agreement estimate from 40 judgements has a standard error near 0.06. In W3's integrity incident, flagged rubrics agreed with the AI grader more (0.91) than clean ones (0.84), which is what model-written rubrics would look like. Gunjal et al. (2025) found rubrics written without reference answers trained weaker policies. Rubric quality metrics are an open problem (Boundary, Transforms, AI feedback lineage).
- Detecting model-assisted work as models improve. Gold accuracy barely separates raters who copy a model from honest ones (0.77 against 0.80), and peer agreement points the wrong way. The peer-prediction score that separated them with AUC 0.98 in simulation depends on having the right model's labels to condition on. Asking people not to use LLMs and disabling paste roughly halved use without eliminating it (Veselovsky et al. 2023). As models get better and more varied, behaviour signals and text signals both weaken (Detection, Boundary).
- Request-to-mix below the collection constraint. Once waiting is removed, W1's 7.0 days are all process time, and further cuts need more rater-hours or less work per useful comparison. Continuous collection against weekly model updates, as in early RLHF practice, shortens the loop but makes every buffer stale faster and every calibration shorter-lived. How to run campaigns that never end, with on-policy samples, steady quality and a stable cost, is an operational design question without a published answer (Request-to-mix, Generation path, Preference learning to RLHF).
- Experiments powerful enough for quality. Interface changes are easy to evaluate on time and hard to evaluate on quality. W1's 2,000 overlap items give a minimum detectable effect of about 5.6 points on agreement with two arms; W2's 200 double-reviewed transcripts give about 19.6 points. Planted errors and gold carry most of the weight today. Cheaper, more sensitive quality outcomes for interface experiments would let platforms improve the interfaces that produce most of their cost (Interface experiments, Designing for quality).
- Whose judgement, and at what cost to the people giving it. When a label is a value judgement, the population is part of the specification, and a model's opinion is not a sample of any human population. Exposure budgets, opt-in routing and fair pay are engineered into the platform, but there is little public evidence on how population choices and welfare policies change the resulting models (Boundary, Welfare, Pay and incentives).
Citation
Cited as:
@article{cheng2026rldata,
title = "RL Data Platform",
author = "Cheng, Kevin",
journal = "Kevin's Notes",
year = "2026",
month = "Nov"
}
References
- Agache, A., et al. "Firecracker: Lightweight Virtualization for Serverless Applications." NSDI 2020 (summary by A. Colyer, The Morning Paper). blog.acolyer.org
- Angelopoulos, A. N., Bates, S., Fannjiang, C., Jordan, M. I., Zrnic, T. "Prediction-Powered Inference." Science 2023. arxiv.org/abs/2301.09633
- Anthropic. "Anthropic/hh-rlhf" (dataset card). Hugging Face 2022. huggingface.co
- Anthropic. "Pricing." Claude Platform documentation, accessed 2026-11-09. platform.claude.com/docs/en/about-claude/pricing
- Anthropic. "Rate limits." Claude API documentation, accessed 2026. platform.claude.com
- Apache Software Foundation. "Iceberg Table Spec." Apache Iceberg documentation. iceberg.apache.org/spec
- Appen Limited. "FY25 results and FY26 outlook." ASX announcement 2026 (25 Feb). asx.com.au
- Appen. "Deciphering AI from Human-Generated Text: The Behavioral Approach." Appen blog, Nov 2023. appen.com/blog
- Argilla. "Argilla is joining Hugging Face" (site banner). argilla.io 2024. argilla.io
- Argilla. "argilla-io/argilla" (README). GitHub 2026. github.com
- Argilla. "Suggestions (records reference)." Argilla documentation. docs.argilla.io
- Argilla. "Task distribution" (rg.TaskDistribution, min_submitted). Argilla documentation. docs.argilla.io/latest/reference/argilla/settings/task_distribution
- Arora, R. K., et al. "HealthBench: Evaluating Large Language Models Towards Improved Human Health." arXiv 2025. arxiv.org/html/2505.08775v1
- Arora, R. K., et al. "HealthBench: Evaluating Large Language Models Towards Improved Human Health." arXiv 2025. arxiv.org/pdf/2505.08775
- Arora, R. K., Wei, J., Soskin Hicks, R., Bowman, P., et al. "HealthBench: Evaluating Large Language Models Towards Improved Human Health." arXiv 2025. arxiv.org/abs/2505.08775
- Arora, R. K., Wei, J., Soskin Hicks, R., et al. "HealthBench: Evaluating Large Language Models Towards Improved Human Health." arXiv 2025. arxiv.org/abs/2505.08775
- Aroyo, L., Welty, C. "Truth Is a Lie: Crowd Truth and the Seven Myths of Human Annotation." AI Magazine 36(1):15–24, 2015. ojs.aaai.org/aimagazine/…/2564
- Axios. "Scale AI taps former Google Cloud executive as new CEO." Axios 2026 (30 Jul). axios.com
- Bai, Y., Jones, A., Ndousse, K., Askell, A., et al. "Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback." arXiv 2022. arxiv.org/abs/2204.05862
- Bai, Y., Kadavath, S., Kundu, S., Askell, A., et al. "Constitutional AI: Harmlessness from AI Feedback." arXiv 2022. arxiv.org/abs/2212.08073
- Bai, Y., Kadavath, S., Kundu, S., Askell, A., Kernion, J., et al. "Constitutional AI: Harmlessness from AI Feedback." arXiv 2022. arxiv.org/abs/2212.08073
- Beck, J., Eckman, S., Kern, C., Kreuter, F. "Bias in the Loop: How Humans Evaluate AI-Generated Suggestions." arXiv 2025. arxiv.org/abs/2509.08514
- Beck, J., Eckman, S., Ma, B., Chew, R., Kreuter, F. "Order Effects in Annotation Tasks: Further Evidence of Annotation Sensitivity." UncertaiNLP Workshop (ACL) 2024. aclanthology.org/2024.uncertainlp-1.8
- Beyer, B., Jones, C., Petoff, J., Murphy, N. R. (eds.). "Managing Incidents." Site Reliability Engineering (Google), O'Reilly 2016. sre.google/sre-book/incident-response
- Bitol (LF AI & Data Foundation). "Open Data Contract Standard (ODCS)." GitHub repository, v3.2.0. github.com/bitol-io/open-data-contract-standard
- Bradley, R. A., Terry, M. E. "Rank Analysis of Incomplete Block Designs: I. The Method of Paired Comparisons." Biometrika 1952 (with Zermelo 1929 and Hunter 2004, as summarised). en.wikipedia.org/wiki/Bradley–Terry_model
- Bradley, R. A., Terry, M. E. "Rank Analysis of Incomplete Block Designs: I. The Method of Paired Comparisons." Biometrika 1952. bibbase.org
- Broder, A. Z. "On the resemblance and containment of documents." Compression and Complexity of Sequences 1997. cs.princeton.edu/…/broder97resemblance.pdf
- Brooker, M. "Exponential Backoff And Jitter." AWS Architecture Blog 2015 (updated 2023). aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter
- Chen, G. H., Chen, S., Liu, Z., Jiang, F., Wang, B. "Humans or LLMs as the Judge? A Study on Judgement Bias." arXiv 2024. arxiv.org/abs/2402.10669
- Chen, H., et al. "From Holistic Evaluation to Structured Criteria: Rubrics Across the Evolving LLM Landscape." arXiv 2026. arxiv.org/abs/2606.08625
- Chiang, W.-L., Zheng, L., Sheng, Y., Angelopoulos, A. N., Li, T., et al. "Chatbot Arena: An Open Platform for Evaluating LLMs by Human Preference." arXiv 2024. arxiv.org/abs/2403.04132
- Choudhury, S. "Process Reward Models for LLM Agents: Practical Framework and Directions." arXiv 2025. arxiv.org/abs/2502.10325
- Chowdhury, S. R., Kini, A., Natarajan, N. "Provably Robust DPO: Aligning Language Models with Noisy Feedback." ICML 2024. arxiv.org/abs/2403.00409
- Christiano, P., Leike, J., Brown, T. B., Martic, M., Legg, S., Amodei, D. "Deep Reinforcement Learning from Human Preferences." arXiv 2017 (NeurIPS 2017). arxiv.org/abs/1706.03741
- Christiano, P., Leike, J., Brown, T. B., Martic, M., Legg, S., Amodei, D. "Deep Reinforcement Learning from Human Preferences." NeurIPS 2017. arxiv.org/abs/1706.03741
- CMS. "From gig to guarantee: how the EU is transforming platform work" (on Directive (EU) 2024/2831). CMS legal update. cms.law
- Cohen, J. "A Coefficient of Agreement for Nominal Scales." 1960 (with Landis and Koch 1977 bands, as summarised). en.wikipedia.org/wiki/Cohen's_kappa
- Computer Weekly. "Kenyan AI workers form Data Labelers Association." Computer Weekly 2025. computerweekly.com
- Confluent. "Schema Evolution and Compatibility for Schema Registry on Confluent Platform." Confluent documentation (Platform 7.7). docs.confluent.io/…/schema-evolution
- Confluent. "Schema Evolution and Compatibility for Schema Registry on Confluent Platform." Confluent Platform 8.0 documentation. docs.confluent.io/…/schema-evolution.html
- Coste, T., Anwar, U., Kirk, R., Krueger, D. "Reward Model Ensembles Help Mitigate Overoptimization." ICLR 2024 (arXiv 2023). arxiv.org/abs/2310.02743
- Cui, G., Yuan, L., Ding, N., Yao, G., He, B., et al. "UltraFeedback: Boosting Language Models with Scaled AI Feedback." arXiv 2023. arxiv.org/abs/2310.01377
- CVAT.ai. "cvat-ai/cvat" (README). GitHub 2026. github.com
- Das, A., Dang, B., Lease, M. "Fast, Accurate, and Healthier: Interactive Blurring Helps Moderators Reduce Exposure to Harmful Content." AAAI HCOMP 2020. ojs.aaai.org/index.php/HCOMP/article/view/7461
- Dawid, A. P., Skene, A. M. "Maximum Likelihood Estimation of Observer Error-Rates Using the EM Algorithm." Journal of the Royal Statistical Society Series C (Applied Statistics) 1979. econpapers.repec.org
- Dawid, A. P., Skene, A. M. "Maximum Likelihood Estimation of Observer Error-Rates Using the EM Algorithm." Journal of the Royal Statistical Society Series C (Applied Statistics) 28:20–28, 1979. doi.org/10.2307/2346806
- Dawid, A. P., Skene, A. M. "Maximum Likelihood Estimation of Observer Error-Rates Using the EM Algorithm." Journal of the Royal Statistical Society Series C 1979. ideas.repec.org
- Dealroom. "Handshake's ARR crosses $1B as AI training revenue surges." Dealroom News 2026. dealroom.co
- Dealroom. "Mercor doubles to $2B gross revenue run rate as AI labs buy expert data." Dealroom News 2026 (6 Jul). dealroom.co
- Dean, J., Barroso, L. A. "The Tail at Scale." Communications of the ACM 56 2013. research.google
- DeepSeek-AI. "DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning." arXiv 2025. arxiv.org/abs/2501.12948
- Deng, A., Xu, Y., Kohavi, R., Walker, T. "Improving the Sensitivity of Online Controlled Experiments by Utilizing Pre-Experiment Data (CUPED)." WSDM 2013. exp-platform.com/cuped
- Deshpande, D., et al. "TRAIL: Trace Reasoning and Agentic Issue Localization." arXiv 2025. arxiv.org/abs/2505.08638
- doccano. "doccano/doccano" (README). GitHub 2026. github.com
- Dwaracherla, V., Asghari, S. M., Hao, B., Van Roy, B. "Efficient Exploration for LLMs." arXiv 2024. arXiv:2402.00396
- Eby, P. J. "PEP 3333: Python Web Server Gateway Interface v1.0.1." Python Enhancement Proposals 2010. peps.python.org
- European Union. "General Data Protection Regulation, Article 33: Notification of a personal data breach to the supervisory authority." 2016. gdpr-text.com/en/read/article-33
- European Union. "Regulation (EU) 2016/679 (GDPR), Article 5: Principles relating to processing of personal data." 2016. gdpr.algolia.com/gdpr-article-5
- Explosion. [Prodigy product page]. prodi.gy 2026. prodi.gy
- Fan, S., et al. "AgentProcessBench: Diagnosing Step-Level Process Quality in Tool-Using Agents." arXiv 2026. arxiv.org/abs/2603.14465
- FastAPI. "Testing." FastAPI documentation 2026. fastapi.tiangolo.com
- Finlayson, M. A., Erjavec, T. "Overview of Annotation Creation: Processes & Tools." In Handbook of Linguistic Annotation, Springer 2016 (arXiv 1602.05753). arxiv.org/abs/1602.05753
- Fleisig, E., Orlikowski, M., Cimiano, P., Klein, D. "Balancing Quality and Variation: Spam Filtering Distorts Data Label Distributions." 2025. arxiv.org/abs/2509.08217
- Fleiss, J. L. "Measuring nominal scale agreement among many raters." Psychological Bulletin 1971. en.wikipedia.org/wiki/Fleiss'_kappa
- Fowler, M. "Event Sourcing." martinfowler.com 2005. martinfowler.com/eaaDev/EventSourcing.html
- Ganguli, D., Lovitt, L., Kernion, J., Askell, A., et al. "Red Teaming Language Models to Reduce Harms: Methods, Scaling Behaviors, and Lessons Learned." arXiv 2022. arxiv.org/abs/2209.07858
- Ganguli, D., Lovitt, L., Kernion, J., Askell, A., et al. "Red Teaming Language Models to Reduce Harms: Methods, Scaling Behaviors, and Lessons Learned." arXiv 2022. arxiv.org/abs/2209.07858
- Gao, L., Schulman, J., Hilton, J. "Scaling Laws for Reward Model Overoptimization." arXiv 2022. arxiv.org/abs/2210.10760
- Gebru, T., et al. "Datasheets for Datasets." Communications of the ACM 2021 (arXiv 1803.09010). arxiv.org/abs/1803.09010
- Gebru, T., Morgenstern, J., Vecchione, B., Wortman Vaughan, J., Wallach, H., Daumé III, H., Crawford, K. "Datasheets for Datasets." Communications of the ACM 2021 (arXiv 1803.09010). arxiv.org/abs/1803.09010
- Gheshlaghi Azar, M., Rowland, M., Piot, B., Guo, D., Calandriello, D., Valko, M., Munos, R. "A General Theoretical Paradigm to Understand Learning from Human Preferences." AISTATS 2024. arxiv.org/abs/2310.12036
- Ghorbani, A., Zou, J. "Data Shapley: Equitable Valuation of Data for Machine Learning." arXiv 2019. arxiv.org/abs/1904.02868
- Gilardi, F., Alizadeh, M., Kubli, M. "ChatGPT Outperforms Crowd-Workers for Text-Annotation Tasks." PNAS 2023. arxiv.org/abs/2303.15056
- Glaese, A., et al. "Improving alignment of dialogue agents via targeted human judgements." arXiv 2022. arxiv.org
- Google DeepMind (Paterson, A., Hawkins, W.). "Best practices for data enrichment." Google DeepMind blog 2022. deepmind.google/blog/best-practices-for-data-enrichment
- Google SRE. "Alerting on SLOs." In The Site Reliability Workbook, O'Reilly 2018. sre.google/workbook/alerting-on-slos
- Google SRE. "Handling Overload." In Beyer, B., Jones, C., Petoff, J., Murphy, N. R. (eds.), Site Reliability Engineering, O'Reilly 2016. sre.google/sre-book/handling-overload
- Google SRE. "Implementing SLOs." In The Site Reliability Workbook, O'Reilly 2018. sre.google/workbook/implementing-slos
- Google. "Canarying Releases." The Site Reliability Workbook, Chapter 16, 2018. sre.google
- Gordon, M. L., Lam, M. S., Park, J. S., Patel, K., Hancock, J. T., Hashimoto, T., Bernstein, M. S. "Jury Learning: Integrating Dissenting Voices into Machine Learning Models." CHI 2022. arxiv.org/abs/2202.02950
- Grafana Labs. "How to implement multi-window, multi-burn-rate alerts with Grafana Cloud." Grafana blog 2025. grafana.com/blog/2025/02/28/…multi-burn-rate-alerts…
- Gunjal, A., Wang, A., Lau, E., Nath, V., He, Y., Liu, B., Hendryx, S. "Rubrics as Rewards: Reinforcement Learning Beyond Verifiable Domains." arXiv 2025. arxiv.org/abs/2507.17746
- Gunjal, A., Wang, A., Lau, E., Nath, V., He, Y., Liu, B., Hendryx, S. "Rubrics as Rewards: Reinforcement Learning Beyond Verifiable Domains." arXiv 2025; ICLR 2026. arxiv.org/abs/2507.17746
- Gutiérrez, J., Gutiérrez-García, V., Blanco-Murillo, J. L. "Does AI Assistance Preserve or Collapse Disagreement? A Study of Pre-Annotations in Ambiguous Video Labeling." ICML 2026. icml.cc/virtual/2026/75673
- Hanley, J. A., Lippman-Hand, A. "If nothing goes wrong, is everything all right? Interpreting zero numerators." JAMA 249(13):1743–1745, 1983. doi.org/10.1001/jama.1983.03330370053031
- Hara, K., Adams, A., Milland, K., Savage, S., Callison-Burch, C., Bigham, J. "A Data-Driven Analysis of Workers' Earnings on Amazon Mechanical Turk." CHI 2018. arxiv.org/abs/1712.05796
- HashiCorp. "terraform plan command." Terraform CLI documentation. developer.hashicorp.com/terraform/cli/commands/plan
- Hata, K., Krishna, R., Fei-Fei, L., Bernstein, M. S. "A Glimpse Far into the Future: Understanding Long-term Crowd Worker Quality." CSCW 2017. arxiv.org/abs/1609.04855
- Hong, H., et al. "Can LLMs Write Reliable Rubrics? A Meta-Evaluation for Experiment Reproduction." arXiv 2026. arxiv.org/abs/2607.12835
- Hosking, T., Blunsom, P., Bartolo, M. "Human Feedback is not Gold Standard." ICLR 2024. arxiv.org/abs/2309.16349
- Hovy, D., Berg-Kirkpatrick, T., Vaswani, A., Hovy, E. "Learning Whom to Trust with MACE." NAACL 2013. aclanthology.org/N13-1132
- Hu, V. C., Ferraiolo, D., Kuhn, R., Schnitzer, A., Sandlin, K., Miller, R., Scarfone, K. "Guide to Attribute Based Access Control (ABAC) Definition and Considerations." NIST SP 800-162, 2014 (updated 2019). csrc.nist.gov/pubs/sp/800/162/upd2/final
- Huang, Z., et al. "Reinforcement Learning with Rubric Anchors." arXiv 2025. arxiv.org/abs/2508.12790
- Hugging Face. "Reward Modeling (RewardTrainer)." TRL documentation 2026. huggingface.co/docs/trl
- Hugging Face. "TRL documentation: Dataset formats and types." huggingface.co/docs/trl/dataset_formats
- Hugging Face. "TRL documentation: PRM Trainer (experimental)." huggingface.co/docs/trl/main/en/prm_trainer
- HumanSignal. "Building Integrations for Label Studio." Label Studio blog 2023. labelstud.io/blog/label-studio-integrations-guide
- HumanSignal. "Configure labeling interface." Label Studio documentation. labelstud.io/guide/setup
- HumanSignal. "How to Configure Task Assignment Settings for Optimal Workflow." Label Studio support article, accessed 2026. support.humansignal.com
- HumanSignal. "HumanSignal/label-studio" (README). GitHub 2026. github.com
- HumanSignal. "Pairwise Comparison template." Label Studio documentation 2026. labelstud.io
- iMerit. "iMerit Unveils Scholars - A Handpicked Global Network of Cognitive Experts for Advanced GenAI Training." PR Newswire 2025 (9 Jul). prnewswire.com
- Ivison, H., et al. "Unpacking DPO and PPO: Disentangling Best Practices for Learning from Preference Feedback." arXiv 2024. arxiv.org/abs/2406.09279
- Johari, R., Pekelis, L., Walsh, D. J. "Always Valid Inference: Bringing Sequential Analysis to A/B Testing." arXiv 2015 (v3 2019). arxiv.org/abs/1512.04922
- JSON Schema. "Specification" (draft 2020-12). json-schema.org. json-schema.org/specification
- Jung, J., Brahman, F., Choi, Y. "Trust or Escalate: LLM Judges with Provable Guarantees for Human Agreement." ICLR 2025. arxiv.org/abs/2407.18370
- Jurgens, D., et al. "davidjurgens/potato" (README; Potato 2.0, ACL 2026 System Demonstrations). GitHub 2026. github.com
- KhudaBukhsh, A. R., Carbonell, J. G., Jansen, P. J. "Detecting Non-Adversarial Collusion in Crowdsourcing." HCOMP 2014. ojs.aaai.org/index.php/HCOMP/article/view/13157
- King & Siegel LLP. "Scale AI Pays $12.5 Million Over Claims It Built Its AI Pipeline on Misclassified Workers." Firm blog 2026 (4 Aug). kingsiegel.com
- Kingman, J. F. C. "The single server queue in heavy traffic." Mathematical Proceedings of the Cambridge Philosophical Society 57(4), 1961 (formula summarised on Wikipedia). wikipedia
- Kish, L. "Survey Sampling" (design effect; summary page). Wiley 1965. en.wikipedia.org/wiki/Design_effect
- Koh, P. W., Liang, P. "Understanding Black-box Predictions via Influence Functions." ICML 2017. arxiv.org/abs/1703.04730
- Krippendorff, K. "Computing Krippendorff's Alpha-Reliability." Annenberg School for Communication, University of Pennsylvania, 2011. asc.upenn.edu (PDF)
- Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C. H., Gonzalez, J. E., Zhang, H., Stoica, I. "Efficient Memory Management for Large Language Model Serving with PagedAttention." SOSP 2023. arXiv:2309.06180
- Köpf, A., Kilcher, Y., von Rütte, D., et al. "OpenAssistant Conversations: Democratizing Large Language Model Alignment." arXiv 2023. arxiv.org
- Label Studio. "Import pre-annotated data (predictions)." Label Studio documentation. labelstud.io/guide/predictions
- Labelbox. [Homepage: Horizon, Alignerr]. labelbox.com 2026. labelbox.com
- Lambert, N. "Reward Modeling." In Reinforcement Learning from Human Feedback (online book), 2025–2026. rlhfbook.com
- Lambert, N., Morrison, J., Pyatkin, V., et al. "Tülu 3: Pushing Frontiers in Open Language Model Post-Training." arXiv 2024. arxiv.org/abs/2411.15124
- Lean Enterprise Institute. "Value-Stream Mapping." Lean Lexicon (online). lean.org
- Lee, H., Phatale, S., Mansoor, H., et al. "RLAIF vs. RLHF: Scaling Reinforcement Learning from Human Feedback with AI Feedback." arXiv 2023. arxiv.org/abs/2309.00267
- Lee, K., Ippolito, D., Nystrom, A., Zhang, C., Eck, D., Callison-Burch, C., Carlini, N. "Deduplicating Training Data Makes Language Models Better." arXiv 2021 (rev. 2022). arXiv:2107.06499
- Li, R., et al. "StarCoder: may the source be with you!" arXiv 2023. arxiv.org/pdf/2305.06161
- Lightman, H., Kosaraju, V., Burda, Y., Edwards, H., Baker, B., Lee, T., Leike, J., Schulman, J., Sutskever, I., Cobbe, K. "Let's Verify Step by Step." ICLR 2024. arxiv.org/abs/2305.20050
- Lightman, H., Kosaraju, V., Burda, Y., Edwards, H., et al. "Let's Verify Step by Step." arXiv 2023. arxiv.org/abs/2305.20050
- Little, J. D. C. "A Proof for the Queuing Formula: L = λW." Operations Research 9(3) 1961; and "Little's Law as Viewed on Its 50th Anniversary." Operations Research 59(3) 2011. reprint
- Little, J. D. C. "A Proof for the Queuing Formula: L = λW." Operations Research 9(3):383–387, 1961. econpapers
- Llama Team, AI @ Meta (Dubey, A., et al.). "The Llama 3 Herd of Models." arXiv 2024. arXiv:2407.21783
- Llama Team, AI @ Meta. "The Llama 3 Herd of Models." arXiv 2024. arxiv.org
- LMArena. "lmarena-ai/arena-human-preference-140k" (dataset card). Hugging Face 2025. huggingface.co
- LMSYS. "Catch me if you can! How to beat GPT-4 with a 13B model." LMSYS blog 2023. lmsys.org/blog/2023-11-14-llm-decontaminator
- LMSYS. "Chatbot Arena: New models & Elo system update." 2023. lmsys.org/blog/2023-12-07-leaderboard
- LMSYS. "lmsys/chatbot_arena_conversations" (dataset card). Hugging Face 2023. huggingface.co
- Longpre, S., Mahari, R., et al. "The Data Provenance Initiative: A Large Scale Audit of Dataset Licensing & Attribution in AI." arXiv 2023. arxiv.org/abs/2310.16787
- Lù, X. H., Kazemnejad, A., Meade, N., Patel, A., Shin, D., Zambrano, A., Stańczak, K., Shaw, P., Pal, C. J., Reddy, S. "AgentRewardBench: Evaluating Automatic Evaluations of Web Agent Trajectories." arXiv 2025. arxiv.org/abs/2504.08942
- McAleese, N., et al. "LLM Critics Help Catch LLM Bugs." arXiv 2024. arxiv.org/abs/2407.00215
- McKinney, et al. v. Scale AI, Inc., et al., Case No. CGC-24-620481, Superior Court of California, County of San Francisco. Court-approved settlement administrator website (notice and FAQ: $12.5 million gross settlement, preliminary approval, final approval hearing set for 30 October 2026). mckinneyscaleaisettlement.com
- MDN Web Docs. "Document: visibilitychange event." Mozilla 2026. developer.mozilla.org
- Mehta, S., Panavas, L., Garre, S., Chen, E. "ComplexConstraints and Beyond: Expert Rubrics for RLVR." arXiv 2026. arxiv.org/abs/2606.09118
- METR. "Recent Frontier Models Are Reward Hacking." June 2025. metr.org/blog/2025-06-05-recent-reward-hacking
- Microsoft and contributors. "Presidio: Data Protection and De-identification SDK." Documentation. presidio.dataprivacystack.org
- Microsoft. "Presidio: Data Protection and De-identification SDK — Concepts." microsoft.github.io/presidio/learn_presidio/concepts
- Min, T., Lee, H., Kwon, Y., Lee, K. "Understanding Impact of Human Feedback via Influence Functions." ACL 2025. arxiv.org/abs/2501.05790
- Miranda, L. J. V., Wang, Y., Elazar, Y., Kumar, S., Pyatkin, V., Brahman, F., Smith, N. A., Hajishirzi, H., Dasigi, P. "Hybrid Preferences: Learning to Route Instances for Human vs. AI Feedback." arXiv 2024. arxiv.org/abs/2410.19133
- MLCommons. "Croissant Format Specification 1.1." docs.mlcommons.org/croissant/docs/croissant-spec-1.1.html
- Mu, T., Helyar, A., Heidecke, J., et al. "Rule Based Rewards for Language Model Safety." arXiv 2024. arxiv.org
- Muldrew, W., Hayes, P., Zhang, M., Barber, D. "Active Preference Learning for Large Language Models." ICML 2024. arXiv:2402.08114
- Nakano, R., Hilton, J., et al. "WebGPT: Browser-assisted question-answering with human feedback." arXiv 2021; comparisons released as "openai/webgpt_comparisons." huggingface.co
- Nebius. "Nebius welcomes Bezos Expeditions as lead investor in AI data business Toloka." Nebius newsroom 2025 (7 May). nebius.com
- Nieva, R. "Inside Scale AI's Business After Meta's Bombshell $14 Billion Deal." Forbes 2026 (14 May). forbes.com
- NVIDIA. "HelpSteer2" (dataset card). Hugging Face 2024. huggingface.co/datasets/nvidia/HelpSteer2
- NVIDIA. "nvidia/HelpSteer3" (dataset card). Hugging Face 2025. huggingface.co
- OpenAI. "Batch API." API documentation, accessed 2026. developers.openai.com
- OpenAI. "Introducing HealthBench." OpenAI, 2025. openai.com/index/healthbench
- OpenAI. "openai/prm800k" (repository README). GitHub 2023. github.com
- OpenAssistant. "OpenAssistant/oasst1" (dataset card). Hugging Face 2023. huggingface.co
- OpenBMB. "openbmb/UltraFeedback" (dataset card). Hugging Face 2023. huggingface.co
- Ouyang, L., Wu, J., Jiang, X., Almeida, D., et al. "Training Language Models to Follow Instructions with Human Feedback." arXiv 2022 (NeurIPS 2022). arxiv.org/abs/2203.02155
- Ouyang, L., Wu, J., Jiang, X., et al. "Training Language Models to Follow Instructions with Human Feedback." NeurIPS 2022. arxiv.org/abs/2203.02155
- PagerDuty. "Severity Levels." PagerDuty Incident Response Documentation. response.pagerduty.com/before/severity_levels
- Paquier, M. "Postgres 9.5 feature highlight - SKIP LOCKED for row-level locking." 2014. paquier.xyz/…skip-locked-row-level
- Park, S. M., Georgiev, K., Ilyas, A., Leclerc, G., Madry, A. "TRAK: Attributing Model Behavior at Scale." arXiv 2023. arxiv.org/abs/2303.14186
- Partnership on AI. "Data Enrichment Sourcing Guidelines." Partnership on AI 2022. partnershiponai.org (PDF)
- Partnership on AI. "Protecting AI's essential workers: introducing our vendor engagement guidance and transparency template." Partnership on AI. partnershiponai.org
- Patwardhan, T., Dias, R., Proehl, E., Kim, G., et al. "GDPval: Evaluating AI Model Performance on Real-World Economically Valuable Tasks." arXiv 2025. arxiv.org/abs/2510.04374
- Peng, Y., Qi, Y., Xia, H., He, G., et al. "Can LLM-as-a-Judge Reliably Verify Rubrics in Agentic Scenarios?" (RuVerBench). EMNLP 2026. arxiv.org/abs/2606.29920
- Perrigo, B. "OpenAI Used Kenyan Workers on Less Than $2 Per Hour to Make ChatGPT Less Toxic." TIME 2023. time.com/6247678
- Phan, L., Gatti, A., Han, Z., Li, N., Hu, J., et al. "Humanity's Last Exam." arXiv 2025. arxiv.org/abs/2501.14249
- PKU-Alignment. "PKU-Alignment/PKU-SafeRLHF" (dataset card). Hugging Face 2024. huggingface.co
- Plank, B. "The 'Problem' of Human Label Variation: On Ground Truth in Data, Modeling and Evaluation." arXiv 2022 (EMNLP 2022). arxiv.org/abs/2211.02570
- Plank, B. "The 'Problem' of Human Label Variation: On Ground Truth in Data, Modeling and Evaluation." EMNLP 2022. aclanthology.org/2022.emnlp-main.731
- Prolific. "Authenticity checks: how we tested the most accurate method for identifying agentic AI." Prolific, Feb 2026. prolific.com/resources
- Prolific. "How much should you pay research participants?" Prolific resources. prolific.com
- Prolific. "How Prolific detects bots and AI in online research." 2025. prolific.com
- Prolific. "Pricing." prolific.com 2026. prolific.com
- Prolific. "Webhooks: verifying requests" and "Receiving events." Prolific API documentation. docs.prolific.com/api-reference/webhooks/verifying · receiving
- Prolific. "What are authenticity checks?" Researcher help centre, accessed 2026-11-09. researcher-help.prolific.com
- Prolific. "What is your pricing?" Prolific Researcher Help Centre, accessed 2026-11-09. researcher-help.prolific.com/en/articles/445239
- Prolific. [Prolific in 2025: product and safeguards update]. prolific.com 2025 (16 Dec). prolific.com
- Pulse 2.0. "Encord: $60 Million Series C Raised To Scale AI-Native Data Infrastructure." Pulse 2.0 2026 (27 Feb). pulse2.com
- Pulse 2.0. "Turing: $111 Million (Series E) Raised At $2.2 Billion Valuation For AGI Infrastructure." Pulse 2.0 2025 (11 Mar). pulse2.com
- Pustejovsky, J., Stubbs, A. "Natural Language Annotation for Machine Learning." O'Reilly 2012. oreilly.com/library/view/natural-language-annotation/9781449332693
- Pydantic. "Functional validators" (model_validator). Pydantic documentation. docs.pydantic.dev/dev/api/functional_validators
- Radiology Business. "'Hungry judge effect': How time of day can impact radiologists' MRI reads" (on a European Journal of Radiology study of prostate MRI reporting). Radiology Business, n.d. radiologybusiness.com
- Rafailov, R., Sharma, A., Mitchell, E., et al. "Direct Preference Optimization: Your Language Model is Secretly a Reward Model." arXiv 2023. arxiv.org/abs/2305.18290
- Reuters (via Yahoo Finance). "Surge AI plans to raise $1bn in first-ever funding round at $15bn valuation." Yahoo Finance 2025 (2 Jul). finance.yahoo.com
- Rogero, J. "The State of Reward Hacking in AI, September 2026." MIRI 2026. intelligence.org (PDF)
- Sacra. "micro1 revenue, valuation & funding." Sacra 2026. sacra.com
- Sacra. "Surge AI revenue, funding & news." Sacra 2025. sacra.com
- Sadasivan, V. S., Kumar, A., Balasubramanian, S., Wang, W., Feizi, S. "Can AI-Generated Text be Reliably Detected?" arXiv 2023. arXiv:2303.11156
- Saunders, W., Yeh, C., Wu, J., Bills, S., Ouyang, L., Ward, J., Leike, J. "Self-critiquing models for assisting human evaluators." arXiv 2022. arxiv.org/abs/2206.05802 · openai.com/index/critiques
- Scale AI. "Calibration Workflow" (Scale Rapid). Scale documentation. scale.com/docs/rapid-or-calibration
- Scale AI. "Callbacks." Scale API reference. api-reference.scale.com/docs/api-reference/callbacks
- Scholer, F., Kelly, D., Wu, W.-C., Lee, H. S., Webber, W. "The Effect of Threshold Priming and Need for Cognition on Relevance Calibration and Assessment." SIGIR 2013. ir.webis.de (anthology entry)
- Schroeder, H., Roy, D., Kabbara, J. "Just Put a Human in the Loop? Investigating LLM-Assisted Annotation for Subjective Tasks." arXiv 2025. arxiv.org/abs/2507.15821
- Settles, B. "Active Learning Literature Survey." Computer Sciences Technical Report 1648, University of Wisconsin–Madison 2009. TR1648
- Shmueli, B., Fell, J., Ray, S., Ku, L.-W. "Beyond Fair Pay: Ethical Implications of NLP Crowdsourcing." NAACL 2021. aclanthology.org/2021.naacl-main.295
- Shumailov, I., Shumaylov, Z., Zhao, Y., Gal, Y., Papernot, N., Anderson, R. "The Curse of Recursion: Training on Generated Data Makes Models Forget." arXiv 2023. arxiv.org/abs/2305.17493
- SiliconANGLE. [Invisible raises $100M at a $2B+ valuation]. SiliconANGLE 2025 (16 Sep). siliconangle.com
- SiliconANGLE. [Toloka raises $72M led by Bezos Expeditions]. SiliconANGLE 2025 (7 May). siliconangle.com
- Singh, S., Nan, Y., Wang, A., D'Souza, D., Kapoor, S., et al. "The Leaderboard Illusion." arXiv 2025. arxiv.org/abs/2504.20879
- Singhal, P., Goyal, T., Xu, J., Durrett, G. "A Long Way to Go: Investigating Length Correlations in RLHF." arXiv 2023. arxiv.org/abs/2310.03716
- Snorkel AI. "Snorkel AI Raises $350M to Scale the Data Factory for Frontier AI." Press release 2026 (22 Sep). snorkel.ai
- Snow, R., O'Connor, B., Jurafsky, D., Ng, A. "Cheap and Fast — But is it Good? Evaluating Non-Expert Annotations for Natural Language Tasks." EMNLP 2008, pp. 254–263. aclanthology.org/D08-1027
- Sodt, R., Maravić, I., et al. "Data Processing Pipelines." The Site Reliability Workbook, Google 2018. sre.google/workbook/data-processing
- SQLite. "Write-Ahead Logging." SQLite documentation, accessed 2026-11-09. sqlite.org/wal.html
- Stanford NLP. "stanfordnlp/SHP" (dataset card). Hugging Face 2022. huggingface.co
- Starace, G., et al. "PaperBench: Evaluating AI's Ability to Replicate AI Research." arXiv 2025. arxiv.org/abs/2504.01848
- Steiger, M., Bharucha, T. J., Venkatagiri, S., Riedl, M. J., Lease, M. "The Psychological Well-Being of Content Moderators: The Emotional Labor of Commercial Moderation and Avenues for Improving Support." CHI 2021. mattlease.com/papers/steiger-chi21.pdf
- Steinhardt, J. (Transluce). "Analyzing Long Agent Transcripts (Docent)." LessWrong / Bounded Regret 2025. lesswrong.com
- Stiennon, N., Ouyang, L., Wu, J., Ziegler, D. M., Lowe, R., et al. "Learning to Summarize from Human Feedback." NeurIPS 2020. arxiv.org/abs/2009.01325
- Stockwell, B. "Facebook inflicted 'lifelong trauma' on Kenyan content moderators, campaigners say, as more than 140 are diagnosed with PTSD." CNN, 22 Dec 2024 (CNN Newsource syndication). kvia.com (CNN Newsource)
- Stripe. "Idempotent requests." Stripe API reference 2026. docs.stripe.com
- SWE-bench. "Harness reference: Docker image layers and cache levels." Documentation, accessed 2026. swebench.com
- Szymanski, A., Ziems, N., Eicher-Miller, H. A., Li, T. J.-J., Jiang, M., Metoyer, R. A. "Limitations of the LLM-as-a-Judge Approach for Evaluating LLM Outputs in Expert Knowledge Tasks." arXiv 2024. arxiv.org/abs/2410.20266
- Tajwar, F., Singh, A., Sharma, A., Rafailov, R., Schneider, J., Xie, T., Ermon, S., Finn, C., Kumar, A. "Preference Fine-Tuning of LLMs Should Leverage Suboptimal, On-Policy Data." ICML 2024. arXiv:2404.14367
- Tan, R., Cabato, R. "Behind the AI boom, an army of overseas workers in 'digital sweatshops'." The Washington Post, 28 Aug 2023. washingtonpost.com
- TanStack. "Virtualizer API" (TanStack Virtual v3). TanStack 2026. tanstack.com/virtual
- TechCrunch. "After data breach, $10B-valued startup Mercor is having a month." TechCrunch 2026 (9 Apr). techcrunch.com
- TechCrunch. "Facebook will pay $52 million in settlement with moderators who developed PTSD on the job." TechCrunch 2020. techcrunch.com
- TechCrunch. "Snorkel AI triples valuation to $3.5B as demand for AI training data booms." TechCrunch 2026 (22 Sep). techcrunch.com
- TechCrunch. "SuperAnnotate helps companies manage their AI datasets." TechCrunch 2024 (18 Nov). techcrunch.com
- TechCrunch. "The Department of Labor just dropped its investigation into Scale AI." TechCrunch 2025 (9 May). techcrunch.com
- TechRadar. "Telus Digital confirms breach - hackers allegedly stole 'almost 1 petabyte of data'." TechRadar Pro 2026 (13 Mar). techradar.com
- TELUS Digital. "AI data solutions." telusdigital.com 2026. telusdigital.com
- TELUS. "TELUS Completes Privatization of TELUS Digital." Media release 2025 (31 Oct). telus.com
- Temporal Technologies. "What is a Temporal Retry Policy?" Temporal documentation. docs.temporal.io/encyclopedia/retry-policies
- The Register. "Mental toll: Scale AI, Outlier sued by humans paid to steer AI away from our darkest depths." The Register 2025. theregister.com
- Tijdens, K. G., Bhattacharya, L. "Work and Wages of Data Labelers in Kenya." WageIndicator Foundation 2026. wageindicator.org
- Tong, A. "This 25-Year-Old Raised Over $100 Million For His AI Data Startup At A $4 Billion Valuation." Forbes 2026 (22 Sep). forbes.com
- Touvron, H., Martin, L., Stone, K., et al. "Llama 2: Open Foundation and Fine-Tuned Chat Models." arXiv 2023. arxiv.org/abs/2307.09288
- Touvron, H., Martin, L., Stone, K., et al. "Llama 2: Open Foundation and Fine-Tuned Chat Models." arXiv 2023. arxiv.org/abs/2307.09288
- Uesato, J., Kushman, N., Kumar, R., Song, F., et al. "Solving Math Word Problems with Process- and Outcome-Based Feedback." arXiv 2022. arxiv.org/abs/2211.14275
- UK AI Security Institute and Meridian Labs. "Inspect." inspect.aisi.org.uk
- UK AI Security Institute. "Inspect: Log Viewer." Inspect documentation 2026. inspect.aisi.org.uk/log-viewer.html
- Uma, A. N., Fornaciari, T., Hovy, D., Paun, S., Plank, B., Poesio, M. "Learning from Disagreement: A Survey." Journal of Artificial Intelligence Research 72:1385–1470, 2021. jair.org/…/12752
- Ustalov, D., Pavlichenko, N., Tseitlin, B. "Learning from Crowds with Crowd-Kit." 2021. arxiv.org/abs/2109.08584
- Verdict. [Scale AI cuts 14% of staff after Meta investment]. Verdict 2025 (17 Jul). verdict.co.uk
- Veselovsky, V., Horta Ribeiro, M., Cozzolino, P., Gordon, A., Rothschild, D., West, R. "Prevalence and Prevention of Large Language Model Use in Crowd Work." arXiv 2023. arxiv.org/abs/2310.15683
- Veselovsky, V., Horta Ribeiro, M., West, R. "Artificial Artificial Artificial Intelligence: Crowd Workers Widely Use Large Language Models for Text Production Tasks." arXiv 2023. arxiv.org/abs/2306.07899
- Veselovsky, V., Horta Ribeiro, M., West, R. "Artificial Artificial Artificial Intelligence: Crowd Workers Widely Use Large Language Models for Text Production Tasks." arXiv 2023. arxiv.org/abs/2306.07899
- Viswanathan, V., Sun, Y., Ma, S., Kong, X., Cao, M., Neubig, G., Wu, T. "Checklists Are Better Than Reward Models For Aligning Language Models." arXiv 2025. arxiv.org/abs/2507.18624
- vLLM Project. "Automatic Prefix Caching (design)." vLLM documentation. docs.vllm.ai
- vLLM Project. "Production Metrics." vLLM documentation (v0.7.3). docs.vllm.ai/en/v0.7.3/serving/metrics.html
- W3C. "PROV-DM: The PROV Data Model." W3C Recommendation 2013. w3.org/TR/2013/REC-prov-dm-20130430
- Wald, A. "Sequential Tests of Statistical Hypotheses." Annals of Mathematical Statistics 16(2):117–186, 1945. projecteuclid.org/euclid.aoms/1177731118
- Wang, B., et al. "Secrets of RLHF in Large Language Models Part II: Reward Modeling." arXiv 2024. arxiv.org/abs/2401.06080
- Wang, J., et al. "Aligning Agents via Planning: A Benchmark for Trajectory-Level Reward Modeling" (Plan-RewardBench). arXiv 2026. arxiv.org/abs/2604.08178
- Wang, P., Li, L., Shao, Z., Xu, R. X., Dai, D., et al. "Math-Shepherd: Verify and Reinforce LLMs Step-by-step without Human Annotations." arXiv 2023. arxiv.org/abs/2312.08935
- Wang, X., Kim, H., Miao, Z., Mitra, K., Rahman, S. "Human-LLM Collaborative Annotation Through Effective Verification of LLM Labels." CHI 2024. megagon.ai
- Wang, Z., Dong, Y., Delalleau, O., et al. "HelpSteer2: Open-source Dataset for Training Top-Performing Reward Models." arXiv 2024. arxiv.org/abs/2406.08673
- Wang, Z., Dong, Y., Zeng, J., et al. "HelpSteer: Multi-attribute Helpfulness Dataset for SteerLM." arXiv 2023. arxiv.org/abs/2311.09528
- Wang, Z., et al. "ProfBench: Multi-Domain Rubrics requiring Professional Knowledge to Answer and Judge." arXiv 2025. arxiv.org/abs/2510.18941
- web.dev (Google). "Interaction to Next Paint (INP)." web.dev 2026. web.dev/articles/inp
- Wikipedia. "Krippendorff's alpha" (thresholds attributed to Krippendorff 2004, pp. 241–243). Accessed 2026-11-09. en.wikipedia.org/wiki/Krippendorff's_alpha
- Wikipedia. "Surge AI." Wikipedia, accessed 2026 (Nov). wikipedia.org
- Wikipedia. "Telus Digital." Wikipedia, accessed 2026 (Nov). wikipedia.org
- Wilson, E. B. "Probable inference, the law of succession, and statistical inference." Journal of the American Statistical Association 1927. scilit.com/publications/51ab62bc5a19b66438acfe9c66479b31
- Xia, M., Malladi, S., Gururangan, S., Arora, S., Chen, D. "LESS: Selecting Influential Data for Targeted Instruction Tuning." arXiv 2024. arxiv.org/abs/2402.04333
- Xie, S. M., et al. "DoReMi: Optimizing Data Mixtures Speeds Up Language Model Pretraining." NeurIPS 2023. arxiv.org/abs/2305.10429
- Xu, R., et al. "Alternating Reinforcement Learning for Rubric-Based Reward Modeling in Non-Verifiable LLM Post-Training" (Rubric-ARM). arXiv 2026. arxiv.org/abs/2602.01511
- Xu, Z., Malkin, N. "A Penny for Your Prompts: Experiments Detecting and Mitigating LLM Usage by Survey Respondents." arXiv 2026. arxiv.org/abs/2607.00403
- Yanacek, D. "Avoiding insurmountable queue backlogs." Amazon Builders' Library. builder.aws.com/…avoiding-insurmountable-queue-backlogs
- Yanacek, D. "Using load shedding to avoid overload." Amazon Builders' Library. builder.aws.com/…using-load-shedding-to-avoid-overload
- Yang, S., Chiang, W.-L., Zheng, L., Gonzalez, J. E., Stoica, I. "Rethinking Benchmark and Contamination for Language Models with Rephrased Samples." arXiv 2023. arxiv.org/pdf/2311.04850
- Ye, J., Liu, P., Sun, T., Zhan, J., Zhou, Y., Qiu, X. "Data Mixing Laws: Optimizing Data Mixtures by Predicting Language Modeling Performance." ICLR 2025. arxiv.org/abs/2403.16952
- Yu, Q., Zhang, Z., Zhu, R., Yuan, Y., Zuo, X., et al. "DAPO: An Open-Source LLM Reinforcement Learning System at Scale." arXiv 2025. arXiv:2503.14476
- Zhang, S., Yin, M., Zhang, J., Liu, J., et al. "Which Agent Causes Task Failures and When? On Automated Failure Attribution of LLM Multi-Agent Systems." arXiv 2025. arxiv.org/abs/2505.00212
- Zhang, Y., Pang, J., Zhu, Z., Liu, Y. "Evaluating LLM-Contaminated Crowdsourcing Data Without Ground Truth." 2025. arxiv.org/abs/2506.06991
- Zheng, C., Zhang, Z., Zhang, B., Lin, R., Lu, K., Yu, B., Liu, D., Zhou, J., Lin, J. "ProcessBench: Identifying Process Errors in Mathematical Reasoning." arXiv 2024. arxiv.org/abs/2412.06559
- Zheng, L., Chiang, W.-L., Sheng, Y., Zhuang, S., et al. "Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena." NeurIPS 2023 Datasets and Benchmarks. arxiv.org/abs/2306.05685
- Zheng, L., Yin, L., Xie, Z., Sun, C., et al. "SGLang: Efficient Execution of Structured Language Model Programs." arXiv 2023. arXiv:2312.07104
- Ziegler, D. M., et al. "Fine-Tuning Language Models from Human Preferences." arXiv 2019. arxiv.org/abs/1909.08593