Build golden questions from your own work
읽는 데 약 47분분 걸린다, 9절에 8개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.15판을 번역한 것이다. 원문 읽기
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
By the end of this chapter, you can write golden questions from the questions people in your business ask, each with its golden SQL, the role that asks it and the kind of answer it needs. You can compare an agent's results with golden results rather than comparing SQL text, check the gold itself before you trust it, and say why a score on a public benchmark isn't a score on your warehouse.
Chapter 1 scored two approaches on five golden questions, and five questions can only serve as a smoke test. A change to the prompt that fixes or breaks one question moves the score by a fifth, and a change that fixes one and breaks another doesn't move it at all. Nothing in them tests a decline for an ambiguous question or one the asker's role may not see. Every later chapter in this book changes one part of the agent and claims that the change helped. Those claims need a set large enough to measure, with questions that cover the warehouse's traps, roles and declines, and with a part held back that no change is tuned on.
Chapter 2 added eleven more, each aimed at one trap. This chapter keeps all sixteen and builds the set to 48 golden questions about the orders, refunds and customers of the shop, whose generated warehouse the agent queries. It starts with the case for writing your own questions at all, since public benchmarks exist and are cheaper to download than to write.
공개 벤치마크는 여러분의 테스트가 아니다
텍스트-SQL 또는 데이터 에이전트용 공개 벤치마크는 질문, 데이터베이스, 질문마다의 정답(gold answer), 그리고 같은 세트에서 다른 사람들이 보고한 점수를 제공한다. 그래서 모델을 비교하는 데는 유용하다. 그러나 에이전트가 여러분의 웨어하우스에서 어떻게 동작할지는 알려 주지 못하는데, 이유는 두 가지다. 벤치마크의 질문, 데이터, 정의는 다른 사람의 것이므로, 높은 점수는 모델이 그들의 작업을 잘 처리한다는 뜻일 뿐이다. 또한 정답은 사람이 작성한 주장이므로, 점수는 정답이 얼마나 자주 옳은지도 함께 측정한다.
두 번째 이유는 실제로 측정된 바 있다. CIDR 2026에서 발표된 감사에서는 전문가들이 각 정답 쿼리를 질문 및 스키마와 대조해 확인하고, 쿼리와 그 하위 쿼리를 실행했다. 그 결과 BIRD Mini-Dev의 최초 500문항 버전에서 52.8%, 정답 SQL이 spider2-snow-0713 파일로 공개된 Spider 2.0-Snow 문제 121개 중 66.1%에서 주석 오류가 발견되었다(Jin et al., CIDR 2026). 가장 흔한 오류는 데이터나 스키마를 잘못 해석한 정답 SQL이었다. 저자들이 BIRD Dev 문제 100개를 수정하고 오픈소스 에이전트 다섯 개를 다시 실행하자 점수는 상대적으로 −3%에서 +31%까지 달라졌고, 한 에이전트는 4위에서 1위가 되었다. 벤치마크는 시간이 지나며 바뀌기도 한다. BIRD 팀은 2026년 10월 26일과 27일에 Mini-Dev를 개정하여 참조 SQL을 고치고 문제를 교체했으며, 2025년 릴리스는 아카이브로 남겼다(BIRD Mini-Dev). 이 수치들은 논문이 측정한 값이며 우리가 측정한 값이 아니다. 이 책은 BIRD와 Spider를 인용하되 포함하여 배포하지는 않는다. 책이 배포하는 데이터는 CC BY 4.0, CC0 또는 자체 라이선스의 데이터뿐인데, BIRD는 CC BY-SA 4.0이기 때문이다.
첫 번째 이유는 책이 배포할 수 있는 데이터에서 확인할 수 있으므로, 이 장에서는 CC BY 4.0으로 공개된 DABstep(Data Agent Benchmark for Multi-step Reasoning)의 일부를 사용한다. DABstep은 결제 처리 업체의 거래에 관해 질문하고, 최종 답만 채점하며, 리더보드를 위해 대부분의 과제를 비공개로 둔다(논문). 데이터셋은 과제 450개로 이루어져 있으며, 답이 공개된 것은 dev 과제 10개뿐이다(데이터셋). 이 책의 사본은 examples/data/dabstep/에 있으며, DABstep의 낮은 난이도에 해당하는 dev 과제 3개와 거래 138,236건의 전체 결제 테이블을 담고 있다. 다만 어떤 과제에도 필요하지 않은 식별자 열 네 개, 즉 해시된 IP 주소, 구매자 이메일, 카드 번호, 각 카드의 은행 식별 번호는 제외했다. SOURCE.md에는 데이터셋의 고정된 리비전과 모든 변경 사항이 적혀 있고, LICENSE는 데이터셋 자체의 고지문이다. 결제 테이블의 가맹점은 가상의 사업체이며, 그 이름은 공개된 DABstep의 것을 그대로 따랐다. lib/dabstep.py가 이 테이블을 DuckDB에 적재한다.
두 세트 모두에 대해 하나의 모델, 곧 녹화본에서 재생한 Qwen3-4B-Instruct-2507로 1장의 스키마 전용 접근법을 실행한다. 모델은 테이블의 스키마와 질문을 보고 SQL을 작성하며, 이 SQL이 실행된다. DABstep에서는 모델이 이어서 쿼리 결과를 읽고 과제가 요구하는 형식으로 최종 답을 낸다. 녹화본 dabstep-runs에 이 응답들이 들어 있다.
1"""Score schema-only SQL on three public DABstep tasks and on the shop's dev questions, with the same model.2The point about task 49 rests on its "SQL ran: False" line, which the assert checks, and on the two top-country lines3that follow it, which read the same fraud data by two definitions."""4from lib import dabstep5from lib.golden import load_golden, schema_only_outcome6from lib.model import RecordedModel7from lib.warehouse import connect, describe_schema89payments = dabstep.connect()10runs = [dabstep.answer_task(payments, RecordedModel("dabstep-runs"), task) for task in dabstep.load_tasks()] # replays recorded replies11for run in runs:12 print(f"task {run.task.task_id}: answered {run.answer[:40]!r}, expected {run.task.answer!r}, correct: {run.correct}")13 print(f"task {run.task.task_id} SQL ran: {not run.result.startswith('error')}")14print(f"DABstep correct: {sum(run.correct for run in runs)} of {len(runs)}")15task49 = next(run for run in runs if str(run.task.task_id) == "49")16assert task49.result.startswith("error") # a query that fails comes back as text that starts with "error"1718# Task 49 asks for the top country "for fraud". DABstep's manual defines fraud as fraudulent volume over total volume.19by_count, by_volume = payments.execute("""20 SELECT arg_max(ip_country, frauds), arg_max(ip_country, fraud_share) FROM (21 SELECT ip_country, count(*) FILTER (has_fraudulent_dispute) AS frauds,22 sum(eur_amount) FILTER (has_fraudulent_dispute) / sum(eur_amount) AS fraud_share23 FROM payments GROUP BY ip_country)""").fetchall()[0] # one row: the top country by each measure24print(f"task 49 top by count of frauds: {by_count}")25print(f"task 49 top by fraud volume ratio: {by_volume}")2627con = connect()28schema, model = describe_schema(con), RecordedModel("schema-only-sql") # the recorded replies to the schema-only prompt29dev = [q for q in load_golden() if q.split == "dev"]30outcomes = [schema_only_outcome(con, model, schema, q) for q in dev]31print(f"shop dev correct: {outcomes.count('correct')} of {len(dev)}")
python public-vs-own-score.pytask 5: answered 'NL', expected 'NL', correct: True
task 5 SQL ran: True
task 49: answered '3. ES', expected 'B. BE', correct: False
task 49 SQL ran: False
task 70: answered '```sql\nSELECT \n AVG(CAST(p.has_fraudule', expected 'Not Applicable', correct: False
task 70 SQL ran: False
DABstep correct: 1 of 3
task 49 top by count of frauds: NL
task 49 top by fraud volume ratio: BE
shop dev correct: 2 of 24
두 세트는 서로 다른 것을 묻기 때문에 어느 한쪽의 점수로 다른 쪽을 예측할 수 없으며, 두 점수의 차이 자체가 요점은 아니다. 스키마 전용 SQL은 DABstep 과제를 1 of 3 맞히는데, 채점은 DABstep의 준정확 일치(quasi-exact match)를 단순화한 방식으로 한다. shop dev 질문은 2 of 24 맞힌다. DABstep의 과제는 회계 달력도, 취소된 주문도, 레거시 마트도 없는 하나의 테이블에 관한 것이다. 상점의 질문은 바로 그런 부분에서 실패한다.
과제 49는 정답이 무엇에 좌우되는지 보여 준다. 이 과제는 "사기(fraud)" 기준으로 상위 국가를 묻고, 정답은 BE이다. 사기 거래의 건수로 세면 상위 국가는 NL이다. 결제 금액에서 사기가 차지하는 비중으로 재면 BE이다. 이를 정리해 주는 것은 DABstep의 매뉴얼이다. 매뉴얼은 사기를 "총 거래액 대비 사기 거래액의 비율"로 정의한다(매뉴얼). 질문만으로는 이를 정할 수 없다. 여기서 과제 49에 대한 모델의 SQL은 실행에 실패했는데도 국가 하나를 답으로 내놓았다. 과제 70의 정답은 Not Applicable이다. 우리가 읽은 바로는 매뉴얼에는 사기 관련 수수료에 대한 설명은 있지만 벌금에 대한 설명은 없다. 모델은 답 대신 쿼리로 응답했다.
작업 규칙: 공개 벤치마크는 공통 과제에서 모델을 비교하는 데 사용하고, 에이전트가 여러분의 웨어하우스에서 동작한다는 증거로는 절대 사용하지 않는다. 정답 세트는 수정되기 때문에, 점수를 인용할 때는 벤치마크의 버전을 함께 밝힌다. 에이전트의 성능은 여러분 자신의 업무에서, 여러분의 정의로 작성한 골든 질문으로 측정하고, 두 점수가 서로 다를 것으로 예상한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Write questions from the work people do
A public benchmark measures someone else's work, so this set has to come from the shop. The best source is the questions people already ask: requests in the analytics team's queue, the numbers in a monthly finance pack, the filters people set on dashboards. Write each in the asker's words, not tidied into the schema's vocabulary, because the agent will hear the asker's words. Then write the golden SQL that answers it under the business's definitions, and check it.
Each golden question holds the same fields. The question is the asker's text. The role is who asks, which decides what they may see, and a regional_lead also carries their region. A golden question's kind says what a right answer looks like: answer when the warehouse can answer it, decline when it can't, and forbidden when the role may not see the answer. A decline also has a decline_type, ambiguous or unanswerable. An answerable question has golden_sql, a comparison rule (order_matters and a tolerance), and a note that names the definition the gold follows. Each question also lists the warehouse's traps it tests, such as fiscal-calendar or late-refunds, and sits in the dev or the test split.
The shop's set lives in examples/data/golden/questions.toml, and load_golden() in lib/golden.py reads it into GoldenQuestion objects. The file's header states the two definitions most questions depend on. Net revenue is the finance team's: euros after discounts and before tax, from real orders that weren't cancelled, on the order's local business day. An order count includes cancelled orders and leaves out test orders. One question in full shows what its fields hold.
1"""Load the shop's golden questions, show what one holds and how the set divides, and compute one gold's other reading.2The prose's refund point rests on the last two lines, which group the same refunds by the order's month and by the refund's."""3from collections import Counter45from lib.golden import golden_result, load_golden6from lib.warehouse import connect78con = connect()9questions = load_golden()10print(f"golden questions: {len(questions)}")11for kind, count in sorted(Counter(q.kind for q in questions).items()):12 print(f"{kind}: {count}")13for decline_type, count in sorted(Counter(q.decline_type for q in questions if q.kind == "decline").items()):14 print(f"decline, {decline_type}: {count}")15print(f"roles: {', '.join(sorted({q.role for q in questions}))}")1617q = next(q for q in questions if q.question_id == "gq-018")18print()19print(f"{q.question_id} ({q.split}, {q.kind}, asked by {q.role})")20print(f"question: {q.question}")21print(f"golden SQL: {' '.join(q.golden_sql.split())}")22print(f"traps: {', '.join(q.traps)}")23print(f"note: {q.note}")2425# The other reading: refunds grouped by the month they were made, not the month the order was placed.26by_refund_month = con.execute(27 "SELECT round(sum(amount_eur), 2) FROM analytics.fct_refunds WHERE refund_month = DATE '2026-03-01'").fetchall()28print(f"refunded on orders placed in March 2026: {golden_result(con, q)[0][0]:,.2f}") # gq-018's gold: by the order's month29print(f"refunded in March 2026, by refund month: {by_refund_month[0][0]:,.2f}")
python load-golden-questions.pygolden questions: 48
answer: 34
decline: 8
forbidden: 6
decline, ambiguous: 4
decline, unanswerable: 4
roles: analyst, finance, marketing, regional_lead, support
gq-018 (dev, answer, asked by finance)
question: How much was refunded, in euros, on orders placed in March 2026?
golden SQL: SELECT round(sum(r.amount_eur), 2) AS refunded FROM analytics.fct_refunds AS r WHERE r.order_month = DATE '2026-03-01'
traps: late-refunds, currency
note: Refunds belong to the order's month here, including refunds made in April or later.
refunded on orders placed in March 2026: 13,046.38
refunded in March 2026, by refund month: 6,646.99
Most of the set asks for an answer; the rest tests when to hold back. The set holds 48 questions: 34 to answer, 8 to decline and 6 that the asking role may not see.
Of the declines, 4 are ambiguous and 4 are unanswerable. Every role in the case asks at least one question.
The question the example prints, gq-018, is one a finance team asks after every month closes. Its golden SQL is short, and its value is in the definition: refunds belong to the month the order was placed, including refunds made weeks later. Refunds on orders placed in March 2026 come to 13,046.38 euros, and a reasonable query that picks refunds by the month they were made returns 6,646.99. Both numbers are useful. The golden question records which one this asker means, and its note says so in words a reviewer can check without reading SQL.
Most of the work is deciding what the asker meant and finding the definition someone owns. Write the note first. If you can't write it in one sentence, the question is ambiguous, and it becomes a decline.
Working rule: Collect golden questions from real requests, keep the asker's wording, and give each one a role, a kind and a note that names the definition its gold follows. Write the golden SQL against the marts the agent will use, and have the person who owns the definition read the note. Expect to spend more time on the definitions than on the SQL.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Compare results, not SQL text
With the golden questions written, the next decision is how to tell whether an agent's answer matches. Comparing the agent's SQL with the golden SQL fails both ways. Two queries can be written differently and return the same rows, and two queries a few words apart can return different numbers. What the asker sees is the result, so that's what to compare. An execution match means the agent's result equals the golden result under the question's comparison rule. Benchmarks do the same: BIRD reports execution accuracy, which compares the rows each query returns (calculate_ex in BIRD's evaluation code), and DABstep scores the final answer by a quasi-exact match (the paper).
In the shop, gq-001 asks for net revenue in fiscal year 2026. Its golden SQL sums net_revenue_eur over fct_orders, joined to dim_date for the fiscal year. Its check query, which the section on checking the gold uses, sums net_amount_eur over fct_order_lines with a date range instead. Two queries show where text and results part ways, each compared with the golden SQL: the check query, and the golden SQL with its filter on cancelled orders removed. For each, it asks whether the text is equal, whether it is equal after sqlglot normalizes both, and whether the results match under results_match().
1"""Two queries written differently for the same golden question: compare their text, then compare their results.2The point rests on the last two result lines, "results match": the order-lines query matches the golden result, and3the query that forgets cancelled orders does not. The asserts at the end check both."""4import sqlglot5from lib.golden import golden_result, load_golden, results_match6from lib.warehouse import connect78con = connect()9q = next(q for q in load_golden() if q.question_id == "gq-001") # net revenue in fiscal year 202610by_orders, by_lines = q.golden_sql, q.check_sql # orders joined to dim_date; lines by date range11forgets_cancelled = by_orders.replace("o.status <> 'cancelled' AND ", "") # the golden SQL's cancelled-order filter, removed121314def normalized(sql: str) -> str:15 # parses and writes the SQL back in DuckDB's form, so spacing and identifier case don't count as differences16 return sqlglot.parse_one(sql, read="duckdb").sql(dialect="duckdb", normalize=True, pretty=False)171819golden = golden_result(con, q)20for name, sql in [("by lines", by_lines), ("forgets cancelled", forgets_cancelled)]:21 rows = con.execute(sql).fetchall()22 print(f"{name}: {rows[0][0]:,.2f} against golden {golden[0][0]:,.2f}")23 print(f"{name} same text: {sql == by_orders}")24 print(f"{name} same normalized text: {normalized(sql) == normalized(by_orders)}")25 print(f"{name} results match: {results_match(rows, golden)}")26# a change to either result must fail this run, as the prose states both facts27assert results_match(con.execute(by_lines).fetchall(), golden)28assert not results_match(con.execute(forgets_cancelled).fetchall(), golden)
python results-match-rules.pyby lines: 1,664,762.75 against golden 1,664,763.72
by lines same text: False
by lines same normalized text: False
by lines results match: True
forgets cancelled: 1,755,242.00 against golden 1,664,763.72
forgets cancelled same text: False
forgets cancelled same normalized text: False
forgets cancelled results match: False
The query over order lines reads a different table, so its text differs from the gold's even after normalizing. Its result matches: it totals 1,664,762.75 against golden 1,664,763.72, under a euro from the gold, since each line is rounded to the cent and the tolerance absorbs that. The query that forgets cancelled orders returns 1,755,242.00 against golden 1,664,763.72, and its result doesn't match. In text, it is one predicate away from the gold. Normalizing doesn't rescue a comparison of text in either direction, because no parser can tell that two different joins give the same sum on this data.
An execution match has its own blind spot. A query can return the right number for the wrong reason on today's data, such as a filter that happens to remove no rows. Checking more questions, and reading the SQL behind surprising matches, is the defence. That's one reason the set has 48 questions and not 5.
Working rule: Score an agent by comparing its result with the golden result, never by comparing SQL text, normalized or not. Keep one comparison function for every score you report, so a change in the score is a change in the agent. When a match surprises you, read the agent's SQL, because a result can match by coincidence.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Order, rounding and column names
A comparison of results still needs rules for the ways two correct results differ. Rows come back in any order unless the query sorts them. Columns carry whatever names the writer chose, in whatever order. Numbers are rounded differently. A rule that is too strict marks correct answers wrong, and a rule that is too loose lets wrong ones through.
results_match(), the comparison every score in this book uses, makes these choices. Rows may come in any order, unless the golden question sets order_matters. Column names are ignored, and columns may come in any order: it tries each way of lining up the answer's columns with the golden ones. Extra columns are allowed, such as a month next to a total for that month, but the number of rows must be equal. Numbers must agree with the gold within 0.05% relative by default, plus an absolute slack of half a unit in the last place the gold rounds to. For money, rounded to the cent, that's half a cent, the default. Changing gq-002's golden result, net revenue in each region in March 2026, the ways real answers differ, and comparing each with the original shows which differences the comparison forgives.
1"""Change the golden result for net revenue by region in March 2026 in the ways real answers differ, and compare.2Then move a ratio gold, gq-033's conversion rates, by a near miss. The prose's claims about thousands and about the3near miss rest on the lines that print True or False, and the asserts check them."""4from lib.golden import golden_result, load_golden, results_match5from lib.warehouse import connect67con = connect()8q = next(q for q in load_golden() if q.question_id == "gq-002")9golden = sorted((region, float(revenue)) for region, revenue in golden_result(con, q)) # sorted by region, so the variants line up10print(f"golden: {golden}")11print(f"tolerance: {q.tolerance:.2%} relative")12print(f"absolute slack: {q.absolute}")1314variants = {15 "rows reversed": golden[::-1],16 "columns swapped": [(revenue, region) for region, revenue in golden],17 "extra month column": [(region, "2026-03", revenue) for region, revenue in golden],18 "rounded to whole euros": [(region, round(revenue)) for region, revenue in golden],19 "rounded to thousands": [(region, round(revenue, -3)) for region, revenue in golden], # round(x, -3) rounds to the nearest thousand20 "in thousands of euros": [(region, revenue / 1000) for region, revenue in golden], # same numbers, unit changed to thousands21 "one region missing": golden[:-1], # drops the last region22}23for name, rows in variants.items():24 print(f"{name}: {results_match(rows, golden, q.order_matters, q.tolerance)}")25# reporting in thousands of euros must fail: a change of unit the agent doesn't state is a real error26assert not results_match(variants["in thousands of euros"], golden, q.order_matters, q.tolerance)2728ranked = sorted(golden, key=lambda row: -row[1]) # highest revenue first, so the reversed list is the wrong order29print(f"ranking reversed, order matters: {results_match(ranked[::-1], ranked, order_matters=True)}")3031# A ratio: gq-033's conversion rates, rounded to four places, with its absolute slack of half that last place.32rates_q = next(q for q in load_golden() if q.question_id == "gq-033")33rates = [(channel, float(rate)) for channel, rate in golden_result(con, rates_q)]34near_miss = [(channel, rate + 0.004) for channel, rate in rates] # 0.004 is about 3% of each rate35print(f"gq-033 rates: {min(r for _, r in rates):.4f} to {max(r for _, r in rates):.4f}")36print(f"gq-033 absolute slack: {rates_q.absolute:.5f}")37print(f"rates 0.004 higher, gq-033's rule: "38 f"{results_match(near_miss, rates, rates_q.order_matters, rates_q.tolerance, rates_q.absolute)}")39print(f"rates 0.004 higher, half a cent of slack: {results_match(near_miss, rates, rates_q.order_matters, rates_q.tolerance)}")40# under the question's own slack the near miss is a miss; with half a cent of slack the same near miss matches41assert not results_match(near_miss, rates, rates_q.order_matters, rates_q.tolerance, rates_q.absolute)42assert results_match(near_miss, rates, rates_q.order_matters, rates_q.tolerance)
python tolerant-comparison.pygolden: [('AMER', 51762.14), ('APAC', 35296.93), ('EMEA', 63023.76)]
tolerance: 0.05% relative
absolute slack: 0.005
rows reversed: True
columns swapped: True
extra month column: True
rounded to whole euros: True
rounded to thousands: False
in thousands of euros: False
one region missing: False
ranking reversed, order matters: False
gq-033 rates: 0.1156 to 0.1284
gq-033 absolute slack: 0.00005
rates 0.004 higher, gq-033's rule: False
rates 0.004 higher, half a cent of slack: True
Reversed rows, swapped columns and an extra month column all match, and so does rounding to whole euros, which moves a regional total by at most half a euro. Rounding to thousands of euros fails, and so does reporting in thousands of euros. A person reading a small number under a heading of thousands would understand it, but the comparison can't see the heading. That's deliberate. An agent that changes units without saying so is a risk, so the golden question fixes the unit and the agent must meet it. A missing region fails. For a ranking, such as gq-039's, order_matters is set, so the regions ranked by revenue in reverse order fail too.
The tolerance needs care in both directions. Ratios such as a conversion rate are small numbers, where half a cent of slack is a lot. gq-033's conversion rates run from 0.1156 to 0.1284, so 0.005 is about 4% of each. Its gold rounds to four places, and its absolute slack is half that last place, 0.00005. Adding 0.004 to every rate is a near miss at this scale: under gq-033's rule it fails, and with half a cent of slack it would match. The book's other ratios, gq-031 and gq-034, follow the same rule.
Working rule: Ignore row order, column order and column names, allow extra columns, and require the same number of rows and numbers within a small relative tolerance. Round each gold to a stated place, and allow half a unit in that place on top. Set order_matters only when the question asks for a ranking or a sequence. Fix units and scale in the question or its note, and treat an answer in other units as wrong, because nobody reading it can tell.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Check the gold before you trust it
Public benchmarks show what happens to unchecked gold: about half of one set was wrong. A golden question written in an afternoon is no different. Its SQL can miss a filter, read the wrong table or follow a definition nobody owns, and every score built on it inherits the mistake. So check each gold before it scores anything. It must run. It must return rows, without NULL values, since an empty gold matches any query that also returns nothing. Where you can, a second query written another way, the gold's check_sql, must return the same result as the golden SQL. And its note must name the definition it follows, so a person can say whether it's the right one.
The shop's set gets those checks, with each check query written independently of its golden SQL: from order lines instead of orders, from a date range instead of the fiscal calendar, or by counting another way. Then look at one question in two readings: which country is top for refunds in fiscal 2026, by the number of refunds and by refund rate.
1"""Check the gold before trusting it: every golden SQL runs and returns rows, and each check query agrees with it.2The prose's gold claims rest on the counts of runs, empty results and agreeing checks, and its refund point on the last two readings."""3import duckdb4from lib.golden import golden_result, load_golden, results_match5from lib.warehouse import connect67con = connect()8answerable = [q for q in load_golden() if q.kind == "answer"]9results, failed = {}, []10for q in answerable:11 try:12 results[q.question_id] = golden_result(con, q)13 except duckdb.Error:14 failed.append(q.question_id)15empty = [qid for qid, rows in results.items() if not rows or any(v is None for row in rows for v in row)] # a NULL in any cell fails, too16print(f"golden SQL that runs: {len(results)} of {len(answerable)}")17print(f"golden SQL that fails: {', '.join(failed) or 'none'}")18print(f"empty or NULL results: {len(empty)}")1920checked = [q for q in answerable if q.check_sql and q.question_id in results]21agree = [q for q in checked if results_match(con.execute(q.check_sql).fetchall(), results[q.question_id],22 q.order_matters, q.tolerance, q.absolute)]23print(f"questions with a check query: {len(checked)}")24print(f"checks that agree: {len(agree)} of {len(checked)}")2526# One question, two readings: "top country for refunds" by number of refunds, and by refund rate (gq-028's definition).27# orders join to their local business day; the LEFT JOIN keeps orders that have no refund, so they still count28by_count, by_rate = con.execute("""29 SELECT arg_max(country, refunds), arg_max(country, refunded / gross) FROM (30 SELECT o.country, count(r.refund_id) AS refunds, sum(r.amount_eur) AS refunded,31 sum(o.gross_revenue_eur) AS gross32 FROM analytics.fct_orders AS o33 JOIN analytics.dim_date AS d ON d.date_day = o.order_date_local34 LEFT JOIN analytics.fct_refunds AS r USING (order_id)35 WHERE o.status <> 'cancelled' AND d.fiscal_year = 202636 GROUP BY o.country)""").fetchall()[0] # one row: arg_max returns the country at the largest value37print(f"top country by number of refunds: {by_count}")38print(f"top country by refund rate: {by_rate}")39print(f"gq-028 golden: {results['gq-028'][0][0]}")
python gold-runs-and-agrees.pygolden SQL that runs: 34 of 34
golden SQL that fails: none
empty or NULL results: 0
questions with a check query: 7
checks that agree: 7 of 7
top country by number of refunds: US
top country by refund rate: NL
gq-028 golden: NL
The golden SQL runs for 34 of 34 answerable questions, and 0 of them come back empty or with a NULL. Of the 7 questions with a check query, the check agrees with its gold in 7 of 7.
The two readings of the refund question disagree, the same trap as DABstep's task 49: by refunds the top country is US, and by refund rate it is NL. The golden question gq-028 says "highest refund rate" in its text, and its note defines the rate as refunded euros over gross revenue of the same orders. Without both, an agent that answered the other reading would be scored wrong for answering a question nobody wrote down.
The checks above find gold that is broken. Reading the agent's wrong answers finds gold that is unclear. gq-031 first asked about the average number of "items" in an order, and the schema-only baseline from chapter 1 got it wrong: its SQL averaged line_count, the number of order lines, where the gold sums units. "Items" allows both readings. The defect was in the question, not the agent, so the question now asks for units, counting quantities, not order lines. Recorded replies are keyed by the exact question text, so the reworded question needed a new recording. Replaying both wordings below shows the effect.
1"""Read a wrong answer: gq-031 once asked about "items", which allows units or order lines. It now asks for units.2The two `outcome` lines settle whether each wording's baseline answer is right against the gold printed first."""3from dataclasses import replace45from lib.golden import golden_result, load_golden, schema_only_outcome6from lib.model import RecordedModel7from lib.prompts import schema_only_messages8from lib.tools import extract_sql9from lib.warehouse import connect, describe_schema1011con = connect()12schema, model = describe_schema(con), RecordedModel("schema-only-sql")13q = next(q for q in load_golden() if q.question_id == "gq-031")14print(f"gq-031 golden: {golden_result(con, q)[0][0]}")15for wording, asked in [("items", replace(q, question="How many items did an order contain on average in 2025?")), # the old wording; the recording keys replies by question text16 ("units", q)]:17 sql = extract_sql(model.complete(schema_only_messages(schema, asked.question)))18 print(f"{wording} wording: {asked.question}")19 print(f"baseline answer, {wording} wording: {con.execute(sql).fetchall()[0][0]:.4f}")20 print(f"baseline outcome, {wording} wording: {schema_only_outcome(con, model, schema, asked)}")
python reworded-golden-question.pygq-031 golden: 3.4117
items wording: How many items did an order contain on average in 2025?
baseline answer, items wording: 2.5691
baseline outcome, items wording: wrong
units wording: How many units did an order contain on average in 2025, counting quantities, not order lines?
baseline answer, units wording: 3.4124
baseline outcome, units wording: correct
The units wording is right, though its query is still off. The items wording got 2.5691, wrong against a gold of 3.4117, and the units wording got 3.4124. The units query keeps cancelled orders and takes the year from the UTC timestamp, and on this data neither moves the average past the tolerance. That's the blind spot of an execution match: the answer is right, and the query isn't.
At a larger scale, a model can propose suspect golds for a person to check. The extended version of the CIDR audit describes an agent built for this, which flagged erroneous BIRD Mini-Dev examples with 83% precision (Jin et al., arXiv:2601.08778). A person still decides each one.
Working rule: Before a golden question scores anything, run its SQL, reject empty and NULL results, compare it with an independent query where you can, and have the definition's owner read its note. Read the agent's wrong answers for unclear questions, and fix the question, not the score. When a question can be read two ways, name the reading in its text, or make it a decline.
답만이 아니라 거절과 역할도 다룬다
검증된 정답집은 각 질문을 신뢰할 수 있게 만들지만, 세트 전체는 여전히 에이전트가 실제로 마주할 상황을 시험해야 한다. 답할 수 있는 질문만 있는 세트는 무엇이든 답하는 에이전트에게 보상을 준다. 추측해서 답해도 점수를 잃지 않기 때문이다. 그래서 이 가게의 세트에는 올바른 답이 거절인 질문도 포함하며, 올바른 행동이 다르므로 거절을 두 유형으로 나눈다. "우리의 최고 고객은 누구인가?"와 같은 모호한 질문은 합리적인 답이 여러 가지이므로, 에이전트는 어떤 선택이 필요한지 말해야 한다. 배송비와 같은 답할 수 없는 질문은 웨어하우스에 없는 데이터를 요구하므로, 에이전트는 그렇다고 말해야 한다. 금지된 질문은 답할 수는 있지만 질문하는 역할에게는 허용되지 않는다. 가게의 재무팀은 고객의 이메일을 볼 수 없고, 지역 책임자는 자기 지역만 볼 수 있다. 8장에서 거절을 구현하고 9장에서 접근 규칙을 구현한다. 이 장에서는 세트가 두 가지를 모두 채점할 수 있는지 확인한다.
커버리지는 웨어하우스의 함정과 가게의 역할도 포함한다. 테스트 주문부터 레거시 마트까지 가게의 웨어하우스에 만들어 둔 모든 함정은 두 분할 모두에 나타나야 한다. 그래야 한 함정을 깨뜨리는 변경이 어느 점수에서든 드러난다. 분할별로 유형, 역할, 함정을 세어 보면 세트가 어디에서 부족한지 알 수 있다.
1"""Count what the golden set covers in each split: kinds, roles and the warehouse's traps.2The prose's coverage point rests on the kind counts and on the last line, which names any trap missing from a split."""3from collections import Counter45from lib.golden import load_golden67questions = load_golden()8splits = ("dev", "test")9for split in splits:10 print(f"{split} questions: {sum(q.split == split for q in questions)}")11print("split answer decline forbidden")12for split in splits:13 kinds = Counter(q.kind for q in questions if q.split == split)14 print(f"{split:<5} {kinds['answer']:>6} {kinds['decline']:>7} {kinds['forbidden']:>9}")1516for split in splits:17 roles = Counter(q.role for q in questions if q.split == split and q.kind == "answer")18 print(f"{split} answers by role: {dict(sorted(roles.items()))}")1920traps = {split: Counter(t for q in questions if q.split == split for t in q.traps) for split in splits}21print("trap dev test")22for trap in sorted(traps["dev"] | traps["test"]):23 print(f"{trap:<20} {traps['dev'][trap]:>3} {traps['test'][trap]:>4}")24missing = sorted(t for t in traps["dev"] | traps["test"] if not traps["dev"][t] or not traps["test"][t]) # Counter gives 0 for an absent trap25print(f"traps missing from a split: {', '.join(missing) or 'none'}")
python golden-coverage.pydev questions: 24
test questions: 24
split answer decline forbidden
dev 17 4 3
test 17 4 3
dev answers by role: {'analyst': 15, 'finance': 1, 'regional_lead': 1}
test answers by role: {'analyst': 10, 'finance': 3, 'marketing': 2, 'regional_lead': 1, 'support': 1}
trap dev test
cancelled-orders 5 8
currency 2 3
definition 2 2
duplicate-customers 2 2
fan-out 2 2
fiscal-calendar 3 4
late-refunds 1 2
legacy-table 2 1
local-business-day 2 2
net-vs-gross 2 2
null-channel 1 1
role-scope 4 4
test-orders 5 4
vat 2 1
traps missing from a split: none
유형은 균형을 이룬다. 각 분할의 답변, 거절, 금지된 질문의 수가 같다. 모든 함정이 두 분할 모두에 나타나며, 마지막 줄은 traps missing from a split: none라고 출력한다. 테스트 분할의 VAT처럼 한 분할에서 여러 함정이 질문 하나에 걸려 있는 경우가 있으므로, 태그 하나가 빠지면 함정이 분할에서 사라질 수 있고 이 줄이 그 함정을 알려 준다.
역할은 균형을 이루지 않는다. dev 분할에서 답할 수 있는 질문은 분석가, 재무, 그리고 지역 책임자 한 명이 한다. 마케팅과 지원은 답할 수 있는 질문을 테스트 분할에서만 한다. 프롬프트와 컨텍스트는 dev에서 조정하므로, 에이전트가 답해야 하는 마케팅 질문을 조정 과정에서는 볼 수 없고, 그 질문이 처음 채점되는 시점은 따로 떼어 둔 세트에서다. 점수를 본 뒤에 질문을 분할 사이에서 옮기지 않고 불균형을 그대로 드러내 둔다. 이 두 역할을 위해 다음에 작성하는 질문은 dev로 보낸다.
작업 규칙: 처음부터 거절과 금지된 질문을 포함하고, 올바른 답이 다르므로 거절을 모호한 질문과 답할 수 없는 질문으로 나눈다. 각 질문에 그것이 시험하는 함정을 태그로 달고, 채점하기 전에 분할별로 유형, 역할, 함정을 센다. 빈틈은 새 질문을 작성해서 메우고, 에이전트가 기존 질문에서 어떤 결과를 냈는지 본 뒤에 그 질문을 분할 사이에서 옮겨서 메우지 않는다.
테스트 분할을 따로 떼어 두기
올바른 대상을 다루는 세트라도 사용하는 방식 때문에 오해를 일으킬 수 있다. 질문 하나가 실패해서 프롬프트를 바꿀 때마다 에이전트는 그 질문들에 조금씩 더 가깝게 맞춰진다. 변경이 충분히 쌓이면 그 질문들의 점수는 에이전트가 얼마나 잘 동작하는지가 아니라 얼마나 잘 튜닝했는지를 측정한다. 따로 떼어 둔 분할은 이에 대한 일반적인 방어책이다. 한 부분으로 튜닝하고, 다른 부분은 결과를 보고할 때만 채점한다. 벤치마크의 비공개 테스트 세트는 정답이 학습 데이터로 유출될 위험을 줄여 주지만(DABstep 논문), 사람들이 질문의 스타일에 맞춰 튜닝하는 것까지 막지는 못한다. 직접 만든 테스트 분할은 작업 방식으로 보호해야 한다.
이 상점의 세트에는 모든 장에서 튜닝에 사용할 수 있는 dev 질문이 24개 있고, 보고할 점수를 얻을 때만 채점하는 test 질문이 24개 있다. 1장의 스키마 전용 기준선을 두 분할 모두에서 채점하면, 이후 모든 장이 넘어서야 할 기준이 나온다.
1"""The baseline every later chapter must beat: schema-only SQL scored on the dev split and on the held-out test split.2The prose's split counts are the per-split lines, and its declines, forbidden and answer counts the last three lines."""3from collections import Counter45from lib.golden import load_golden, schema_only_outcome6from lib.model import RecordedModel7from lib.warehouse import connect, describe_schema89con = connect()10schema, model = describe_schema(con), RecordedModel("schema-only-sql")11outcomes = {"dev": Counter(), "test": Counter()}12by_kind = Counter()13for q in load_golden():14 outcome = schema_only_outcome(con, model, schema, q)15 outcomes[q.split][outcome] += 116 by_kind[q.kind, outcome == "correct"] += 1 # (kind, correct) pairs, counted over both splits1718for split, counts in outcomes.items():19 total = sum(counts.values())20 for outcome in ("correct", "wrong", "error", "declined"): # "error" when the SQL fails; grade() gives the rest21 print(f"{split} {outcome}: {counts[outcome]} of {total}")22 print(f"{split} accuracy: {counts['correct'] / total:.1%}")23for kind in ("answer", "decline", "forbidden"):24 print(f"{kind} correct, both splits: {by_kind[kind, True]} of {by_kind[kind, True] + by_kind[kind, False]}")
python baseline-on-both-splits.pydev correct: 2 of 24
dev wrong: 14 of 24
dev error: 8 of 24
dev declined: 0 of 24
dev accuracy: 8.3%
test correct: 3 of 24
test wrong: 13 of 24
test error: 8 of 24
test declined: 0 of 24
test accuracy: 12.5%
answer correct, both splits: 5 of 34
decline correct, both splits: 0 of 8
forbidden correct, both splits: 0 of 6
기준선은 판단이 필요한 부분에서 가장 약하다. 두 분할을 합치면 거절해야 하는 질문 중 0 of 8개, 금지된 질문 중 0 of 6개, 답할 수 있는 질문 중 5 of 34개를 맞힌다. 기준선은 SQL만 작성하므로 아무것도 거절하지 않는다.
dev 질문은 2 of 24개를 맞혀 정확도가 8.3%이고, test 질문은 3 of 24개를 맞혀 정확도가 12.5%이다. 나머지 질문은 모두 실패한다. 실행되지 않거나, 잘못된 결과를 내거나, 거절해야 할 질문에 답한다.
두 분할은 질문 하나만큼 차이가 나며, 아직 어느 쪽도 튜닝되지 않았다. 각 장이 dev에서 컨텍스트를 바꾸기 시작하면 두 점수는 벌어질 것이다. dev 점수는 오르는데 test 점수는 오르지 않는다면, 그 변경이 상점이 아니라 dev 질문에 맞춰졌다는 신호이다. 분할당 질문이 24개이므로 질문 하나는 정확도 약 4포인트에 해당한다. 따라서 한두 문제 차이는 잡음으로 보고, 두 총점을 비교하기보다 변경 전후에 같은 질문끼리 비교한다.
작업 규칙: 골든 질문은 무엇이든 튜닝하기 전에 한 번만 분할하고, 튜닝은 dev에서만 한다. test 분할은 결과를 보고할 때만 채점하며, 두 분할의 점수를 나란히 보고한다. 테스트 질문을 너무 자주 들여다보아 사람들이 그에 맞춰 튜닝하게 되었다면, 새 테스트 질문을 작성하고 기존 질문은 dev로 옮긴다.
운영 환경에서 잘못되는 것들
이 책에서는 상점의 48 골든 질문으로 에이전트를 측정한다. 실제 웨어하우스에서 같은 방식을 적용하면 다음과 같은 문제가 생기며, 각 문제에는 이를 알아차릴 방법이 있다.
정의가 바뀌면 골드가 낡는다. 재무팀이 순매출의 정의를 바꾸면 net_revenue_eur를 합산하는 모든 골든 쿼리가 실패하지 않은 채로 틀려 있을 수 있다. 골든 질문을 정의 및 지표와 함께 저장소에 두고, 변경을 함께 검토하며, 변경할 때마다 점검 쿼리를 다시 실행한다. 점검 쿼리의 결과가 더는 일치하지 않으면 그것이 경보다.
골든 결과는 데이터가 도착하면서 변한다. 환불은 주문 후 몇 달 동안 계속 들어오므로, 2026년 3월 주문에 대한 gq-018의 환불액은 환불 테이블이 적재될 때마다 늘어난다. 아직 마감되지 않은 기간에 대한 골든 질문은 매주 다른 골든 결과를 내며, 지난주의 결과를 저장해 두고 비교하면 아무 이유 없이 실패한다. golden_result()처럼 채점 시점에 골든 SQL로 골든 결과를 계산하고, 숫자가 고정되어야 하는 질문에는 마감된 기간을 우선 사용한다.
질문 집합이 사람들이 실제로 묻는 질문과 달라진다. 질문은 사업과 함께 바뀐다. 새로운 채널, 새로운 지역, 새로운 회계 정책이 생기기 때문이다. 한 번 작성한 집합은 이런 질문에서 점점 멀어진다. 사람들이 에이전트에게 묻는 질문에서 표본을 추출하고, 에이전트가 틀렸거나 답을 거절한 질문에 대해 골든 질문을 작성하여 dev에 추가한다.
테스트 분할이 유출된다. 누군가 실패한 테스트 질문을 읽고 프롬프트를 그 질문에 맞게 조정하면, 다른 것은 개선되지 않았는데 테스트 점수만 오른다. 한 질문을 겨냥한 변경 뒤에 dev 점수와 test 점수가 함께 움직이면 이를 알 수 있다. 테스트 질문은 튜닝 논의에서 제외하고, 유출되었다면 새로 교체한다.
벤치마크 점수는 벤치마크와 함께 움직인다. 벤더가 내세우는 BIRD나 Spider의 정확도는 관리자가 계속 수정하는 집합의 한 버전에 대한 수치이다. 모델을 비교할 때는 모든 점수에 벤치마크의 버전을 기록하고, 모델을 바꾸기 전에 자체 집합에서 다시 채점한다.
비교가 단위의 변경을 가린다. 매출을 천 유로 단위로 반환하기 시작한 에이전트는 금액 관련 질문을 한꺼번에 모두 틀리며, 허용 오차를 더 느슨하게 잡으면 이를 가릴 것이다. 허용 오차는 작은 상대 값으로 유지하고, 많은 질문이 함께 실패하면 비교 규칙을 건드리기 전에 답변 하나를 먼저 읽어 본다.
작업 규칙: 골든 집합을 코드처럼 다룬다. 정의 옆에 두고, CI에서 점검을 실행하며, 채점 시점에 골든 결과를 계산하고, 실제 트래픽의 질문을 dev에 추가하며, 테스트 분할을 보호한다. 점수가 움직이면 집합이나 비교 방식을 바꾸기 전에 달라진 답변부터 읽는다.
이 장에서 내린 결정
- 주된 평가 세트는 상점 자체의 것이다. 상점의 팀들이 하는 업무를 바탕으로 작성한 골든 질문이며, 역할, 종류, 정의를 갖추고
examples/data/golden/questions.toml에 있다. - 공개 벤치마크는 인용할 뿐 채점에는 쓰지 않는다. BIRD와 Spider 2.0은 인용으로만 등장한다. CC BY 4.0 라이선스이고 리비전으로 고정한 DABstep의 세 과제 부분집합은 공개 점수와 여러분의 웨어하우스에서의 점수가 서로 다르다는 점을 보여 준다.
- DABstep의 데이터는 라이선스와 함께 이동한다. 부분집합은 데이터셋 자체의
LICENSE를 유지하고, 식별자 열 네 개를 제거하며, 모든 행과 가맹점의 가상 이름을 그대로 두고,SOURCE.md가 각 변경 사항을 명시한다. - SQL 텍스트가 아니라 결과를 비교한다. 모든 채점에 함수 하나,
results_match()를 쓴다. 질문이 순서를 요구하지 않으면 행 순서는 무엇이든 상관없고, 열 이름과 순서는 무시하며, 추가 열은 허용하고, 숫자는 작은 상대 허용 오차에 정답의 반올림된 마지막 자리의 절반을 더한 범위 안에서 일치하면 된다. - 모든 정답은 채점에 쓰이기 전에 검증한다. 정답 쿼리는 실행되고, NULL 없이 행을 반환하며, 독립적인 쿼리가 있는 경우 그 결과와 일치한다. 정답의 비고에는 해당 정의가 명시된다.
- 거절 질문과 금지 질문도 세트에 포함한다. 거절 질문은 모호한 질문과 답할 수 없는 질문으로 나뉘고, 금지 질문은 상점의 여러 역할에 걸쳐 있다.
- 세트는 한 번만 동일한 크기의 dev와 test 절반으로 나눈다. 종류별 균형을 맞춘다. 각 장은 dev에서 조정하고, 보고하는 수치에 대해서만 test로 채점한다.
- 스키마만 사용하는 SQL이 기준선이다. 두 분할 모두에서 그러하며, 이후의 모든 장은 이 기준선에 대한 변화를 보고한다.
이 판의 이 장
2026.11.15판예제 통과 2026년 11월 19이 장에서 8개 예제개 중 8개가 통과한다
영어판 2026.11.15판을 번역한 것이다.