自社の業務から正解付き質問を作る
読了まで約48 分分、9 節 節の 8 例 例。
この章を終えると、自社の業務で人々が尋ねる質問から、正解付き質問を書けるようになる。各質問には、正解の SQL、その質問をするロール、必要な回答の種類を添える。エージェントの結果は、SQL の文面ではなく正解の結果と比較できるようになる。正解そのものも、信頼する前に検査できるようになる。公開ベンチマークのスコアが、自社のウェアハウスのスコアではない理由も説明できるようになる。
第 1 章では、5 つの正解付き質問で 2 つの方式を採点したが、5 問ではスモークテストにしかならない。プロンプトを変更して 1 問が直る、あるいは壊れると、スコアは 5 分の 1 動く。1 問が直って別の 1 問が壊れる変更では、スコアはまったく動かない。あいまいな質問に対する辞退や、質問者のロールには見せてはならない質問に対する辞退を試すものも、この 5 問にはない。本書の以降の章は、いずれもエージェントの一部を変更し、その変更が役に立ったと主張する。その主張には、測定できるだけの大きさの質問集合が必要である。その集合は、ウェアハウスの落とし穴、ロール、辞退を網羅する質問を含み、どの変更の調整にも使わずに取り分けておく部分を持たなければならない。
第 2 章では、それぞれが 1 つの落とし穴を狙う質問を 11 問追加した。この章では、その 16 問をすべて残し、店舗の注文、返金、顧客に関する 48 件の正解付き質問まで集合を拡張する。エージェントは、その店舗の生成されたウェアハウスに問い合わせる。まず、自分で質問を書く理由から始める。公開ベンチマークは存在し、書くよりダウンロードするほうが安上がりだからである。
公開ベンチマークは自分のテストにならない
text-to-SQL やデータエージェントの公開ベンチマークは、質問、データベース、各質問の正解(gold)の答え、そして同じセットについて他者が報告したスコアを提供する。そのため、モデルどうしの比較には有用である。しかし、自分のウェアハウスでエージェントがどの程度の成績を出すかは、このベンチマークからは分からない。理由は二つある。第一に、ベンチマークの質問、データ、定義は他者のものであり、高いスコアはモデルが他者の仕事をこなせることを示すにすぎない。第二に、gold の答えは人が書いた主張であり、スコアは gold がどの程度の頻度で正しいかも測っている。
第二の理由は実測されている。CIDR 2026 で発表された監査では、専門家が各 gold クエリを質問とスキーマに照らして確認し、実行し、そのサブクエリも実行した。その結果、最初の 500 問版である BIRD Mini-Dev の 52.8% に、また gold SQL が公開されている Spider 2.0-Snow の 121 問のうち 66.1% に、アノテーションの誤りが見つかった。後者は spider2-snow-0713 ファイルに含まれる問題である(Jin et al., CIDR 2026)。最も多かった誤りは、データやスキーマを読み違えた gold SQL であった。著者らが BIRD Dev の 100 問を修正し、5 つのオープンソースエージェントを再実行したところ、スコアは相対値で −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 個のタスクがあり、答えが公開されているのは 10 個の dev タスクだけである(データセット)。本書のコピーは examples/data/dabstep/ にあり、DABstep の低いほうの難易度レベルにある 3 個の dev タスクと、138,236 件の取引からなる決済テーブル全体を含む。ただし、どのタスクにも不要な 4 つの識別子列、すなわちハッシュ化された IP アドレス、購入者のメールアドレス、カード番号、および各カードの銀行識別番号は除いてある。SOURCE.md には データセット の固定したリビジョンとすべての変更点を記し、LICENSE はデータセット自身の表示である。決済テーブルの加盟店は架空の事業者であり、その名前は公開されている DABstep のものである。lib/dabstep.py がこのテーブルを DuckDB に読み込む。
両方のセットに対して、第 1 章のスキーマのみの方式を、1 つのモデル Qwen3-4B-Instruct-2507 で実行する。応答は録画から再生する。モデルはテーブルのスキーマと質問を見て 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
2 つのセットは問う内容が異なるため、一方のスコアから他方のスコアは予測できず、差は要点ではない。スキーマのみの SQL は、DABstep の準完全一致を簡略化した方法で採点すると、DABstep のタスクでは 1 of 3 個、ショップの dev の質問では 2 of 24 個に正解する。DABstep のタスクは 1 つのテーブルに関するもので、会計カレンダーも、キャンセルされた注文も、レガシーのマートもない。ショップの質問は、まさにそれらの点でつまずく。
タスク 49 は、gold が何に依存するかを示している。このタスクは「不正」について上位の国を尋ね、その gold は BE である。不正取引の件数で数えると、上位の国は NL である。決済額に占める不正の割合で測ると、BE である。これを決めるのは DABstep のマニュアルであり、不正は「総額に対する不正額の比率」と定義されている(マニュアル)。質問文だけでは決まらない。タスク 49 では、モデルの SQL は実行に失敗したが、それでも国名を答えた。タスク 70 の gold は Not Applicable である。我々の読み方では、マニュアルには不正に関連する手数料の記述はあるが、罰金の記述はない。モデルは答えではなくクエリを返した。
実践ルール: 公開ベンチマークは、共通のタスクでモデルを比較するために使い、エージェントが自分のウェアハウスで動作する証拠としては決して使わない。gold セットは修正されるので、引用するスコアにはベンチマークのバージョンを添える。自分のエージェントは、自分の仕事から書いた、自分の定義による golden question で測定し、2 つのスコアが一致しないことを前提にする。
この部分はまだ翻訳されていないため、英語で表示している。
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.
順序、丸め、列名
結果の比較には、正しい二つの結果が食い違う場合についての規則がなお必要である。クエリが並べ替えを指定しない限り、行はどの順序で返ってもよい。列には書き手が選んだ名前が、任意の順序で付く。数値の丸め方も異なる。規則が厳しすぎると正しい答えが誤りと判定され、緩すぎると誤った答えが通ってしまう。
この本のすべてのスコアが用いる比較であるresults_match()は、次のように判断を下す。ゴールデンクエスチョンがorder_mattersを設定していない限り、行は任意の順序でよい。列名は無視され、列の順序も問われない。答えの列とゴールデンの列を対応づける方法をすべて試すためである。月ごとの合計の隣に月の列を置くような余分な列は許されるが、行数は等しくなければならない。数値は、既定ではゴールドと0.05% relativeの範囲で一致しなければならず、これに加えて、ゴールドが丸められている最終桁の半単位分の絶対的な許容幅が認められる。セント単位に丸められた金額であれば、これは0.5セントであり、既定値である。gq-002のゴールデンな結果、すなわち2026年3月の地域別の純売上を、実際の答えが異なる典型的な形に変え、それぞれを元の結果と比較すると、この比較がどの違いを許容するかが分かる。
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
行の逆順、列の入れ替え、月の列の追加はいずれも一致と判定される。ユーロ単位への丸めも同様であり、これは地域ごとの合計を高々0.5ユーロしか動かさない。千ユーロ単位への丸めは不一致となり、千ユーロ単位での報告も不一致となる。千単位という見出しの下にある小さな数値は、人間が読めば理解できるが、比較は見出しを見ることができない。これは意図的な設計である。単位を断りなく変えるエージェントは危険であるため、ゴールデンクエスチョンが単位を固定し、エージェントはそれに従わなければならない。地域が一つ欠けた場合も不一致となる。gq-039のような順位付けの問題ではorder_mattersが設定されているため、売上の順位を逆順にした地域の並びも不一致となる。
許容幅は、大きすぎても小さすぎても注意が要る。転換率のような比率は小さな数値であり、0.5セント分の許容幅は大きすぎる。gq-033の転換率は0.1156 to 0.1284にわたっており、0.005はそれぞれのおよそ4%にあたる。このゴールドは小数第4位に丸められており、絶対的な許容幅はその最終桁の半分、すなわち0.00005である。すべての率に0.004を加えた答えは、この尺度ではわずかなずれにすぎない。gq-033の規則では不一致となるが、0.5セントの許容幅であれば一致してしまう。この本の他の比率であるgq-031とgq-034も、同じ規則に従う。
実践ルール: 行の順序、列の順序、列名は無視し、余分な列は許容する。そのうえで、行数が同じであること、数値が小さな相対許容幅の範囲内にあることを要求する。各ゴールドは明示した桁に丸め、その桁の半単位をさらに許容する。order_mattersを設定するのは、問いが順位付けや系列を求めるときだけにする。単位と尺度は問いまたはその注記で固定し、別の単位による答えは誤りとして扱う。それを読む者には単位が分からないからである。
正解を信頼する前に検証する
公開ベンチマークは、検証されていない正解に何が起きるかを示している。あるデータセットでは、約半数の正解が誤っていた。午後のうちに書き上げた正解付きの質問も、事情は変わらない。その SQL はフィルタを取りこぼしているかもしれず、誤ったテーブルを読んでいるかもしれず、誰も管理していない定義に従っているかもしれない。そして、それを基に算出したスコアはすべて、その誤りを引き継ぐ。したがって、各正解は何かを採点する前に検証する。まず、実行できなければならない。次に、行を返さなければならず、NULL 値を含んでもならない。空の正解は、同じく何も返さないどのクエリとも一致してしまうからである。可能であれば、別の書き方で書いた 2 本目のクエリ、すなわちその正解の check_sql が、正解 SQL と同じ結果を返さなければならない。さらに、その注記は従っている定義を明示し、それが正しい定義かどうかを人が判断できるようにしておく。
このショップのデータセットにも、これらの検証を行う。各検証クエリは、正解 SQL とは独立に書く。たとえば、注文ではなく注文明細から集計する、会計カレンダーではなく日付範囲を使う、別の方法で数える、といった書き方である。そのうえで、ある 1 つの質問を 2 通りの読み方で見る。2026 会計年度に返金が最も多い国はどこか、という質問を、返金件数で見る場合と返金率で見る場合である。
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
正解 SQL は、回答可能な質問のうち 34 of 34 件で実行でき、そのうち 0 件は結果が空か NULL になる。検証クエリを持つ 7 件の質問のうち、検証クエリが正解と一致するのは 7 of 7 件である。
返金に関する質問の 2 通りの読み方は食い違う。これは DABstep のタスク 49 と同じ落とし穴である。返金件数で見ると首位の国は US であり、返金率で見ると NL である。正解付きの質問 gq-028 は、本文で「返金率が最も高い」と述べており、その注記は、返金率を同じ注文の総売上に対する返金額(ユーロ)の比と定義している。この両方がなければ、もう一方の読み方で答えたエージェントは、誰も書き留めていない質問に答えたとして不正解にされてしまう。
上記の検証が見つけるのは、壊れた正解である。エージェントの誤答を読むと、不明確な正解が見つかる。gq-031 は当初、注文 1 件あたりの「items」の平均数を尋ねていたが、第 1 章のスキーマのみのベースラインはこれを誤った。その SQL は注文明細の数である line_count を平均していたのに対し、正解は数量(units)を合計していたからである。「items」はどちらの読み方も許す。欠陥はエージェントではなく質問にあったため、質問は注文明細の数ではなく数量を数える units を求める文面に改めた。記録済みの応答は質問文そのものをキーにしているので、文面を変えた質問には新しい記録が必要だった。以下で両方の文面を再生すると、その効果がわかる。
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
units の文面は正しいが、そのクエリにはまだ誤りが残っている。items の文面は 2.5691 を返し、結果は wrong だった。正解は 3.4117 である。units の文面の結果は 3.4124 だった。units のクエリはキャンセル済みの注文を含めたままで、年も UTC のタイムスタンプから取っているが、このデータでは、どちらも平均値を許容範囲の外へ動かさない。これが実行一致の盲点である。答えは正しいが、クエリは正しくない。
より大規模な場面では、モデルに疑わしい正解の候補を挙げさせ、人が検証することもできる。CIDR の監査の拡張版には、この目的で作られたエージェントが記述されており、BIRD Mini-Dev の誤った例を 83% の適合率で検出した(Jin et al., arXiv:2601.08778)。それでも、各候補の最終判断は人が下す。
実践ルール: 正解付きの質問が何かを採点する前に、その SQL を実行し、空の結果と NULL を含む結果を退け、可能であれば独立したクエリと比較し、定義の管理者にその注記を読ませる。不明確な質問を見つけるために、エージェントの誤答を読み、スコアではなく質問を直す。質問が 2 通りに読めるときは、本文でどちらの読み方かを明示するか、回答を辞退すべき質問にする。
回答だけでなく、辞退とロールも網羅する
検査済みの正解データは個々の質問を信頼できるものにするが、評価セット全体は、エージェントが実際に出会うものを試すものでなければならない。回答可能な質問だけのセットは、すべてに答えようとするエージェントに有利に働く。推測しても減点されないからである。そこでショップのセットには、正しい答えが辞退である質問を含める。正しい振る舞いが異なるため、辞退は2種類に分ける。曖昧な質問、たとえば「最も優良な顧客は誰か」には、妥当な答えが複数ある。エージェントは、どの選択を必要としているかを述べるべきである。回答不能な質問、たとえば配送コストの質問は、ウェアハウスが保持していないデータを求めており、エージェントはそのことを述べるべきである。禁止された質問は、回答自体は可能だが、質問したロールには許されないものである。ショップの経理チームは顧客のメールアドレスを見ることができず、地域リードは自分の地域だけを見ることができる。第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がそうである。そのため、タグが1つ欠けるだけでトラップが分割から消えることになり、この行がそれを示す。
ロールは均衡していない。dev分割の回答可能な質問をするのは、アナリスト、経理、および地域リード1名である。マーケティングとサポートが回答可能な質問をするのは、テスト分割だけである。プロンプトとコンテキストはdevで調整するため、エージェントが答えるべきマーケティングの質問は、調整の過程で一度も目に入らない。それが初めて採点されるのは、ホールドアウトされたセットにおいてである。スコアを見た後で質問を分割間で移すことはせず、不均衡をそのまま見える状態にしておく。この2つのロール向けに次に書く質問は、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% である。それ以外の質問はすべて失敗する。実行できないか、誤った結果を返すか、拒否すべき質問に答えてしまう。
両分割の質問数は 1 問だけ異なり、どちらについてもまだ調整は行っていない。各章が dev でコンテキストを変更し始めると、両者は乖離していくと予想される。dev の得点が上がるのに test の得点が上がらない場合、その変更はショップではなく dev の質問に適合しているというシグナルである。分割ごとの質問数が 24 件であるため、1 問は正答率でおよそ 4 ポイントに当たる。したがって、1〜2 問の差はノイズとして扱い、2 つの合計を比べるのではなく、変更の前後で同じ質問どうしを比較する。
実践ルール: 評価用の質問は、何かを調整する前に一度だけ分割し、調整は dev でのみ行う。test 分割は結果を報告するときにだけ採点し、両方の分割を並べて報告する。test の質問が何度も参照され、それに合わせた調整が行われるようになったら、新しい test の質問を書き、古いものは dev に移す。
本番環境で何がうまくいかなくなるか
本書では、ショップの 48 件のゴールデンクエスチョンがエージェントを測定する。実際のウェアハウスで同じ手法を用いると、次のような形で失敗する。それぞれに、気づくための方法がある。
定義が変わると、ゴールドが古くなる。 財務部門が純売上の定義を変更すると、net_revenue_eur を合計するすべてのゴールデンクエリが、失敗しないまま誤りになる可能性がある。ゴールデンクエスチョンは、定義やメトリクスと同じリポジトリで管理し、変更を一緒にレビューし、変更のたびに検査クエリを再実行する。検査クエリの結果が一致しなくなることが警報となる。
ゴールデン結果は、データの到着に伴って動く。 返金は注文の後も数か月にわたって届き続ける。そのため、gq-018 における 2026 年 3 月の注文の返金額は、返金テーブルが読み込まれるたびに増える。未確定の期間を対象とするゴールデンクエスチョンでは、ゴールデン結果が週ごとに異なり、先週の結果を保存して比較する方式は理由もなく失敗する。ゴールデン結果は、golden_result() が行うように、採点時にゴールデン SQL から計算する。数値が変わってはならない質問には、確定済みの期間を選ぶことが望ましい。
問題集が、人々の実際の質問に似なくなる。 質問は、新しいチャネル、新しい地域、新しい会計方針など、事業とともに変わる。一度だけ書いた問題集は、実際の質問から乖離していく。人々がエージェントに尋ねた質問からサンプルを抽出し、エージェントが誤答した質問や回答を拒んだ質問についてゴールデンクエスチョンを書き、dev に追加する。
テスト分割が漏洩する。 誰かが失敗したテスト質問を読み、それに合わせてプロンプトを調整すると、ほかには何も改善していないのにテストスコアが上がる。特定の質問を狙った変更の後に dev とテストのスコアが連動して動くことで、漏洩に気づける。テスト質問は調整の議論から切り離し、漏洩した場合は入れ替える。
ベンチマークのスコアは、ベンチマークとともに動く。 ベンダーが示す BIRD や Spider での精度は、保守者が修正を重ねるデータセットの、ある一つのバージョンについての値である。モデルを比較するときは、すべてのスコアにベンチマークのバージョンを記録し、切り替える前に自分たちの問題集で再採点する。
比較が単位の変更を隠す。 売上を千ユーロ単位で返し始めたエージェントは、金額に関するすべての質問で一度に失敗する。許容誤差を緩めると、これが隠れてしまう。許容誤差は小さな相対値にとどめ、多くの質問が同時に失敗したときは、ルールに手を加える前に回答を一つ読む。
実践ルール: ゴールデンセットはコードとして扱う。定義の隣に置き、検査を CI で実行し、ゴールデン結果は採点時に計算し、実際のトラフィックから得た質問を dev に追加し、テスト分割を保護する。スコアが動いたときは、問題集や比較方法を変更する前に、変化した回答を読む。
この章で下した決定
- 主たる評価セットは店舗自身のものである。 店舗のチームが行う業務から作成したゴールデン質問であり、ロール、種類、定義を備え、
examples/data/golden/questions.tomlに置く。 - 公開ベンチマークは引用にとどめ、採点には用いない。 BIRD と Spider 2.0 は引用としてのみ登場する。CC BY 4.0 のもとにあり、リビジョンで固定した DABstep の 3 タスクのサブセットによって、公開スコアと自社のウェアハウスでのスコアが一致しないことを示す。
- DABstep のデータはライセンスとともに配布する。 サブセットはデータセット自身の
LICENSEを保持し、4 つの識別子列を削除し、すべての行と加盟店の架空の名称を残す。各変更はSOURCE.mdに記載する。 - 比較するのは SQL の文面ではなく結果である。 すべての採点に 1 つの関数
results_match()を用いる。質問が順序を求めない限り行の順序は問わず、列名と列の順序は無視し、余分な列は許容し、数値は小さな相対許容誤差に、正解値の丸めた最下位桁の 0.5 単位を加えた範囲内で一致すればよい。 - すべての正解は、採点に使う前に検証する。 正解クエリは実行でき、NULL を含まない行を返し、独立したクエリが存在する場合はそれと一致する。注記にはその定義を明記する。
- 辞退する質問と禁止された質問もセットに含める。 辞退は曖昧なものと回答不能なものに分け、禁止された質問は店舗のロール全体にわたって用意する。
- セットは一度だけ、種類の釣り合いをとって、同数の dev と test に分割する。 各章は dev で調整を行い、報告する数値に限って test で採点する。
- スキーマのみを用いる SQL をベースラインとする。 両方の分割でこれを基準とし、以降の各章はこれに対する変化を報告する。
この版における本章
第2026.11.15版2026年11月19日時点で例が通過この章の8 例件のうち8件が合格
英語版の書籍(版2026.11.15)から翻訳した。