File size: 13,063 Bytes
f45837e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
#!/usr/bin/env python3
"""Emit a K-source / M-eval split manifest, with the leakage guards intact.

    python3 make_split.py --k 10 --m 10 --out splits/scale_10_10.json
    RUBRIC_GEN_SPLIT=splits/scale_10_10.json python3 collect_targeted.py ...

WHY THIS EXISTS. The frozen manifest is 5 source / 15 eval
(`splits/error_side_5_15.json`, revision 4, frozen 2026-08-05). Scaling the
mining side to K competitions means K-5 competitions must come from somewhere,
and there are exactly two places:

  (a) MOVE them out of the evaluation set. Cheap, local, and it INVALIDATES
      every previously reported eval number that used them -- v5, v6, v7,
      gated1, and the precision/recall results all evaluated on those 15. A
      competition that becomes a mining source can never again be eval, so the
      old and new numbers are not comparable on the moved competitions.
  (b) PREPARE new competitions from MLE-bench. No contamination, but each needs
      Kaggle rules accepted by hand on kaggle.com and tens of GB downloaded.
      The frozen manifest already records four candidates blocked on exactly
      this (`replacement_candidates_unavailable_without_manual_rules_accepted`).

This script supports BOTH, and makes the cost of (a) explicit rather than silent:
it refuses to run without `--acknowledge-invalidates`, records which competitions
moved, and writes the list of prior result files whose eval set is no longer clean.

The intended combination is `--k 10 --add-eval <5 new ids>`: promote 5 out of eval
into the mining set, and backfill eval with 5 newly prepared competitions so the
evaluation set keeps its size and statistical power. `--add-eval` cannot do the
downloading -- Kaggle rules acceptance is manual and per-competition -- so it
instead REFUSES any id whose prepared data is not actually on disk, with the exact
command needed to fix it.

WHAT IT WILL NOT DO. Move a competition into eval that has ever been mined.
That direction is unrecoverable contamination: rubrics derived from a program
would be scored against that same competition. `--strict` on the reader side
still refuses an unfrozen manifest, so a thaw cannot pass unnoticed.
"""

from __future__ import annotations

import argparse
import json
import os
import time
from pathlib import Path

HERE = Path(__file__).resolve().parent
FROZEN = HERE / "splits" / "error_side_5_15.json"


