FWeindel commited on
Commit
73df429
·
verified ·
1 Parent(s): a100977

fineenvs_v1: validation run 2026-10-20-fineenvs_v1-36fc78e213a3

Browse files

### Reproducibility and retries

| Stage | Mode | Tasks with expectation | Matched first attempt | Matched after 1 / 2 / 3+ retries | Archived as not robust | Not-run retried | Recovered | Unresolved |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 1 | classifier | 0 | 0 | 0 / 0 / 0 | 0 | 0 | 0 | 0 |
| 2 | classifier | 0 | 0 | 0 / 0 / 0 | 0 | 0 | 0 | 0 |
| 3 | classifier | 0 | 0 | 0 / 0 / 0 | 0 | 0 | 0 | 0 |

Expected outcomes come from an earlier audit of the same tasks (matched by task ID). A task whose result differs from that audit is rerun up to the retry limit; a task that never matches is archived as not robust. Without an expectation only tasks with no result (crash, node failure, missing reward or missing runner evidence) are rerun, and a task still without a result after the last attempt is archived as not robust. Stages 1, 2 and 3 are covered; the retries run after the whole pipeline.

## fineenvs_v1

Keeps **5,000 tasks** and archives **0** from [FineEnvs/SmolDataEnvs-harbor-train](https://huggingface.co/datasets/FineEnvs/SmolDataEnvs-harbor-train) at commit `4719635555de1666f374d847baebb500d368e493`.


Our patcher modified **5,000 of the original 5,000 tasks**.

Automatic fixes changed **4,576 unique tasks**.

Tasks can have multiple change labels, so category counts may overlap.

| Change label | Tasks affected | Explanation |
| --- | ---: | --- |
| gold-answer-solution | 5000 | Retain one shared upstream image pinned to docker.io/savatar101/env-data-agent-train@sha256:7b3f7e22780b431ce0d43717dcef6875cde84baeee824cc87e968374d62d3470; use its existing math-verify 0.9.0 and check installed dependency versions in tests/setup.sh instead of repeating a best-effort pip install. Move the original input initialization for BUCKET_PREFIX=4quant__soft-tissue-sarcoma and nonempty-input check into setup_files/setup.sh and remove the duplicate healthcheck hook. Preserve the upstream input basename mapping, environment variables, instructions, grading logic and reward.txt output format. Rename the JSON correctness score to reward, including empty/missing-answer zeros; preserve the score value and auxiliary metrics. Add solution/solve.sh, which writes the verifier's EXPECTED_ANSWER to /workdir/answer.txt, so the reference stage can check that the environment and grader accept it; it does not recompute the answer from the data. Package 3 input files (397355382 bytes) under setup_files/inputs with remote Xet identities and SHA-256 checksums in input-manifest.json. Remove the setup downloader invocation and copy the packaged files locally during setup, verifying their checksums with bounded-memory copying. No input download occurs at setup or image build time.<br>Retain one shared upstream image pinned to docker.io/savatar101/env-data-agent-train@sha256:7b3f7e22780b431ce0d43717dcef6875cde84baeee824cc87e968374d62d3470; use its existing math-verify 0.9.0 and check installed dependency versions in tests/setup.sh instead of repeating a best-effort pip install. Move the original input initialization for BUCKET_PREFIX=CooperUnion__anime-recommendations-database and nonempty-input check into setup_files/setup.sh and remove the duplicate healthcheck hook. Preserve the upstream input basename mapping, environment variables, instructions, grading logic and reward.json output format. Rename the JSON correctness score to reward, including empty/missing-answer zeros; preserve the score value and auxiliary metrics. Add solution/solve.sh, which writes the verifier's EXPECTED_ANSWER to /workdir/answer.txt, so the reference stage can check that the environment and grader accept it; it does not recompute the answer from the data. Package 2 input files (112341362 bytes) under setup_files/inputs with remote Xet identities and SHA-256 checksums in input-manifest.json. Remove the setup downloader invocation and copy the packaged files locally during setup, verifying their checksums with bounded-memory copying. No input download occurs at setup or image build time.<br>Retain one shared upstream image pinned to docker.io/savatar101/env-data-agent-train@sha256:7b3f7e22780b431ce0d43717dcef6875cde84baeee824cc87e968374d62d3470; use its existing math-verify 0.9.0 and check installed dependency versions in tests/setup.sh instead of repeating a best-effort pip install. Move the original input initialization for BUCKET_PREFIX=CooperUnion__anime-recommendations-database and nonempty-input check into setup_files/setup.sh and remove the duplicate healthcheck hook. Preserve the upstream input basename mapping, environment variables, instructions, grading logic and reward.txt output format. Rename the JSON correctness score to reward, including empty/missing-answer zeros; preserve the score value and auxiliary metrics. Add solution/solve.sh, which writes the verifier's EXPECTED_ANSWER to /workdir/answer.txt, so the reference stage can check that the environment and grader accept it; it does not recompute the answer from the data. Package 2 input files (112341362 bytes) under setup_files/inputs with remote Xet identities and SHA-256 checksums in input-manifest.json. Remove the setup downloader invocation and copy the packaged files locally during setup, verifying their checksums with bounded-memory copying. No input download occurs at setup or image build time.<br>Retain one shared upstream image pinned to docker.io/savatar101/env-data-agent-train@sha256:7b3f7e22780b431ce0d43717dcef6875cde84baeee824cc87e968374d62d3470; use its existing math-verify 0.9.0 and check installed dependency versions in tests/setup.sh instead of repeating a best-effort pip install. Move the original input initialization for BUCKET_PREFIX=CooperUnion__cardataset and nonempty-input check into setup_files/setup.sh and remove the duplicate healthcheck hook. Preserve the upstream input basename mapping, environment variables, instructions, grading logic and reward.json output format. Rename the JSON correctness score to reward, including empty/missing-answer zeros; preserve the score value and auxiliary metrics. Add solution/solve.sh, which writes the verifier's EXPECTED_ANSWER to /workdir/answer.txt, so the reference stage can check that the environment and grader accept it; it does not recompute the answer from the data. Package 1 input files (1475504 bytes) under setup_files/inputs with remote Xet identities and SHA-256 checksums in input-manifest.json. Remove the setup downloader invocation and copy the packaged files locally during setup, verifying their checksums with bounded-memory copying. No input download occurs at setup or image build time.<br>Retain one shared upstream image pinned to docker.io/savatar101/env-data-agent-train@sha256:7b3f7e22780b431ce0d43717dcef6875cde84baeee824cc87e968374d62d3470; use its existing math-verify 0.9.0 and check installed dependency versions in tests/setup.sh instead of repeating a best-effort pip install. Move the original input initialization for BUCKET_PREFIX=CooperUnion__cardataset and nonempty-input check into setup_files/setup.sh and remove the duplicate healthcheck hook. Preserve the upstream input basename mapping, environment variables, instructions, grading logic and reward.txt output format. Rename the JSON correctness score to reward, including empty/missing-answer zeros; preserve the score value and auxiliary metrics. Add solution/solve.sh, which writes the verifier's EXPECTED_ANSWER to /workdir/answer.txt, so the reference stage can check that the environment and grader accept it; it does not recompute the answer from the data. Package 1 input files (1475504 bytes) under setup_files/inputs with remote Xet identities and SHA-256 checksums in input-manifest.json. Remove the setup downloader invocation and copy the packaged files locally during setup, verifying their checksums with bounded-memory copying. No input download occurs at setup or image build time.<br>Retain one shared upstream image pinned to docker.io/savatar101/env-data-agent-train@sha256:7b3f7e22780b431ce0d43717dcef6875cde84baeee824cc87e968374d62d3470; use its existing math-verify 0.9.0 and check installed dependency versions in tests/setup.sh instead of repeating a best-effort pip install. Move the original input initialization for BUCKET_PREFIX=Cornell-University__movie-dialog-corpus and nonempty-input check into setup_files/setup.sh and remove the duplicate healthcheck hook. Preserve the upstream input basename mapping, environment variables, instructions, grading logic and reward.json output format. Rename the JSON correctness score to reward, including empty/missing-answer zeros; preserve the score value and auxiliary metrics. Add solution/solve.sh, which writes the verifier's EXPECTED_ANSWER to /workdir/answer.txt, so the reference stage can check that the environment and grader accept it; it does not recompute the answer from the data. Package 6 input files (30116727 bytes) under setup_files/inputs with remote Xet identities and SHA-256 checksums in input-manifest.json. Remove the setup downloader invocation and copy the packaged files locally during setup, verifying their checksums with bounded-memory copying. No input download occurs at setup or image build time.<br>Retain one shared upstream image pinned to docker.io/savatar101/env-data-agent-train@sha256:7b3f7e22780b431ce0d43717dcef6875cde84baeee824cc87e968374d62d3470; use its existing math-verify 0.9.0 and check installed dependency versions in tests/setup.sh instead of repeating a best-effort pip install. Move the original input initialization for BUCKET_PREFIX=PromptCloudHQ__amazon-reviews-unlocked-mobile-phones and nonempty-input check into setup_files/setup.sh and remove the duplicate healthcheck hook. Preserve the upstream input basename mapping, environment variables, instructions, grading logic and reward.txt output format. Rename the JSON correctness score to reward, including empty/missing-answer zeros; preserve the score value and auxiliary metrics. Add solution/solve.sh, which writes the verifier's EXPECTED_ANSWER to /workdir/answer.txt, so the reference stage can check that the environment and grader accept it; it does not recompute the answer from th

fineenvs_v1/archive.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c40d87d7120d98b899773345bad4d1501f4d4cab98e2bd22e4b2fb6724a66e1d
3
+ size 3798215
fineenvs_v1/patch.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Expose FineEnvs preparation while retaining one inspected upstream image.
2
+
3
+ First run data/utils/fineenvs/prepare_inputs.py on the pinned source. Then run this patcher with
4
+ --source PINNED.parquet --inputs-cache SNAPSHOT --output NEW_DIRECTORY.
5
+ Every retained task includes its input bytes under setup_files/inputs. This
6
+ patcher does not access the network, build images, or execute task verifiers.
7
+ """
8
+ import argparse
9
+ import copy
10
+ import gzip
11
+ import hashlib
12
+ import io
13
+ import json
14
+ from pathlib import Path
15
+ import re
16
+ import shlex
17
+ import sys
18
+ import tarfile
19
+ import tomllib
20
+ from concurrent.futures import ProcessPoolExecutor
21
+ from multiprocessing import get_context
22
+
23
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
24
+ from data.utils.patch_reporting import write_patch_report
25
+ from data.utils.task_archive import read_members
26
+
27
+ SOURCE = {
28
+ "dataset": "FineEnvs/SmolDataEnvs-harbor-train",
29
+ "url": "https://huggingface.co/datasets/FineEnvs/SmolDataEnvs-harbor-train",
30
+ "revision": "4719635555de1666f374d847baebb500d368e493",
31
+ }
32
+ ORIGINAL_DOCKERFILE = b"FROM docker.io/savatar101/env-data-agent-train:base\nWORKDIR /workdir\n"
33
+ PIP_PREPARATION = b"pip install --quiet math-verify >/dev/null 2>&1 || true\n"
34
+ HEALTHCHECK = 'python3 /opt/pull_bucket.py && [ -n "$(ls /home/user/input)" ]'
35
+ TASK_SETUP = b'''#!/usr/bin/env bash
36
+ set -euo pipefail
37
+ python3 /setup_files/pull_bucket.py
38
+ [ -n "$(ls /home/user/input)" ]
39
+ '''
40
+ # All source tasks passed validation with packaged inputs.
41
+ EXCLUDED = {}
42
+ SUPPORT_DIR = Path(__file__).resolve().parents[1] / "utils" / "fineenvs"
43
+ if Path(__file__).with_name("preparation.json").is_file():
44
+ SUPPORT_DIR = Path(__file__).resolve().parent
45
+ LOCK_PATH = SUPPORT_DIR / "preparation.json"
46
+ SNAPSHOT_PATH = SUPPORT_DIR / "input-snapshot.json"
47
+ SNAPSHOT_ROOT = "/opt/fineenvs-inputs"
48
+ # Only the measured slow prefix receives an additional shared image. Build-time
49
+ # downloads must match both the recorded remote identities and actual bytes.
50
+ BUILD_SNAPSHOT = b'''import hashlib
51
+ import json
52
+ from pathlib import Path
53
+ from huggingface_hub import download_bucket_files, list_bucket_tree
54
+
55
+ root = Path("/opt/fineenvs-inputs")
56
+ snapshot = json.loads((root / "manifest.json").read_text())
57
+ observed = {f.path: f for f in list_bucket_tree(
58
+ snapshot["bucket"], prefix=snapshot["prefix"] + "/", recursive=True,
59
+ token=False) if getattr(f, "type", None) == "file"}
60
+ assert set(observed) == {f["path"] for f in snapshot["files"]}, "input inventory changed"
61
+ targets = []
62
+ for f in snapshot["files"]:
63
+ actual = observed[f["path"]]
64
+ assert (actual.size, actual.xet_hash) == (f["size"], f["xet_hash"]), "remote input changed"
65
+ targets.append((actual, root / "files" / Path(f["path"]).name))
66
+ (root / "files").mkdir(parents=True, exist_ok=True)
67
+ download_bucket_files(snapshot["bucket"], files=targets, token=False)
68
+ for f in snapshot["files"]:
69
+ path = root / "files" / Path(f["path"]).name
70
+ assert path.stat().st_size == f["size"], "input size mismatch"
71
+ with path.open("rb") as stream:
72
+ assert hashlib.file_digest(stream, "sha256").hexdigest() == f["sha256"], "input hash mismatch"
73
+ '''
74
+ STAGE_SNAPSHOT = b'''import hashlib
75
+ import json
76
+ import os
77
+ from pathlib import Path
78
+ import time
79
+
80
+
81
+ def copy_input(source, target, expected):
82
+ # Avoid the opaque sendfile fast path used by shutil.copyfile. Keep dirty
83
+ # destination pages bounded for the upstream 1 GiB task memory limit.
84
+ started = time.monotonic()
85
+ digest = hashlib.sha256()
86
+ total = pending = 0
87
+ with source.open("rb") as reader, target.open("wb", buffering=0) as writer:
88
+ while chunk := reader.read(1024 * 1024):
89
+ view = memoryview(chunk)
90
+ while view:
91
+ written = writer.write(view)
92
+ if not written:
93
+ raise OSError("input copy made no progress")
94
+ view = view[written:]
95
+ digest.update(chunk)
96
+ total += len(chunk)
97
+ pending += len(chunk)
98
+ if pending >= 32 * 1024 * 1024:
99
+ os.fdatasync(writer.fileno())
100
+ os.posix_fadvise(writer.fileno(), total - pending, pending, os.POSIX_FADV_DONTNEED)
101
+ pending = 0
102
+ os.fdatasync(writer.fileno())
103
+ os.posix_fadvise(writer.fileno(), 0, 0, os.POSIX_FADV_DONTNEED)
104
+ if total != expected["size"] or digest.hexdigest() != expected["sha256"]:
105
+ raise RuntimeError(f"input copy mismatch: {source.name}")
106
+ print(f"[pull_bucket] copied {source.name}: {total} bytes in {time.monotonic() - started:.3f}s", flush=True)
107
+
108
+
109
+ root = Path("/opt/fineenvs-inputs")
110
+ snapshot = json.loads((root / "manifest.json").read_text())
111
+ assert os.environ["BUCKET_PREFIX"].rstrip("/") == snapshot["prefix"]
112
+ assert (os.environ.get("HF_BUCKET") or "AdithyaSK/jupyter-agent-kaggle-all") == snapshot["bucket"]
113
+ dest = Path("/home/user/input")
114
+ dest.mkdir(parents=True, exist_ok=True)
115
+ # Match the original downloader's existing-file guard and basename mapping.
116
+ existing = [p for p in dest.iterdir() if p.is_file()]
117
+ if existing:
118
+ print(f"[pull_bucket] {dest}/ already has {len(existing)} file(s); skipping", flush=True)
119
+ else:
120
+ for f in snapshot["files"]:
121
+ source = root / "files" / Path(f["path"]).name
122
+ assert source.stat().st_size == f["size"], "baked input size mismatch"
123
+ print(f"[pull_bucket] copying {source.name}: {f['size']} bytes", flush=True)
124
+ copy_input(source, dest / source.name, f)
125
+ print(f"[pull_bucket] staged {len(snapshot['files'])} file(s) from baked snapshot", flush=True)
126
+ '''
127
+
128
+
129
+ def verifier_setup(lock):
130
+ versions = repr(lock["verifier_distributions"])
131
+ return ("#!/usr/bin/env bash\nset -euo pipefail\npython3 - <<'PY'\n"
132
+ "from importlib.metadata import version\n"
133
+ f"expected = {versions}\n"
134
+ "for name, wanted in expected.items():\n"
135
+ " actual = version(name)\n"
136
+ " if actual != wanted:\n"
137
+ " raise RuntimeError(f'{name}: expected {wanted}, found {actual}')\n"
138
+ "from math_verify import parse, verify\n"
139
+ "import antlr4, latex2sympy2_extended, mpmath, sympy\n"
140
+ "PY\n").encode()
141
+
142
+
143
+ def gold_solution(config):
144
+ """Reference solution: write the answer the grader expects, exactly as the agent must.
145
+
146
+ It proves the environment starts, the answer path is writable and the grader
147
+ accepts the expected value; it does not recompute the answer from the data.
148
+ The grader compares against verifier.env EXPECTED_ANSWER, which differs from the
149
+ notebook's metadata.gold_answer in 41 upstream tasks.
150
+ """
151
+ expected = config["verifier"]["env"]["EXPECTED_ANSWER"]
152
+ return ("#!/bin/bash\nset -euo pipefail\nmkdir -p /workdir\n"
153
+ f"printf '%s' {shlex.quote(expected)} > /workdir/answer.txt\n").encode()
154
+
155
+
156
+ def normalize_rewards(script, grader):
157
+ """Rename the JSON score, including the missing-answer branch, without regrading."""
158
+ if grader.count(b'"correctness":') != 2:
159
+ raise ValueError("unexpected upstream JSON grader score fields")
160
+ if b"reward.json" in script:
161
+ if script.count(b'"correctness":') != 1:
162
+ raise ValueError("unexpected upstream missing-answer JSON score")
163
+ script = script.replace(b'"correctness":', b'"reward":')
164
+ script = script.replace(b"# correctness ", b"# reward ")
165
+ elif b"reward.txt" not in script:
166
+ raise ValueError("unknown upstream reward format")
167
+ return script, grader.replace(b'"correctness":', b'"reward":')
168
+
169
+
170
+ def transform(blob, lock, snapshot=None, packaged=None):
171
+ files = read_members(blob)
172
+ config = tomllib.loads(files["task.toml"].decode())
173
+ if files["environment/Dockerfile"] != ORIGINAL_DOCKERFILE:
174
+ raise ValueError("unexpected upstream Dockerfile")
175
+ if hashlib.sha256(files["environment/pull_bucket.py"]).hexdigest() != lock["pull_bucket_sha256"]:
176
+ raise ValueError("unexpected upstream input downloader")
177
+ if config["environment"]["healthcheck"]["command"] != HEALTHCHECK:
178
+ raise ValueError("unexpected upstream healthcheck")
179
+ if files["tests/test.sh"].count(PIP_PREPARATION) != 1:
180
+ raise ValueError("unexpected upstream verifier preparation")
181
+ if any(name.startswith(("setup_files/", "solution/")) or name == "tests/setup.sh" for name in files):
182
+ raise ValueError("unexpected existing setup or solution")
183
+ # Remove only the obsolete lifecycle declaration and its explanatory comment.
184
+ # Preserve other TOML bytes, including variables, answers and resources.
185
+ toml, count = re.subn(
186
+ r"# Pre-agent hook: Harbor runs the command AFTER container start and BEFORE the\n"
187
+ r"# agent setup begins\. We use it to pull this task's bucket prefix into\n"
188
+ r"# /home/user/input/\. See environment/pull_bucket\.py\.\n"
189
+ r"\[environment\.healthcheck\]\n.*?(?=\[environment\.env\])",
190
+ "", files["task.toml"].decode(), count=1, flags=re.S)
191
+ if count != 1:
192
+ raise ValueError("unexpected upstream lifecycle declaration")
193
+ before = copy.deepcopy(config)
194
+ del before["environment"]["healthcheck"]
195
+ if tomllib.loads(toml) != before:
196
+ raise ValueError("configuration changed beyond the healthcheck removal")
197
+ verifier_script, grader = normalize_rewards(
198
+ files["tests/test.sh"].replace(PIP_PREPARATION, b""), files["tests/grader.py"])
199
+ replacements = {
200
+ "environment/Dockerfile": (f'FROM {lock["image"]}\nWORKDIR /workdir\n').encode(),
201
+ "task.toml": toml.encode(),
202
+ "tests/test.sh": verifier_script,
203
+ "tests/grader.py": grader,
204
+ }
205
+ additions = {
206
+ "setup_files/setup.sh": (TASK_SETUP, 0o755),
207
+ "setup_files/pull_bucket.py": (files["environment/pull_bucket.py"], 0o644),
208
+ "tests/setup.sh": (verifier_setup(lock), 0o755),
209
+ "solution/solve.sh": (gold_solution(config), 0o755),
210
+ }
211
+ prebuilt = packaged is None and snapshot is not None and config["environment"]["env"]["BUCKET_PREFIX"].rstrip("/") == snapshot["prefix"]
212
+ if prebuilt:
213
+ if config["environment"]["env"]["HF_BUCKET"] != snapshot["bucket"]:
214
+ raise ValueError("snapshot bucket does not match task")
215
+ names = [Path(f["path"]).name for f in snapshot["files"]]
216
+ if not names or len(set(names)) != len(names):
217
+ raise ValueError("snapshot has missing or colliding basenames")
218
+ additions.update({
219
+ "environment/input-snapshot.json": ((json.dumps(snapshot, sort_keys=True, indent=2) + "\n").encode(), 0o644),
220
+ "environment/build_snapshot.py": (BUILD_SNAPSHOT, 0o644),
221
+ "setup_files/stage_inputs.py": (STAGE_SNAPSHOT, 0o644),
222
+ })
223
+ replacements["environment/Dockerfile"] += (
224
+ f"COPY input-snapshot.json {SNAPSHOT_ROOT}/manifest.json\n"
225
+ f"COPY build_snapshot.py {SNAPSHOT_ROOT}/build_snapshot.py\n"
226
+ f"RUN python3 {SNAPSHOT_ROOT}/build_snapshot.py\n").encode()
227
+ additions["setup_files/setup.sh"] = (TASK_SETUP.replace(b"pull_bucket.py", b"stage_inputs.py"), 0o755)
228
+ if packaged is not None:
229
+ manifest, directory = packaged
230
+ env = config['environment']['env']
231
+ if (manifest['bucket'], manifest['prefix']) != (env['HF_BUCKET'], env['BUCKET_PREFIX'].rstrip('/')):
232
+ raise ValueError('packaged input family does not match task')
233
+ names = [f['name'] for f in manifest['files']]
234
+ if not names or len(names) != len(set(names)) or any(
235
+ not n or Path(n).is_absolute() or '..' in Path(n).parts or Path(n).as_posix() != n or n == '.' for n in names):
236
+ raise ValueError('invalid or colliding input paths')
237
+ del additions['setup_files/pull_bucket.py']
238
+ additions.update({
239
+ 'setup_files/setup.sh': (TASK_SETUP.replace(b'pull_bucket.py', b'stage_inputs.py'), 0o755),
240
+ 'setup_files/stage_inputs.py': ((SUPPORT_DIR / 'stage_inputs.py').read_bytes(), 0o644),
241
+ 'setup_files/input-manifest.json': ((json.dumps(manifest, sort_keys=True, indent=2) + '\n').encode(), 0o644),
242
+ })
243
+ for item in manifest['files']:
244
+ additions['setup_files/inputs/' + item['name']] = (directory / 'files' / item['name'], 0o644)
245
+ if any('/' in name for name in names):
246
+ instruction = files['instruction.md'].decode()
247
+ instruction = instruction.replace('Files (in /home/user/input, no subfolders):',
248
+ 'Files (in /home/user/input; additional source variants retain their subfolders):')
249
+ for name in names:
250
+ if '/' not in name:
251
+ instruction = re.sub(r'(?m)^- ' + re.escape(name) + r'$',
252
+ lambda match: '- /home/user/input/' + name, instruction)
253
+ replacements['instruction.md'] = instruction.encode()
254
+ # Preserve original modes, links and metadata. Fix gzip time and new-member
255
+ # metadata so repeated patching produces identical bytes.
256
+ output = io.BytesIO()
257
+ with gzip.GzipFile(fileobj=output, mode="wb", filename="", mtime=0,
258
+ compresslevel=1 if packaged is not None else 9) as compressed:
259
+ with tarfile.open(fileobj=io.BytesIO(blob), mode="r:*") as original:
260
+ with tarfile.open(fileobj=compressed, mode="w") as patched:
261
+ for member in original:
262
+ content = original.extractfile(member).read() if member.isfile() else None
263
+ info = copy.copy(member)
264
+ if member.name in replacements:
265
+ content = replacements[member.name]
266
+ info.size = len(content)
267
+ patched.addfile(info, io.BytesIO(content) if content is not None else None)
268
+ for name, (content, mode) in sorted(additions.items()):
269
+ info = tarfile.TarInfo(name)
270
+ info.mode = mode
271
+ if isinstance(content, Path):
272
+ info.size = content.stat().st_size
273
+ with content.open('rb') as stream:
274
+ patched.addfile(info, stream)
275
+ else:
276
+ info.size = len(content)
277
+ patched.addfile(info, io.BytesIO(content))
278
+ variant = "reward.json" if b"reward.json" in files["tests/test.sh"] else "reward.txt"
279
+ reason = (
280
+ f"Retain one shared upstream image pinned to {lock['image']}; use its existing "
281
+ "math-verify 0.9.0 and check installed dependency versions in tests/setup.sh "
282
+ "instead of repeating a best-effort pip install. Move the original input "
283
+ f"initialization for BUCKET_PREFIX={config['environment']['env']['BUCKET_PREFIX']} "
284
+ "and nonempty-input check into setup_files/setup.sh and remove the duplicate "
285
+ "healthcheck hook. Preserve the upstream downloader bytes and basename mapping, "
286
+ f"environment variables, instructions, grading logic and {variant} output format. "
287
+ "Rename the JSON correctness score to reward, including empty/missing-answer zeros; "
288
+ "preserve the score value and auxiliary metrics. "
289
+ "Add solution/solve.sh, which writes the verifier's EXPECTED_ANSWER to "
290
+ "/workdir/answer.txt, so the reference stage can check that the environment and grader "
291
+ "accept it; it does not recompute the answer from the data."
292
+ )
293
+ if config["metadata"]["gold_answer"] != config["verifier"]["env"]["EXPECTED_ANSWER"]:
294
+ reason += (f" Upstream records two answers: notebook gold_answer "
295
+ f"{config['metadata']['gold_answer']!r} and graded EXPECTED_ANSWER "
296
+ f"{config['verifier']['env']['EXPECTED_ANSWER']!r}; the solution uses the graded one.")
297
+ if prebuilt:
298
+ reason += (
299
+ f" Bake all {len(snapshot['files'])} original input files ({sum(f['size'] for f in snapshot['files'])} bytes) "
300
+ "into one image shared by this bucket family, with remote Xet identity and SHA-256 checks at build time. "
301
+ "Copy the same basenames and bytes locally during setup, preserving the existing-file guard. "
302
+ "The pilot task 0060_333_60333012_qa_4 timed out in all five fresh preparations at 60.001 seconds; "
303
+ f"evidence: {snapshot['evidence']['report']}; archive member: {snapshot['evidence']['archive_member']}. "
304
+ "A later public download succeeded, so this is a preparation reliability repair, not an exclusion. "
305
+ "Generation 1 built this snapshot image successfully, but local copy preparation still "
306
+ "hit 60 seconds in two of five runs (others 9.047, 8.949 and 8.615 seconds). "
307
+ "Replace shutil.copyfile/sendfile with a 1 MiB buffered copy, flush and release only "
308
+ "destination cache pages every 32 MiB, and verify SHA-256 during the copy. "
309
+ "This addresses possible dirty-page pressure from 943755800 input bytes under the "
310
+ "unchanged 1024 MiB memory limit; logs do not establish the kernel stall cause. "
311
+ "Per-file progress and elapsed-time logs expose any remaining stall. "
312
+ "Evidence: generation-0001/stage3-10/results/submissions/e437d78d5ed6/report/"
313
+ "stage-3-a8956d95a28f.json; archive image-build-logs/fd623c862442.build.log and "
314
+ "results/stage_3_build_validation/a8956d95a28f/00004-0060_333_60333012_qa_4/"
315
+ "preparation-review.json (retry-1 through retry-4). "
316
+ "Verifier timeout remains 120 seconds; successful verifier preparations met its "
317
+ "6-second allowance. Fresh stage-3 setup review is required; this is not a claimed pass."
318
+ )
319
+ if packaged is not None:
320
+ reason = reason.replace('Preserve the upstream downloader bytes and basename mapping, ',
321
+ 'Preserve the upstream input basename mapping, ')
322
+ reason += (f" Package {len(manifest['files'])} input files ({sum(f['size'] for f in manifest['files'])} bytes) "
323
+ "under setup_files/inputs with remote Xet identities and SHA-256 checksums in input-manifest.json. "
324
+ "Remove the setup downloader invocation and copy the packaged files locally during setup, verifying "
325
+ "their checksums with bounded-memory copying. No input download occurs at setup or image build time.")
326
+ if any('/' in f['name'] for f in manifest['files']):
327
+ reason += (' Preserve content-pinned input variants under distinct source-relative paths instead of '
328
+ 'the upstream downloader overwriting equal basenames nondeterministically. '
329
+ 'Keep task-declared root files at their original root locations and make those instruction '
330
+ 'paths explicit; disclose the additional source subfolders. Question and graded answer are unchanged.')
331
+ return output.getvalue(), reason
332
+
333
+
334
+ def packaged_inputs(cache, source):
335
+ """Verify a complete prepared snapshot once before reusing its families."""
336
+ def digest(path):
337
+ with path.open('rb') as stream:
338
+ return hashlib.file_digest(stream, 'sha256').hexdigest()
339
+ index = json.loads((cache / 'index.json').read_text())
340
+ if not index.get('complete') or index['source'] != SOURCE or index['source_parquet_sha256'] != digest(source):
341
+ raise ValueError('input snapshot is incomplete or belongs to a different source')
342
+ result = {}
343
+ for family in index['families']:
344
+ path = (cache / family['manifest']).resolve()
345
+ if not path.is_relative_to(cache.resolve()) or digest(path) != family['manifest_sha256']:
346
+ raise ValueError('input manifest path or checksum mismatch')
347
+ manifest = json.loads(path.read_text())
348
+ key = (manifest['bucket'], manifest['prefix'])
349
+ if key in result or key != (family['bucket'], family['prefix']):
350
+ raise ValueError('duplicate or mismatched input family')
351
+ names = [f['name'] for f in manifest['files']]
352
+ if not names or len(set(names)) != len(names) or any(
353
+ not n or Path(n).is_absolute() or '..' in Path(n).parts or Path(n).as_posix() != n or n == '.' for n in names):
354
+ raise ValueError('invalid input manifest filenames')
355
+ for item in manifest['files']:
356
+ f = path.parent / 'files' / item['name']
357
+ if f.is_symlink() or f.stat().st_size != item['size'] or digest(f) != item['sha256']:
358
+ raise ValueError('packaged input checksum mismatch: ' + str(f))
359
+ result[key] = (manifest, path.parent)
360
+ return index, result
361
+
362
+
363
+ def main():
364
+ parser = argparse.ArgumentParser(description=__doc__)
365
+ parser.add_argument("--source", type=Path, required=True)
366
+ parser.add_argument("--output", type=Path, required=True)
367
+ parser.add_argument('--inputs-cache', type=Path, required=True,
368
+ help='complete checksum-verified snapshot produced by prepare_inputs.py')
369
+ parser.add_argument('--workers', type=int, default=4, help='bounded parallel task compression workers')
370
+ parser.add_argument('--include-archived', action='store_true',
371
+ help='include any explicitly excluded tasks for revalidation')
372
+ args = parser.parse_args()
373
+ if not 1 <= args.workers <= 8:
374
+ parser.error('--workers must be between 1 and 8')
375
+ import pyarrow as pa
376
+ import pyarrow.parquet as pq
377
+ source = args.source
378
+ if source.is_dir():
379
+ sources = sorted(source.glob("*.parquet"))
380
+ if len(sources) != 1:
381
+ raise ValueError("expected one pinned source Parquet")
382
+ source = sources[0]
383
+ destination = args.output / source.name
384
+ reporting_paths = [destination, destination.with_suffix('.archive.parquet'),
385
+ destination.with_suffix('.manifest.json'),
386
+ destination.with_suffix('.manifest.patch.py'),
387
+ args.output / 'preparation.json']
388
+ reporting_paths.append(args.output / 'input-snapshot.json')
389
+ if destination.resolve() == source.resolve() or any(p.exists() for p in reporting_paths):
390
+ raise ValueError("use a new output directory distinct from the immutable source")
391
+ lock = json.loads(LOCK_PATH.read_text())
392
+ input_index, inputs = packaged_inputs(args.inputs_cache, source)
393
+ parquet = pq.ParquetFile(source)
394
+ args.output.mkdir(parents=True, exist_ok=True)
395
+ labels, reasons = {}, {}
396
+ excluded = {} if args.include_archived else EXCLUDED
397
+ with ProcessPoolExecutor(max_workers=args.workers, mp_context=get_context('spawn')) as pool, \
398
+ pq.ParquetWriter(destination, parquet.schema_arrow) as writer:
399
+ for batch in parquet.iter_batches(batch_size=args.workers * 2):
400
+ rows = [row for row in batch.to_pylist() if row["path"] not in excluded]
401
+ pending = []
402
+ for row in rows:
403
+ config = tomllib.loads(read_members(row['task_binary'])['task.toml'].decode())
404
+ env = config['environment']['env']
405
+ family = inputs[(env['HF_BUCKET'], env['BUCKET_PREFIX'].rstrip('/'))]
406
+ pending.append(pool.submit(transform, row['task_binary'], lock, None, family))
407
+ for row, future in zip(rows, pending):
408
+ name = row["path"]
409
+ if name in labels:
410
+ raise ValueError(f"duplicate source task ID: {name}")
411
+ row["task_binary"], reasons[name] = future.result()
412
+ labels[name] = ["runtime-preparation", "gold-answer-solution", "reward-key-normalization"]
413
+ labels[name].append('packaged-task-inputs')
414
+ writer.write_table(pa.Table.from_pylist(rows, schema=parquet.schema_arrow))
415
+ if len(labels) and len(labels) % 100 < len(rows):
416
+ print(f'Packaged {len(labels)} tasks', flush=True)
417
+ report = write_patch_report(
418
+ source, destination, source=SOURCE,
419
+ dropped={name: {"category": "resource-limit", "reason": reason} for name, reason in excluded.items()},
420
+ change_labels=labels,
421
+ change_reasons=reasons, patches=[{"label": "runtime-preparation", **lock},
422
+ {"label": "packaged-task-inputs", **input_index},
423
+ {"label": "reward-key-normalization", "reason": "Rename JSON correctness to reward without changing grading."},
424
+ {"label": "gold-answer-solution", "reason": "solution/solve.sh "
425
+ "writes the graded EXPECTED_ANSWER to /workdir/answer.txt."}],
426
+ patcher=__file__)
427
+ (args.output / 'preparation.json').write_bytes(LOCK_PATH.read_bytes())
428
+ (args.output / 'input-snapshot.json').write_text(json.dumps(input_index, indent=2) + '\n')
429
+ for helper in ('stage_inputs.py', 'prepare_inputs.py', 'reviewed-input-conflicts.json'):
430
+ (args.output / helper).write_bytes((SUPPORT_DIR / helper).read_bytes())
431
+ print(json.dumps({"tasks": len(report["tasks"]), "changed": len(labels),
432
+ "excluded": len(excluded), "output": str(destination),
433
+ "requires_review_setup": True}))
434
+
435
+
436
+ if __name__ == "__main__":
437
+ main()
fineenvs_v1/tasks.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ff268d168d9f63d271e0f4ed3633efeb297de0ea8ca8548a6f962efe4af850c
3
+ size 35925854146