"""Seeded relational investigations with answers computed independently in Python. Only the task's public tables are stored in SQLite. Reference SQL and expected answers remain in this module's Python objects, never in the queryable database. """ from __future__ import annotations import random import sqlite3 from collections import defaultdict from dataclasses import dataclass from datetime import date, datetime, timedelta from decimal import ROUND_HALF_UP, Decimal from fractions import Fraction JSONScalar = str | int | float | None @dataclass class Task: instruction: str schema: str connection: sqlite3.Connection expected_rows: list[list[JSONScalar]] oracle_sql: str def _rounded(value: Fraction | int, places: int) -> float: value = Fraction(value) decimal = Decimal(value.numerator) / Decimal(value.denominator) return float(decimal.quantize(Decimal(10) ** -places, rounding=ROUND_HALF_UP)) def _task(instruction, schema, tables, expected, oracle): connection = sqlite3.connect(":memory:", check_same_thread=False) connection.executescript(schema) for name, rows in tables.items(): if rows: placeholders = ",".join("?" for _ in rows[0]) connection.executemany(f"INSERT INTO {name} VALUES ({placeholders})", rows) connection.commit() counts = "\n".join(f"-- {name}: {len(rows)} rows" for name, rows in tables.items()) return Task( instruction=instruction + " Return exactly the requested columns, in that order. Row order does not matter.", schema=schema.strip() + "\n" + counts, connection=connection, expected_rows=expected, oracle_sql=oracle.strip(), ) def _sales_net_revenue(rng): customers = [(i, ("consumer", "business", "education")[(i - 1) % 3]) for i in range(1, 13)] orders, items, refunds = [], [], [] totals = defaultdict(int) for order_id in range(1, 25): customer_id = (order_id - 1) % 12 + 1 status = "completed" if order_id == 1 or rng.random() < 0.8 else "cancelled" orders.append((order_id, customer_id, status)) amount = 0 for _ in range(rng.randint(2, 3)): quantity, price = rng.randint(1, 4), rng.randint(100, 2000) items.append((len(items) + 1, order_id, quantity, price)) amount += quantity * price refund_amount = 0 for _ in range(rng.randint(0, 2)): cents = rng.randint(50, 500) refund_status = rng.choice(["posted", "posted", "pending"]) refunds.append((len(refunds) + 1, order_id, cents, refund_status)) if refund_status == "posted": refund_amount += cents if status == "completed": totals[customers[customer_id - 1][1]] += amount - refund_amount return _task( "Find net revenue for each customer segment having at least one completed order. " "Revenue is SUM(quantity * unit_price_cents) minus posted refunds, considering only completed orders. " "Pending refunds and cancelled orders do not count. Avoid counting either items or refunds multiple times. " "Columns: segment, net_revenue_cents (integer).", """CREATE TABLE customers(customer_id INTEGER PRIMARY KEY, segment TEXT NOT NULL); CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, status TEXT NOT NULL); CREATE TABLE order_items(item_id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, quantity INTEGER NOT NULL, unit_price_cents INTEGER NOT NULL); CREATE TABLE refunds(refund_id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, amount_cents INTEGER NOT NULL, status TEXT NOT NULL);""", {"customers": customers, "orders": orders, "order_items": items, "refunds": refunds}, [[segment, amount] for segment, amount in sorted(totals.items())], """WITH item_totals AS ( SELECT order_id, SUM(quantity * unit_price_cents) AS amount FROM order_items GROUP BY order_id ), refund_totals AS ( SELECT order_id, SUM(amount_cents) AS amount FROM refunds WHERE status = 'posted' GROUP BY order_id ) SELECT c.segment, SUM(i.amount - COALESCE(r.amount, 0)) AS net_revenue_cents FROM orders o JOIN customers c USING(customer_id) JOIN item_totals i USING(order_id) LEFT JOIN refund_totals r USING(order_id) WHERE o.status = 'completed' GROUP BY c.segment""", ) def _inventory_shortages(rng): products = [(i, rng.randint(8, 24)) for i in range(1, 9)] warehouses = [(1, "north"), (2, "south"), (3, "west")] inventory, reservations, expected = [], [], [] for product_id, reorder_point in products: stock = reserved = 0 for warehouse_id, _ in warehouses: if product_id != 8 and rng.random() < 0.9: quantity = 0 if product_id == 1 else rng.randint(0, 14) inventory.append((product_id, warehouse_id, quantity)) stock += quantity for _ in range(rng.randint(0, 4)): quantity, status = rng.randint(1, 10), rng.choice(["active", "active", "cancelled"]) reservations.append((len(reservations) + 1, product_id, quantity, status)) if status == "active": reserved += quantity available = stock - reserved if available < reorder_point: expected.append([product_id, available]) return _task( "List products whose total available stock across all warehouses is strictly below their reorder_point. " "Available stock is all inventory units minus active reservation units; missing inventory or reservations mean zero. " "Negative availability is valid. Cancelled reservations do not count. " "Columns: product_id, available_units (integer).", """CREATE TABLE products(product_id INTEGER PRIMARY KEY, reorder_point INTEGER NOT NULL); CREATE TABLE warehouses(warehouse_id INTEGER PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE inventory(product_id INTEGER NOT NULL, warehouse_id INTEGER NOT NULL, units INTEGER NOT NULL, PRIMARY KEY(product_id, warehouse_id)); CREATE TABLE reservations(reservation_id INTEGER PRIMARY KEY, product_id INTEGER NOT NULL, units INTEGER NOT NULL, status TEXT NOT NULL);""", { "products": products, "warehouses": warehouses, "inventory": inventory, "reservations": reservations, }, expected, """WITH stocks AS (SELECT product_id, SUM(units) AS units FROM inventory GROUP BY product_id), held AS (SELECT product_id, SUM(units) AS units FROM reservations WHERE status = 'active' GROUP BY product_id) SELECT p.product_id, COALESCE(s.units, 0) - COALESCE(h.units, 0) AS available_units FROM products p LEFT JOIN stocks s USING(product_id) LEFT JOIN held h USING(product_id) WHERE COALESCE(s.units, 0) - COALESCE(h.units, 0) < p.reorder_point""", ) def _service_failure_rates(rng): services = [(i, f"service-{i}") for i in range(1, 7)] metrics, expected = [], [] for service_id, _ in services: valid = [] for day in range(1, 11): requests = rng.randint(100, 1500) failures = rng.randint(0, min(80, requests)) if not (service_id == 1 and day <= 6): mode = rng.randrange(7) if mode == 0: requests = failures = None elif mode == 1: failures = None elif mode == 2: requests = failures = 0 metrics.append((service_id, f"2025-06-{day:02}", requests, failures)) if requests is not None and requests > 0 and failures is not None: valid.append((requests, failures)) if len(valid) >= 5: expected.append( [ service_id, _rounded(Fraction(sum(f for _, f in valid), sum(r for r, _ in valid)), 4), ] ) return _task( "Compute the weighted failure rate for each service with at least five valid observed days. " "A valid day has requests > 0 and non-NULL failures; discard an entire day if either count is missing. " "The rate is SUM(failures) / SUM(requests) across valid days, not the mean of daily rates. " "Columns: service_id, failure_rate (round to four decimal places).", """CREATE TABLE services(service_id INTEGER PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE daily_metrics(service_id INTEGER NOT NULL, day TEXT NOT NULL, requests INTEGER, failures INTEGER, PRIMARY KEY(service_id, day));""", {"services": services, "daily_metrics": metrics}, expected, """SELECT service_id, ROUND(1.0 * SUM(failures) / SUM(requests), 4) AS failure_rate FROM daily_metrics WHERE requests > 0 AND failures IS NOT NULL GROUP BY service_id HAVING COUNT(*) >= 5""", ) def _overdue_invoices(rng): invoices, payments, credits, expected = [], [], [], [] as_of = date(2025, 7, 1) for invoice_id in range(1, 15): customer_id, amount = rng.randint(1, 6), rng.randint(500, 5000) due = as_of + timedelta(days=rng.randint(-25, 10)) status = rng.choice(["issued", "issued", "void"]) if invoice_id == 1: amount, due, status = 10000, as_of - timedelta(days=10), "issued" invoices.append((invoice_id, customer_id, amount, due.isoformat(), status)) paid = credited = 0 for _ in range(rng.randint(0, 3)): cents, payment_status = ( rng.randint(100, 1400), rng.choice(["settled", "settled", "pending"]), ) payments.append((len(payments) + 1, invoice_id, cents, payment_status)) if payment_status == "settled": paid += cents for _ in range(rng.randint(0, 2)): cents, credit_status = rng.randint(50, 500), rng.choice(["approved", "pending"]) credits.append((len(credits) + 1, invoice_id, cents, credit_status)) if credit_status == "approved": credited += cents outstanding = amount - paid - credited if status == "issued" and due < as_of and outstanding > 0: expected.append([invoice_id, customer_id, outstanding]) return _task( "As of 2025-07-01, find issued invoices with due_date strictly earlier than that date and positive outstanding balance. " "Outstanding balance is invoice amount minus settled payments minus approved credits. " "Missing payments or credits count as zero; pending records and void invoices do not count. " "Columns: invoice_id, customer_id, outstanding_cents (integer).", """CREATE TABLE invoices(invoice_id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, amount_cents INTEGER NOT NULL, due_date TEXT NOT NULL, status TEXT NOT NULL); CREATE TABLE payments(payment_id INTEGER PRIMARY KEY, invoice_id INTEGER NOT NULL, amount_cents INTEGER NOT NULL, status TEXT NOT NULL); CREATE TABLE credits(credit_id INTEGER PRIMARY KEY, invoice_id INTEGER NOT NULL, amount_cents INTEGER NOT NULL, status TEXT NOT NULL);""", {"invoices": invoices, "payments": payments, "credits": credits}, expected, """WITH paid AS (SELECT invoice_id, SUM(amount_cents) AS amount FROM payments WHERE status = 'settled' GROUP BY invoice_id), credited AS (SELECT invoice_id, SUM(amount_cents) AS amount FROM credits WHERE status = 'approved' GROUP BY invoice_id), balances AS ( SELECT i.invoice_id, i.customer_id, i.amount_cents - COALESCE(p.amount, 0) - COALESCE(c.amount, 0) AS outstanding_cents FROM invoices i LEFT JOIN paid p USING(invoice_id) LEFT JOIN credited c USING(invoice_id) WHERE i.status = 'issued' AND i.due_date < '2025-07-01' ) SELECT invoice_id, customer_id, outstanding_cents FROM balances WHERE outstanding_cents > 0""", ) def _treatment_effects(rng): participants, readings = [], [] changes = defaultdict(list) for participant_id in range(1, 19): treatment = ("control", "low_dose", "high_dose")[(participant_id - 1) % 3] participants.append((participant_id, treatment)) baseline = rng.randint(35, 85) effect = {"control": 0, "low_dose": -5, "high_dose": -12}[treatment] phases = {} for phase in ("baseline", "followup"): values = [] replicate_count = rng.randint(1, 3) if participant_id <= 3 else rng.randint(0, 3) for _ in range(replicate_count): value = baseline + (effect if phase == "followup" else 0) + rng.randint(-9, 9) if participant_id > 3 and rng.random() < 0.15: value = None readings.append((len(readings) + 1, participant_id, phase, value)) if value is not None: values.append(value) if values: phases[phase] = Fraction(sum(values), len(values)) if len(phases) == 2: changes[treatment].append(phases["followup"] - phases["baseline"]) expected = [ [treatment, _rounded(sum(values) / len(values), 3)] for treatment, values in sorted(changes.items()) ] return _task( "For each treatment, calculate mean within-participant change (followup minus baseline). " "First average all non-NULL replicate readings for each participant and phase. " "Include only participants with at least one non-NULL reading in both phases, then average their changes, giving each participant equal weight. " "Omit treatments with no qualifying participants. Columns: treatment, mean_change (round to three decimal places).", """CREATE TABLE participants(participant_id INTEGER PRIMARY KEY, treatment TEXT NOT NULL); CREATE TABLE readings(reading_id INTEGER PRIMARY KEY, participant_id INTEGER NOT NULL, phase TEXT NOT NULL, value INTEGER);""", {"participants": participants, "readings": readings}, expected, """WITH means AS ( SELECT participant_id, phase, AVG(value) AS mean_value FROM readings WHERE value IS NOT NULL GROUP BY participant_id, phase ), changes AS ( SELECT participant_id, MAX(CASE WHEN phase = 'followup' THEN mean_value END) - MAX(CASE WHEN phase = 'baseline' THEN mean_value END) AS delta FROM means GROUP BY participant_id HAVING COUNT(DISTINCT phase) = 2 ) SELECT p.treatment, ROUND(AVG(c.delta), 3) AS mean_change FROM participants p JOIN changes c USING(participant_id) GROUP BY p.treatment""", ) def _signup_cohorts(rng): users, purchases = [], [] cohorts = defaultdict(lambda: [0, 0]) for user_id in range(1, 19): signup = date(2025, 3 + (user_id - 1) // 6, rng.randint(1, 20)) users.append((user_id, signup.isoformat())) valid_purchases = 0 for index in range(3 if user_id == 1 else rng.randint(0, 5)): offset = index + 1 if user_id == 1 else rng.randint(-3, 40) purchased_at = signup + timedelta(days=offset) status = ( "completed" if user_id == 1 else rng.choice(["completed", "completed", "cancelled"]) ) purchases.append((len(purchases) + 1, user_id, purchased_at.isoformat(), status)) if status == "completed" and 0 <= offset < 30: valid_purchases += 1 cohort = cohorts[signup.strftime("%Y-%m")] cohort[0] += 1 cohort[1] += int(valid_purchases >= 2) expected = [ [month, size, repeat, _rounded(Fraction(repeat, size), 4)] for month, (size, repeat) in sorted(cohorts.items()) ] return _task( "Summarize each signup-month cohort. A repeat buyer has at least two completed purchases on or after signup_at " "and strictly before signup_at + 30 days. All signed-up users belong in the denominator, including users with no purchases. " "Ignore cancelled purchases and records before signup. Columns: cohort_month (YYYY-MM), cohort_size, repeat_buyers, " "repeat_rate (repeat_buyers / cohort_size, rounded to four decimal places).", """CREATE TABLE users(user_id INTEGER PRIMARY KEY, signup_at TEXT NOT NULL); CREATE TABLE purchases(purchase_id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, purchased_at TEXT NOT NULL, status TEXT NOT NULL);""", {"users": users, "purchases": purchases}, expected, """WITH user_counts AS ( SELECT u.user_id, SUBSTR(u.signup_at, 1, 7) AS cohort_month, COUNT(p.purchase_id) AS purchases FROM users u LEFT JOIN purchases p ON p.user_id = u.user_id AND p.status = 'completed' AND p.purchased_at >= u.signup_at AND p.purchased_at < DATE(u.signup_at, '+30 days') GROUP BY u.user_id, u.signup_at ) SELECT cohort_month, COUNT(*) AS cohort_size, SUM(purchases >= 2) AS repeat_buyers, ROUND(1.0 * SUM(purchases >= 2) / COUNT(*), 4) AS repeat_rate FROM user_counts GROUP BY cohort_month""", ) def _missing_inspections(rng): machines = [(i, f"machine-{i}") for i in range(1, 11)] repairs, inspections, expected = [], [], [] as_of = "2025-07-01" start = date(2025, 6, 1) for machine_id, _ in machines: completed, passed = [], [] for index in range(rng.randint(1, 3)): repaired_at = (start + timedelta(days=rng.randint(0, 35))).isoformat() status = rng.choice(["completed", "completed", "cancelled"]) if machine_id == 1 and index == 0: repaired_at, status = "2025-06-10", "completed" repairs.append((len(repairs) + 1, machine_id, repaired_at, status)) if status == "completed" and repaired_at <= as_of: completed.append(repaired_at) for _ in range(0 if machine_id == 1 else rng.randint(0, 5)): inspected_at = (start + timedelta(days=rng.randint(0, 35))).isoformat() result = rng.choice(["pass", "fail"]) inspections.append((len(inspections) + 1, machine_id, inspected_at, result)) if result == "pass" and inspected_at <= as_of: passed.append(inspected_at) if completed: latest = max(completed) if not any(inspected_at >= latest for inspected_at in passed): expected.append([machine_id, latest]) return _task( "As of 2025-07-01 inclusive, find machines with a completed repair but no passing inspection on or after their latest completed repair. " "Repairs marked cancelled do not count. Ignore all repairs and inspections after the as-of date; " "a passing inspection on the repair date is sufficient. Exclude machines with no completed repair by the as-of date. " "Columns: machine_id, last_repair_date (YYYY-MM-DD).", """CREATE TABLE machines(machine_id INTEGER PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE repairs(repair_id INTEGER PRIMARY KEY, machine_id INTEGER NOT NULL, repaired_at TEXT NOT NULL, status TEXT NOT NULL); CREATE TABLE inspections(inspection_id INTEGER PRIMARY KEY, machine_id INTEGER NOT NULL, inspected_at TEXT NOT NULL, result TEXT NOT NULL);""", {"machines": machines, "repairs": repairs, "inspections": inspections}, expected, """WITH latest AS ( SELECT machine_id, MAX(repaired_at) AS last_repair_date FROM repairs WHERE status = 'completed' AND repaired_at <= '2025-07-01' GROUP BY machine_id ) SELECT l.machine_id, l.last_repair_date FROM latest l WHERE NOT EXISTS ( SELECT 1 FROM inspections i WHERE i.machine_id = l.machine_id AND i.result = 'pass' AND i.inspected_at >= l.last_repair_date AND i.inspected_at <= '2025-07-01' )""", ) def _latency_regressions(rng): services, samples = [], [] regions = defaultdict(list) for service_id in range(1, 13): region = ("east", "west", "central")[(service_id - 1) // 4] services.append((service_id, region)) before = rng.randint(30, 180) after = before + rng.randint(-20, 90) averages = {} for phase, center in (("before", before), ("after", after)): values = [center + rng.randint(-6, 6) for _ in range(2)] averages[phase] = Fraction(sum(values), len(values)) for value in values: samples.append((len(samples) + 1, service_id, phase, value)) regions[region].append((service_id, averages["after"] - averages["before"])) expected = [] for region, regressions in sorted(regions.items()): for service_id, delta in sorted(regressions, key=lambda pair: (-pair[1], pair[0]))[:2]: expected.append([region, service_id, _rounded(delta, 2)]) return _task( "For each region, return exactly two services with the largest latency increase after deployment. " "Increase is mean after latency minus mean before latency, using all samples in each phase. " "Rank on the unrounded increase descending and break ties by service_id ascending. Negative increases remain eligible. " "Columns: region, service_id, latency_increase_ms (round to two decimal places).", """CREATE TABLE services(service_id INTEGER PRIMARY KEY, region TEXT NOT NULL); CREATE TABLE latency_samples(sample_id INTEGER PRIMARY KEY, service_id INTEGER NOT NULL, phase TEXT NOT NULL, latency_ms INTEGER NOT NULL);""", {"services": services, "latency_samples": samples}, expected, """WITH changes AS ( SELECT s.region, s.service_id, AVG(CASE WHEN l.phase = 'after' THEN l.latency_ms END) - AVG(CASE WHEN l.phase = 'before' THEN l.latency_ms END) AS increase FROM services s JOIN latency_samples l USING(service_id) GROUP BY s.region, s.service_id ), ranked AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY region ORDER BY increase DESC, service_id ASC) AS place FROM changes ) SELECT region, service_id, ROUND(increase, 2) AS latency_increase_ms FROM ranked WHERE place <= 2""", ) def _delivery_streaks(rng): drivers = [(i, f"driver-{i}") for i in range(1, 7)] jobs, expected = [], [] for driver_id, _ in drivers: longest = current = 0 day = datetime(2025, 6, 1, 9) for index in range(10): day += timedelta(days=rng.randint(1, 2)) due = day + timedelta(hours=2) status = rng.choice(["delivered", "delivered", "delivered", "cancelled"]) actual = ( due + timedelta(minutes=rng.randint(-40, 40)) if status == "delivered" else None ) if driver_id == 1 and index == 0: status, actual = "delivered", due - timedelta(minutes=1) jobs.append( ( len(jobs) + 1, driver_id, day.isoformat(), due.isoformat(), actual.isoformat() if actual else None, status, ) ) if status == "delivered" and actual <= due: current += 1 longest = max(longest, current) else: current = 0 expected.append([driver_id, longest]) return _task( "For every driver, find the longest streak of consecutive scheduled jobs delivered on time. " "Order each driver's jobs by scheduled_at ascending, then job_id ascending. A job is on time only if status = 'delivered' " "and delivered_at <= due_at. A cancelled job, late delivery, or missing delivered_at breaks the streak. " "Calendar gaps between jobs do not break it. Return zero for drivers with no on-time jobs. " "Columns: driver_id, longest_on_time_streak (integer).", """CREATE TABLE drivers(driver_id INTEGER PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE jobs(job_id INTEGER PRIMARY KEY, driver_id INTEGER NOT NULL, scheduled_at TEXT NOT NULL, due_at TEXT NOT NULL, delivered_at TEXT, status TEXT NOT NULL);""", {"drivers": drivers, "jobs": jobs}, expected, """WITH flags AS ( SELECT *, CASE WHEN status = 'delivered' AND delivered_at <= due_at THEN 1 ELSE 0 END AS on_time FROM jobs ), islands AS ( SELECT *, SUM(1 - on_time) OVER (PARTITION BY driver_id ORDER BY scheduled_at, job_id ROWS UNBOUNDED PRECEDING) AS streak_group FROM flags ), streaks AS ( SELECT driver_id, streak_group, COUNT(*) AS length FROM islands WHERE on_time = 1 GROUP BY driver_id, streak_group ) SELECT d.driver_id, COALESCE(MAX(s.length), 0) AS longest_on_time_streak FROM drivers d LEFT JOIN streaks s USING(driver_id) GROUP BY d.driver_id""", ) def _currency_conversion(rng): rates, transactions = [], [] by_currency = defaultdict(list) totals = defaultdict(Fraction) last_settled = {} start = date(2025, 6, 1) for currency, base in (("EUR", 1100000), ("GBP", 1300000), ("JPY", 7500)): for index in range(6): effective_at = (start + timedelta(days=index * 5)).isoformat() rate = base + rng.randint(-100, 100) * (500 if currency != "JPY" else 5) rates.append((currency, effective_at, rate)) by_currency[currency].append((effective_at, rate)) for transaction_id in range(1, 31): currency = ("EUR", "GBP", "JPY")[(transaction_id - 1) % 3] occurred_at = (start + timedelta(days=rng.randint(0, 29))).isoformat() amount = rng.randint(100, 20000) * (-1 if rng.random() < 0.2 else 1) status = "settled" if transaction_id <= 3 else rng.choice(["settled", "settled", "pending"]) transactions.append((transaction_id, currency, occurred_at, amount, status)) if status == "settled": applicable = [item for item in by_currency[currency] if item[0] <= occurred_at] rate = max(applicable)[1] totals[currency] += Fraction(amount * rate, 100 * 1000000) last_settled[currency] = (len(transactions) - 1, rate) # SQLite ROUND uses binary floats. Avoid exact half-cent totals, where a # mathematically equivalent query can round a decimal midpoint differently. for currency, total in totals.items(): if (total * 100).denominator == 2: index, rate = last_settled[currency] transaction = list(transactions[index]) transaction[3] += 1 transactions[index] = tuple(transaction) totals[currency] += Fraction(rate, 100 * 1000000) expected = [[currency, _rounded(amount, 2)] for currency, amount in sorted(totals.items())] return _task( "Convert settled transactions to USD, then total by currency. For each transaction use that currency's latest exchange rate " "with effective_at on or before occurred_at. amount_minor is in hundredths of the source currency, including for JPY; " "usd_micros_per_unit is millionths of a USD per one source-currency unit. Negative amounts are refunds. " "Ignore pending transactions. A prior rate always exists. Sum unrounded converted amounts, then round once. " "Columns: currency, total_usd (round to two decimal places).", """CREATE TABLE exchange_rates(currency TEXT NOT NULL, effective_at TEXT NOT NULL, usd_micros_per_unit INTEGER NOT NULL, PRIMARY KEY(currency, effective_at)); CREATE TABLE transactions(transaction_id INTEGER PRIMARY KEY, currency TEXT NOT NULL, occurred_at TEXT NOT NULL, amount_minor INTEGER NOT NULL, status TEXT NOT NULL);""", {"exchange_rates": rates, "transactions": transactions}, expected, """SELECT t.currency, ROUND(1.0 * SUM(t.amount_minor * r.usd_micros_per_unit) / 100000000, 2) AS total_usd FROM transactions t JOIN exchange_rates r ON r.currency = t.currency AND r.effective_at = ( SELECT MAX(r2.effective_at) FROM exchange_rates r2 WHERE r2.currency = t.currency AND r2.effective_at <= t.occurred_at ) WHERE t.status = 'settled' GROUP BY t.currency""", ) _BUILDERS = { "sales_net_revenue": _sales_net_revenue, "inventory_shortages": _inventory_shortages, "service_failure_rates": _service_failure_rates, "overdue_invoices": _overdue_invoices, "treatment_effects": _treatment_effects, "signup_cohorts": _signup_cohorts, "missing_inspections": _missing_inspections, "latency_regressions": _latency_regressions, "delivery_streaks": _delivery_streaks, "currency_conversion": _currency_conversion, } TASK_IDS = list(_BUILDERS) def build_task(task_id: str, seed: int) -> Task: """Build a reproducible, fresh database and its private reference answer.""" try: builder = _BUILDERS[task_id] except KeyError: raise ValueError(f"Unknown task_id {task_id!r}; choose one of {TASK_IDS}") from None return builder(random.Random(seed))