def _gcs_prepared_gb(cid: str, bucket: str) -> float | None:
    """Compressed-tarball size in GB of a fleet-prepared competition, or None."""
    from google.cloud import storage  # only reached with --gcs-bucket

    b = storage.Client(project=os.environ.get("GOOGLE_CLOUD_PROJECT",
                                              "edward-sun")).bucket(bucket)
    tar = b.get_blob(f"data/{cid}/prepared.tar.gz")
    if tar is None or not tar.size or b.get_blob(f"data/{cid}/meta.json") is None:
        return None
    return tar.size / 1e9


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--k", type=int, required=True, help="source (minable) competitions")
    ap.add_argument("--m", type=int, default=0,
                    help="evaluation competitions (default: all remaining)")
    ap.add_argument("--base", default=str(FROZEN))
    ap.add_argument("--out", required=True)
    ap.add_argument("--acknowledge-invalidates", action="store_true",
                    help="required: confirms that moving eval -> source voids "
                         "prior eval numbers on the moved competitions")
    ap.add_argument("--prefer-tier", default="low,medium,high",
                    help="order in which to promote eval competitions to source")
    ap.add_argument("--promote", default="",
                    help="comma-separated eval competition ids to promote to "
                         "source, overriding smallest-first. For DIRECTED "
                         "scaling: recall's domain gaps (audio, DICOM, "
                         "segmentation) are closed by promoting comps FROM "
                         "those domains, which smallest-first never picks.")
    ap.add_argument("--add-eval", default="",
                    help="comma-separated NEW competition ids to add to the "
                         "evaluation set, replacing the ones promoted to source "
                         "so eval keeps its size and statistical power")
    ap.add_argument("--data-dir", default="",
                    help="where prepared competition data lives; --add-eval ids "
                         "are refused unless their data is actually present")
    ap.add_argument("--gcs-bucket", default="",
                    help="fleet bucket (e.g. edward-sun-agent-cwm-evals): an "
                         "--add-eval id with no local data is accepted if "
                         "data/<id>/prepared.tar.gz and meta.json exist there. "
                         "The empty-shell hazard the local check guards against "
                         "cannot occur in the bucket: the prep job refuses to "
                         "upload a tarball whose prepared/public is empty.")
    args = ap.parse_args()

    base = json.loads(Path(args.base).read_text())
    src = list(base["source_competitions"])
    ev = list(base["evaluation_competitions"])
    if args.k < len(src):
        raise SystemExit(f"--k {args.k} is below the frozen source count "
                         f"{len(src)}; shrinking the source set is not supported "
                         f"(the extra rubrics already exist)")
    need = args.k - len(src)
    if need > len(ev):
        raise SystemExit(f"need {need} more source competitions but only "
                         f"{len(ev)} eval competitions exist. Preparing new "
                         f"competitions requires manual Kaggle rules acceptance; "
                         f"see this file's docstring.")
    if need and not args.acknowledge_invalidates:
        raise SystemExit(
            f"promoting {need} eval competitions to source will invalidate every\n"
            f"previously reported eval number on them (v5/v6/v7/gated1 and the\n"
            f"precision-recall runs all used the 15-competition eval set).\n"
            f"Re-run with --acknowledge-invalidates if that is intended.")

    # Promote smallest-dataset-first within the requested tier order: mining
    # cost scales with dataset size, and the eval set should keep the large,
    # expensive competitions where a single run is most informative.
    order = {t: i for i, t in enumerate(args.prefer_tier.split(","))}
    ev_sorted = sorted(ev, key=lambda c: (order.get(c.get("tier"), 9),
                                          c.get("dataset_size_gb", 0)))
    if args.promote:
        want = [x.strip() for x in args.promote.split(",") if x.strip()]
        by_id = {c["id"]: c for c in ev}
        missing = [w for w in want if w not in by_id]
        if missing:
            raise SystemExit(f"--promote ids not in the eval set: {missing}")
        if len(want) != need:
            raise SystemExit(f"--promote lists {len(want)} ids but --k "
                             f"{args.k} needs {need} promotions")
        promoted = [by_id[w] for w in want]
    else:
        promoted = ev_sorted[:need]
    remaining = [c for c in ev if c["id"] not in {p["id"] for p in promoted}]
    if args.m:
        if args.m > len(remaining):
            raise SystemExit(f"--m {args.m} exceeds the {len(remaining)} "
                             f"competitions left after promoting {need}. "
                             f"K + M cannot exceed {len(src) + len(ev)} without "
                             f"preparing new competitions.")
        remaining = remaining[: args.m]

    # --add-eval: replace what was promoted so eval does not shrink. Each new id
    # must have REAL prepared data. Measured reason for the guard: the local tree
    # contains a `detecting-insults-in-social-commentary` directory with
    # prepared/public and prepared/private present and ZERO files inside -- an
    # empty shell that would pass any existence check on the directory alone and
    # then fail at grading time, deep inside a fleet run.
    added = []
    if args.add_eval:
        import os as _os
        data = Path(args.data_dir or _os.environ.get("MLEBENCH_DATA_DIR")
                    or (HERE.parent / ".mlebench" / "data"))
        known = {c["id"] for c in src} | {c["id"] for c in ev}
        excluded = set(base.get("development_competitions_excluded") or [])
        for cid in [x.strip() for x in args.add_eval.split(",") if x.strip()]:
            if cid in known:
                raise SystemExit(f"--add-eval {cid} is already in the split")
            if cid in excluded:
                raise SystemExit(
                    f"--add-eval {cid} is in the frozen manifest's excluded "
                    f"list (documented preparation or rules defect); pick "
                    f"another competition")
            prep = data / cid / "prepared"
            files = sum(1 for _ in prep.rglob("*") if _.is_file()) if prep.exists() else 0
            if files == 0 and args.gcs_bucket:
                gb = _gcs_prepared_gb(cid, args.gcs_bucket)
                if gb is None:
                    raise SystemExit(
                        f"--add-eval {cid}: no local prepared data and no "
                        f"data/{cid}/prepared.tar.gz + meta.json in "
                        f"gs://{args.gcs_bucket}")
                added.append({"id": cid, "tier": "unknown", "category": "unknown",
                              "dataset_size_gb": round(gb, 2),
                              "prepared": f"gs://{args.gcs_bucket}/data/{cid}/"
                                          f"prepared.tar.gz",
                              "size_is_compressed_tarball": True})
                continue
            if files == 0:
                raise SystemExit(
                    f"--add-eval {cid}: no prepared data under {prep} "
                    f"({files} files). Prepare it first:\n"
                    f"  accept the competition rules on kaggle.com, then\n"
                    f"  mlebench prepare -c {cid} --data-dir {data}\n"
                    f"or, if the fleet already prepared it, pass --gcs-bucket.")
            if not (prep / "private").exists():
                raise SystemExit(f"--add-eval {cid}: prepared/private missing, "
                                 f"so it could never be graded")
            added.append({"id": cid, "tier": "unknown", "category": "unknown",
                          "dataset_size_gb": round(
                              sum(f.stat().st_size for f in prep.rglob("*")
                                  if f.is_file()) / 1e9, 2)})
        remaining = remaining + added
        print(f"added to eval: {[c['id'] for c in added]}")

    new_src = src + promoted
    ids_s = {c["id"] for c in new_src}
    ids_e = {c["id"] for c in remaining}
    overlap = ids_s & ids_e
    if overlap:
        raise SystemExit(f"source/eval overlap, refusing to write: {overlap}")

    out = {
        "experiment_id": f"scale-{len(new_src)}-{len(remaining)}",
        "frozen": True,
        "frozen_at_utc": time.strftime("%Y-%m-%d", time.gmtime()),
        "revision": int(base.get("revision", 0)) + 1,
        "revision_reason":
            f"Scaled the mining side from {len(src)} to {len(new_src)} source "
            f"competitions by promoting {[c['id'] for c in promoted]} out of the "
            f"evaluation set. Promotion order: smallest dataset first within "
            f"tier order {args.prefer_tier}. No new competitions were downloaded.",
        "derived_from": str(Path(args.base).name),
        "promoted_eval_to_source": [c["id"] for c in promoted],
        "added_to_eval": [c["id"] for c in added],
        "invalidates_prior_eval_on": [c["id"] for c in promoted],
        "benchmark": base.get("benchmark"),
        "selection": base.get("selection"),
        "source_competitions": new_src,
        "evaluation_competitions": remaining,
        "source_dataset_size_gb_total": round(
            sum(c.get("dataset_size_gb", 0) for c in new_src), 2),
        "evaluation_dataset_size_gb_total": round(
            sum(c.get("dataset_size_gb", 0) for c in remaining), 2),
    }
    p = Path(args.out)
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(json.dumps(out, indent=2) + "\n")

    print(f"source ({len(new_src)}): {[c['id'] for c in new_src]}")
    print(f"eval   ({len(remaining)}): {[c['id'] for c in remaining]}")
    if promoted:
        print(f"\nPROMOTED eval -> source: {[c['id'] for c in promoted]}")
        print("  prior eval numbers on these are now void:")
        print("    data/gke_runs/{v5A,v5B,v6,v7,gated1}.jsonl "
              "and results/*pr_results*.json")
    print(f"\n-> {p}")
    print(f"use with: RUBRIC_GEN_SPLIT={p} python3 collect_targeted.py ...")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())