#!/usr/bin/env python3 """Build a deterministic, evidence-conditioned DeepResearch medium benchmark. Selection never uses model outputs. Every selected question has at least one successfully fetched, non-QA-dump teacher-provenance document containing the normalized gold answer. Questions are stratified by dataset difficulty, teacher outcome, and how much work an independent original-query search needs to surface the answer after QA-dump documents are blocked. The independently retrieved evidence URL need not be the exact URL used by the teacher: exact- content deduplication deliberately retains only one representative URL in FTS. """ from __future__ import annotations import argparse import hashlib import json import random import re import unicodedata from collections import Counter, defaultdict from functools import lru_cache from pathlib import Path from typing import Any from urllib.parse import urlsplit try: from .common import read_jsonl, write_jsonl from .corpus_db import connect, open_document, search except ImportError: # direct script execution from common import read_jsonl, write_jsonl from corpus_db import connect, open_document, search BENCHMARK_NAME = "deepresearch9k-medium-v1" DEFAULT_SEED = 20260809 AGENT_VISIBLE_K = 12 # Exact quotas keyed by (difficulty, teacher_correct, retrieval bucket). The # source has only five D2/teacher-failure questions whose answer is absent from # the original-query top 20 before stricter filtering, so forcing every cell # to be 50/50 is impossible. These quotas retain exact global 128/128 teacher # balance and the desired difficulty/bucket marginals without oversampling a # nonexistent cell. CELL_QUOTAS = { (1, False, "visible"): 24, (1, True, "visible"): 8, (1, False, "open"): 22, (1, True, "open"): 6, (1, False, "reformulate"): 2, (1, True, "reformulate"): 2, (2, False, "visible"): 20, (2, True, "visible"): 36, (2, False, "open"): 18, (2, True, "open"): 46, (2, False, "reformulate"): 2, (2, True, "reformulate"): 6, (3, False, "visible"): 4, (3, True, "visible"): 4, (3, False, "open"): 12, (3, True, "open"): 8, (3, False, "reformulate"): 24, (3, True, "reformulate"): 12, } SUSPICIOUS_URL_MARKERS = ( "huggingface.co/datasets", "honestybench", "halueval", "qapairs", "musique", "hotpotqa", "hotpot_qa", "triviaqa", "natural_questions", "strategyqa", "2wikimultihopqa", ) SHORT_COMMON_ANSWERS = { "earth", "false", "home", "magazine", "no", "plants", "rock", "true", "yes", } def normalize(text: str) -> str: decomposed = unicodedata.normalize("NFKD", text or "") without_marks = "".join( character for character in decomposed if not unicodedata.combining(character) ) return re.sub(r"[^\w]+", " ", without_marks.casefold(), flags=re.UNICODE).strip() def contains_answer(text: str, normalized_answer: str) -> bool: return f" {normalized_answer} " in f" {normalize(text)} " def answer_is_usable(answer: str) -> bool: normalized = normalize(answer) compact = normalized.replace(" ", "") if not normalized or normalized in SHORT_COMMON_ANSWERS or "" in answer: return False if len(compact) < 4 or len(answer) > 120: return False # Very short single alphabetic tokens are especially prone to incidental # matches in long pages. Four-digit years remain useful. if " " not in normalized and normalized.isalpha() and len(normalized) < 6: return False return True def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def url_is_suspicious(url: str) -> bool: lowered = url.casefold() if any(marker in lowered for marker in SUSPICIOUS_URL_MARKERS): return True path = urlsplit(lowered).path return path.endswith((".jsonl", ".parquet")) def find_blocked_documents(connection) -> tuple[set[str], list[dict[str, str]]]: blocked: set[str] = set() details = [] for row in connection.execute( "SELECT url_id, canonical_url, title, text FROM documents WHERE status='success'" ): reason = None if url_is_suspicious(row["canonical_url"]): reason = "url_marker" else: lowered = row["text"].casefold() question_fields = lowered.count('"question"') + lowered.count('"question":') answer_fields = lowered.count('"answer"') + lowered.count('"answer":') if question_fields >= 5 and answer_fields >= 5: reason = "repeated_structured_qa" if reason: blocked.add(row["url_id"]) details.append( { "docid": row["url_id"], "url": row["canonical_url"], "title": row["title"], "reason": reason, } ) return blocked, details def load_provenance(connection) -> dict[str, list[str]]: result: defaultdict[str, list[str]] = defaultdict(list) for row in connection.execute( """ SELECT q.qid, d.url_id FROM document_qids AS q JOIN documents AS d USING(url_id) WHERE d.status='success' """ ): result[row["qid"]].append(row["url_id"]) return dict(result) def target_cells() -> dict[tuple[int, bool, str], int]: return dict(CELL_QUOTAS) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--database", type=Path, required=True) parser.add_argument( "--database-label", type=Path, help="persistent source path recorded when --database is a staged copy", ) parser.add_argument("--data", type=Path, required=True) parser.add_argument("--coverage", type=Path, required=True) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--seed", type=int, default=DEFAULT_SEED) args = parser.parse_args() records = read_jsonl(args.data) coverage = {row["qid"]: row for row in read_jsonl(args.coverage)} connection = connect(args.database, readonly=True) blocked_docids, blocked_details = find_blocked_documents(connection) provenance = load_provenance(connection) @lru_cache(maxsize=32768) def document(docid: str) -> dict[str, Any] | None: return open_document(connection, docid=docid) candidates = [] rejected = Counter() for record in records: metadata = record.get("metadata") or {} qid = metadata.get("manifest_qid") or metadata.get("qid") audit = coverage.get(qid) answer = metadata.get("answer") or record.get("label", "") if audit is None or not audit.get("answer_in_fetched_provenance"): rejected["audit_no_provenance_answer"] += 1 continue if not answer_is_usable(answer): rejected["unusable_answer"] += 1 continue candidates.append(record) rng = random.Random(args.seed) rng.shuffle(candidates) coarse_base_counts = Counter( (int(record["metadata"]["difficulty"]), bool(record["metadata"]["teacher_correct"])) for record in candidates ) # Stable sort after shuffling: prioritize rare strata while preserving a # seeded random order within each stratum. This changes no eligibility or # quota; it avoids thousands of unnecessary FTS queries while waiting for # a rare D2/teacher-failure row to appear in a global random stream. candidates.sort( key=lambda record: coarse_base_counts[ ( int(record["metadata"]["difficulty"]), bool(record["metadata"]["teacher_correct"]), ) ] ) quotas = target_cells() selected_by_cell: defaultdict[tuple[int, bool, str], list[dict[str, Any]]] = defaultdict(list) scanned = 0 for record in candidates: if all(len(selected_by_cell[cell]) >= quota for cell, quota in quotas.items()): break scanned += 1 metadata = record["metadata"] qid = metadata.get("manifest_qid") or metadata["qid"] audit = coverage[qid] difficulty = int(metadata["difficulty"]) teacher_correct = bool(metadata["teacher_correct"]) base_cells = [ (difficulty, teacher_correct, bucket) for bucket in ("visible", "open", "reformulate") ] if all(len(selected_by_cell[cell]) >= quotas[cell] for cell in base_cells): rejected[f"base_quota_full:{difficulty}/{teacher_correct}"] += 1 continue # The earlier audit used a superset of this benchmark's visible # results (top 20, before blocking QA dumps). A miss there is # guaranteed to remain a reformulation case here and need not repeat # an expensive FTS query. audit_retrieval_miss = not bool(audit["answer_in_question_search_top_20"]) reformulate_cell = (difficulty, teacher_correct, "reformulate") if ( audit_retrieval_miss and len(selected_by_cell[reformulate_cell]) >= quotas[reformulate_cell] ): rejected[f"reformulate_quota_full:{difficulty}/{teacher_correct}"] += 1 continue answer = metadata.get("answer") or record.get("label", "") normalized_answer = normalize(answer) clean_provenance_hits = [] for docid in provenance.get(qid, []): if docid in blocked_docids: continue page = document(docid) if page and contains_answer(page["text"], normalized_answer): clean_provenance_hits.append(docid) if not clean_provenance_hits: rejected["no_clean_provenance_answer"] += 1 continue if audit_retrieval_miss: bucket = "reformulate" evidence_rank, evidence_row = None, None else: try: visible = search( connection, metadata["question"], AGENT_VISIBLE_K, excluded_docids=blocked_docids, ) except ValueError: rejected["unsearchable_question"] += 1 continue snippet_matches = [ (rank, row) for rank, row in enumerate(visible, 1) if contains_answer(row["text"], normalized_answer) ] full_matches = [] if not snippet_matches: for rank, row in enumerate(visible, 1): page = document(row["docid"]) if page and contains_answer(page["text"], normalized_answer): full_matches.append((rank, row)) if snippet_matches: bucket = "visible" evidence_rank, evidence_row = snippet_matches[0] elif full_matches: bucket = "open" evidence_rank, evidence_row = full_matches[0] else: bucket = "reformulate" evidence_rank, evidence_row = None, None cell = (int(metadata["difficulty"]), bool(metadata["teacher_correct"]), bucket) if cell not in quotas or len(selected_by_cell[cell]) >= quotas[cell]: rejected[f"quota_full:{cell}"] += 1 continue enriched = json.loads(json.dumps(record, ensure_ascii=False)) enriched["metadata"]["benchmark"] = { "name": BENCHMARK_NAME, "selection_bucket": bucket, "clean_provenance_answer_docids": sorted(clean_provenance_hits), "original_query_evidence_rank": evidence_rank, "original_query_evidence_docid": evidence_row["docid"] if evidence_row else None, } selected_by_cell[cell].append(enriched) if len(selected_by_cell[cell]) == quotas[cell] or scanned % 100 == 0: print( f"scanned={scanned} selected={sum(map(len, selected_by_cell.values()))} " f"filled={sum(len(selected_by_cell[c]) >= q for c, q in quotas.items())}/{len(quotas)}", flush=True, ) missing = { str(cell): quota - len(selected_by_cell[cell]) for cell, quota in quotas.items() if len(selected_by_cell[cell]) < quota } if missing: raise RuntimeError(f"could not fill benchmark quotas after scanning {scanned}: {missing}") selected = [row for cell in sorted(selected_by_cell, key=str) for row in selected_by_cell[cell]] rng.shuffle(selected) for index, row in enumerate(selected): row["metadata"]["benchmark"]["index"] = index args.output_dir.mkdir(parents=True, exist_ok=True) questions_path = args.output_dir / "questions.jsonl" blocked_docids_path = args.output_dir / "blocked_docids.txt" write_jsonl(questions_path, selected) write_jsonl(args.output_dir / "blocked_documents.jsonl", blocked_details) blocked_docids_path.write_text( "".join(f"{docid}\n" for docid in sorted(blocked_docids)) ) by_difficulty = Counter(row["metadata"]["difficulty"] for row in selected) by_teacher = Counter(str(row["metadata"]["teacher_correct"]).lower() for row in selected) by_bucket = Counter( row["metadata"]["benchmark"]["selection_bucket"] for row in selected ) summary = { "benchmark": BENCHMARK_NAME, "seed": args.seed, "questions": len(selected), "source_data": str(args.data), "source_coverage": str(args.coverage), "database": str(args.database_label or args.database), "database_sha256": sha256(args.database), "questions_sha256": sha256(questions_path), "blocked_docids_sha256": sha256(blocked_docids_path), "search_k": AGENT_VISIBLE_K, "agent_visible_k": AGENT_VISIBLE_K, "blocked_documents": len(blocked_docids), "candidates_after_coarse_filter": len(candidates), "coarse_candidates_by_difficulty_teacher": { f"D{difficulty}/teacher_{str(teacher).lower()}": count for (difficulty, teacher), count in sorted(coarse_base_counts.items()) }, "candidates_scanned": scanned, "by_difficulty": dict(sorted(by_difficulty.items())), "by_teacher_correct": dict(sorted(by_teacher.items())), "by_selection_bucket": dict(sorted(by_bucket.items())), "rejected": dict(rejected.most_common()), "selection_note": ( "Evidence-conditioned diagnostic; model outputs were not used for selection. " "Not a clean held-out estimate because train questions and train-trajectory provenance are allowed." ), } (args.output_dir / "summary.json").write_text( json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n" ) connection.close() print(json.dumps(summary, ensure_ascii=False, sort_keys=True)) if __name__ == "__main__": main()