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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#!/usr/bin/env python3
"""Select a frozen DeepResearch frontier benchmark from a judged base pilot.

The pilot is intentionally separate from final checkpoint evaluation.  The
``frontier`` tier retains candidates where the pre-RL base model succeeds
sometimes but not always, with no one-search/no-open success.  The separate
``challenge`` tier retains clean base-model floor cases with zero successes.
Three-of-three ceiling questions and incomplete/error/blank pilots are removed.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import random
import statistics
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any

try:
    from .common import read_jsonl, write_jsonl
except ImportError:  # direct script execution
    from common import read_jsonl, write_jsonl


BENCHMARK_NAME = "deepresearch9k-frontier-v1"
DEFAULT_SEED = 20260810


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 row_qid(row: dict[str, Any]) -> str:
    return str(row.get("qid") or row.get("manifest_qid") or "")


def record_qid(record: dict[str, Any]) -> str:
    metadata = record.get("metadata") or {}
    return str(metadata.get("qid") or metadata.get("manifest_qid") or "")


def pilot_statistics(rows: list[dict[str, Any]]) -> dict[str, Any]:
    scores = [int(row.get("judge_score") or 0) for row in rows]
    turns = [int(row.get("num_turns") or 0) for row in rows]
    searches = [int((row.get("tool_stats") or {}).get("search", 0)) for row in rows]
    opens = [int((row.get("tool_stats") or {}).get("open_page", 0)) for row in rows]
    fast_successes = sum(
        score
        and (
            turn <= 2
            or (search_calls <= 1 and open_calls == 0)
        )
        for score, turn, search_calls, open_calls in zip(
            scores, turns, searches, opens, strict=True
        )
    )
    successful_turns = [turn for score, turn in zip(scores, turns, strict=True) if score]
    return {
        "replicas": len(rows),
        "successes": sum(scores),
        "success_rate": statistics.fmean(scores) if scores else None,
        "local_em_successes": sum(int(row.get("local_em") or 0) for row in rows),
        "fast_successes": fast_successes,
        "mean_turns": statistics.fmean(turns) if turns else None,
        "mean_searches": statistics.fmean(searches) if searches else None,
        "mean_opens": statistics.fmean(opens) if opens else None,
        "min_success_turns": min(successful_turns) if successful_turns else None,
        "blank_answers": sum(not str(row.get("predicted") or "").strip() for row in rows),
        "non_finish": sum(row.get("stop_reason") != "finish" for row in rows),
        "agent_errors": sum(bool(row.get("error")) for row in rows),
        "judge_errors": sum(bool(row.get("judge_error")) for row in rows),
        "unscored": sum(row.get("judge_score") is None for row in rows),
    }


def rejection_reason(
    stats: dict[str, Any],
    *,
    expected_replicas: int,
    min_successes: int,
    max_successes: int,
    max_fast_successes: int,
    min_mean_turns: float,
) -> str | None:
    if stats["replicas"] != expected_replicas:
        return "incomplete_replicas"
    if stats["agent_errors"] or stats["judge_errors"] or stats["unscored"]:
        return "pilot_error"
    if stats["non_finish"]:
        return "non_finish"
    if stats["blank_answers"]:
        return "blank_answer"
    if stats["successes"] < min_successes:
        return "too_hard"
    if stats["successes"] > max_successes:
        return "too_easy"
    if stats["fast_successes"] > max_fast_successes:
        return "one_step_success"
    if float(stats["mean_turns"] or 0.0) < min_mean_turns:
        return "too_few_turns"
    return None


def challenge_eligible(
    stats: dict[str, Any], *, expected_replicas: int, min_mean_turns: float
) -> bool:
    """Return whether a clean candidate is a genuine base-model floor case."""

    return bool(
        stats["replicas"] == expected_replicas
        and not stats["agent_errors"]
        and not stats["judge_errors"]
        and not stats["unscored"]
        and not stats["non_finish"]
        and not stats["blank_answers"]
        and stats["successes"] == 0
        and float(stats["mean_turns"] or 0.0) >= min_mean_turns
    )


def balanced_sample(
    rows: list[dict[str, Any]], *, count: int, rng: random.Random
) -> list[dict[str, Any]]:
    """Round-robin difficulty/teacher cells, then consume remaining supply."""

    groups: defaultdict[tuple[int, bool], list[dict[str, Any]]] = defaultdict(list)
    for row in rows:
        metadata = row["metadata"]
        groups[(int(metadata["difficulty"]), bool(metadata["teacher_correct"]))].append(row)
    for values in groups.values():
        rng.shuffle(values)
    keys = sorted(groups)
    rng.shuffle(keys)
    selected = []
    while len(selected) < count:
        made_progress = False
        for key in keys:
            if groups[key] and len(selected) < count:
                selected.append(groups[key].pop())
                made_progress = True
        if not made_progress:
            break
    if len(selected) < count:
        raise RuntimeError(f"requested {count} rows but only {len(selected)} are available")
    return selected


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--candidates", type=Path, required=True)
    parser.add_argument("--pilot-data", type=Path, required=True)
    parser.add_argument("--pilot-results", type=Path, required=True)
    parser.add_argument("--blocked-docids", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--hard-open", type=int, default=64)
    parser.add_argument("--reformulate", type=int, default=192)
    parser.add_argument("--challenge-hard-open", type=int, default=0)
    parser.add_argument("--challenge-reformulate", type=int, default=0)
    parser.add_argument("--min-successes", type=int, default=1)
    parser.add_argument("--max-successes", type=int)
    parser.add_argument("--max-fast-successes", type=int, default=0)
    parser.add_argument("--min-mean-turns", type=float, default=3.0)
    parser.add_argument("--seed", type=int, default=DEFAULT_SEED)
    args = parser.parse_args()
    if min(args.hard_open, args.reformulate, args.min_successes) < 1:
        parser.error("frontier selection quotas and min-successes must be positive")
    if min(args.challenge_hard_open, args.challenge_reformulate) < 0:
        parser.error("challenge selection quotas must be non-negative")

    candidates = list(read_jsonl(args.candidates))
    candidate_by_qid = {record_qid(row): row for row in candidates}
    if "" in candidate_by_qid or len(candidate_by_qid) != len(candidates):
        raise ValueError("candidate qids must be present and unique")
    pilot_data = list(read_jsonl(args.pilot_data))
    result_rows = list(read_jsonl(args.pilot_results))
    result_by_index = {int(row["index"]): row for row in result_rows}
    if len(result_by_index) != len(result_rows):
        raise ValueError("pilot results contain duplicate indexes")
    expected_indexes = set(range(len(pilot_data)))
    if set(result_by_index) != expected_indexes:
        missing = sorted(expected_indexes - set(result_by_index))
        extra = sorted(set(result_by_index) - expected_indexes)
        raise ValueError(f"pilot coverage mismatch: missing={missing} extra={extra}")

    grouped: defaultdict[str, list[dict[str, Any]]] = defaultdict(list)
    replicas_by_qid: defaultdict[str, set[int]] = defaultdict(set)
    for index, record in enumerate(pilot_data):
        qid = record_qid(record)
        result = result_by_index[index]
        if row_qid(result) != qid:
            raise ValueError(
                f"pilot qid mismatch at index={index}: expected={qid!r} actual={row_qid(result)!r}"
            )
        benchmark = (record.get("metadata") or {}).get("benchmark") or {}
        replica = int(benchmark["pilot_replica"])
        if replica in replicas_by_qid[qid]:
            raise ValueError(f"duplicate pilot replica for qid={qid}: {replica}")
        replicas_by_qid[qid].add(replica)
        grouped[qid].append(result)

    replica_counts = {len(replicas) for replicas in replicas_by_qid.values()}
    if len(replica_counts) != 1:
        raise ValueError(f"inconsistent pilot replica counts: {sorted(replica_counts)}")
    expected_replicas = next(iter(replica_counts))
    max_successes = (
        args.max_successes if args.max_successes is not None else expected_replicas - 1
    )
    if not args.min_successes <= max_successes < expected_replicas:
        parser.error("success range must retain some-but-not-all successful replicas")

    rejected = Counter()
    eligible_by_bucket: defaultdict[str, list[dict[str, Any]]] = defaultdict(list)
    challenge_by_bucket: defaultdict[str, list[dict[str, Any]]] = defaultdict(list)
    pilot_by_qid = {}
    audit_rows = []
    for qid, candidate in candidate_by_qid.items():
        stats = pilot_statistics(grouped.get(qid, []))
        pilot_by_qid[qid] = stats
        reason = rejection_reason(
            stats,
            expected_replicas=expected_replicas,
            min_successes=args.min_successes,
            max_successes=max_successes,
            max_fast_successes=args.max_fast_successes,
            min_mean_turns=args.min_mean_turns,
        )
        metadata = candidate["metadata"]
        bucket = metadata["benchmark"]["selection_bucket"]
        is_challenge = challenge_eligible(
            stats,
            expected_replicas=expected_replicas,
            min_mean_turns=args.min_mean_turns,
        )
        audit_rows.append(
            {
                "qid": qid,
                "selection_bucket": bucket,
                "difficulty": metadata.get("difficulty"),
                "teacher_correct": metadata.get("teacher_correct"),
                "eligible": reason is None,
                "challenge_eligible": is_challenge,
                "calibration_tier": (
                    "frontier" if reason is None else "challenge" if is_challenge else None
                ),
                "rejection_reason": reason,
                "base_pilot": stats,
            }
        )
        if reason:
            rejected[reason] += 1
            if is_challenge:
                challenge_by_bucket[bucket].append(candidate)
            continue
        eligible_by_bucket[bucket].append(candidate)

    quotas = {
        "hard_open": args.hard_open,
        "reformulate": args.reformulate,
    }
    challenge_quotas = {
        "hard_open": args.challenge_hard_open,
        "reformulate": args.challenge_reformulate,
    }
    missing = {
        f"frontier/{bucket}": quota - len(eligible_by_bucket[bucket])
        for bucket, quota in quotas.items()
        if len(eligible_by_bucket[bucket]) < quota
    }
    missing.update(
        {
            f"challenge/{bucket}": quota - len(challenge_by_bucket[bucket])
            for bucket, quota in challenge_quotas.items()
            if len(challenge_by_bucket[bucket]) < quota
        }
    )
    args.output_dir.mkdir(parents=True, exist_ok=True)
    audit_path = args.output_dir / "pilot_audit.jsonl"
    write_jsonl(audit_path, audit_rows)
    supply = {
        bucket: len(eligible_by_bucket[bucket])
        for bucket in sorted(set(quotas) | set(eligible_by_bucket))
    }
    challenge_supply = {
        bucket: len(challenge_by_bucket[bucket])
        for bucket in sorted(set(challenge_quotas) | set(challenge_by_bucket))
    }
    supply_summary = {
        "candidates": len(candidates),
        "pilot_replicas": expected_replicas,
        "eligible_by_selection_bucket": supply,
        "challenge_eligible_by_selection_bucket": challenge_supply,
        "requested_by_selection_bucket": quotas,
        "challenge_requested_by_selection_bucket": challenge_quotas,
        "missing_by_selection_bucket": missing,
        "rejected": dict(rejected.most_common()),
        "pilot_audit": str(audit_path),
        "pilot_audit_sha256": sha256(audit_path),
    }
    (args.output_dir / "pilot_supply.json").write_text(
        json.dumps(supply_summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )
    if missing:
        raise RuntimeError(
            "insufficient frontier candidates: "
            f"missing={missing} frontier_supply={supply} challenge_supply={challenge_supply}"
        )

    rng = random.Random(args.seed)
    selected = []
    for bucket, quota in quotas.items():
        rows = balanced_sample(eligible_by_bucket[bucket], count=quota, rng=rng)
        for row in rows:
            row["metadata"]["benchmark"]["calibration_tier"] = "frontier"
        selected.extend(rows)
    for bucket, quota in challenge_quotas.items():
        rows = balanced_sample(challenge_by_bucket[bucket], count=quota, rng=rng)
        for row in rows:
            row["metadata"]["benchmark"]["calibration_tier"] = "challenge"
        selected.extend(rows)
    rng.shuffle(selected)
    for index, row in enumerate(selected):
        qid = record_qid(row)
        benchmark = row["metadata"]["benchmark"]
        benchmark["name"] = BENCHMARK_NAME
        benchmark["index"] = index
        benchmark["base_pilot"] = pilot_by_qid[qid]

    questions_path = args.output_dir / "questions.jsonl"
    blocked_path = args.output_dir / "blocked_docids.txt"
    write_jsonl(questions_path, selected)
    blocked_path.write_text(args.blocked_docids.read_text(encoding="utf-8"), encoding="utf-8")

    by_cell = Counter(
        (
            row["metadata"]["benchmark"]["selection_bucket"],
            int(row["metadata"]["difficulty"]),
            bool(row["metadata"]["teacher_correct"]),
        )
        for row in selected
    )
    summary = {
        "benchmark": BENCHMARK_NAME,
        "seed": args.seed,
        "questions": len(selected),
        "source_candidates": str(args.candidates),
        "source_candidates_sha256": sha256(args.candidates),
        "pilot_data": str(args.pilot_data),
        "pilot_data_sha256": sha256(args.pilot_data),
        "pilot_results": str(args.pilot_results),
        "pilot_results_sha256": sha256(args.pilot_results),
        "pilot_replicas": expected_replicas,
        "success_range": [args.min_successes, max_successes],
        "max_fast_successes": args.max_fast_successes,
        "min_mean_turns": args.min_mean_turns,
        "pilot_audit": str(audit_path),
        "pilot_audit_sha256": sha256(audit_path),
        "eligible_by_selection_bucket": {
            bucket: len(rows) for bucket, rows in sorted(eligible_by_bucket.items())
        },
        "challenge_eligible_by_selection_bucket": {
            bucket: len(rows) for bucket, rows in sorted(challenge_by_bucket.items())
        },
        "by_calibration_tier": dict(
            sorted(
                Counter(
                    row["metadata"]["benchmark"]["calibration_tier"] for row in selected
                ).items()
            )
        ),
        "by_calibration_tier_and_selection_bucket": {
            f"{tier}/{bucket}": count
            for (tier, bucket), count in sorted(
                Counter(
                    (
                        row["metadata"]["benchmark"]["calibration_tier"],
                        row["metadata"]["benchmark"]["selection_bucket"],
                    )
                    for row in selected
                ).items()
            )
        },
        "by_selection_bucket": dict(
            sorted(Counter(row["metadata"]["benchmark"]["selection_bucket"] for row in selected).items())
        ),
        "by_cell": {
            f"{bucket}/D{difficulty}/teacher_{str(teacher).lower()}": count
            for (bucket, difficulty, teacher), count in sorted(by_cell.items())
        },
        "rejected": dict(rejected.most_common()),
        "questions_sha256": sha256(questions_path),
        "blocked_docids_sha256": sha256(blocked_path),
        "selection_note": (
            "Internal model-calibrated frontier set. Selection used repeated pre-RL base outputs; "
            "final scores must use fresh rollouts and are not a clean held-out benchmark estimate."
        ),
    }
    (args.output_dir / "summary.json").write_text(
        json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )
    print(json.dumps(summary, ensure_ascii=False, sort_keys=True))


if __name__ == "__main__":
    main()