codemaivanngu commited on
Commit
2bcfcd8
·
verified ·
1 Parent(s): d6b02b5

Add resumable full-dataset preparation helper and target setup guidance

Browse files
DESIGN.md CHANGED
@@ -60,8 +60,10 @@ spreadsheet service.
60
  - [x] Build/qualify a CPU runtime on Modal for the target distro/architecture.
61
  - [x] Publish a credential-free bundle, checksums, dependency/license notices,
62
  code/data provenance, and qualification receipt to a public HF repository.
63
- - [ ] User downloads through the company proxy; run readiness and a small canary
64
- on the target container before scaling RL.
 
 
65
 
66
  ## Runtime packaging
67
 
 
60
  - [x] Build/qualify a CPU runtime on Modal for the target distro/architecture.
61
  - [x] Publish a credential-free bundle, checksums, dependency/license notices,
62
  code/data provenance, and qualification receipt to a public HF repository.
63
+ - [x] User downloads through the company proxy and runs a target-container canary:
64
+ 34 passed, two expected skips; Python root placed on node-local storage.
65
+ - [ ] Qualify the pinned dataset, start the persistent service, and validate a
66
+ live model rollout through the training container before scaling RL.
67
 
68
  ## Runtime packaging
69
 
INSTALL.md CHANGED
@@ -22,10 +22,14 @@ Qualification passed 29 local tests, 34 Linux CPU tests, and the same 34 tests
22
  after offline installation in a clean Ubuntu container. The Linux runs skip
23
  Gym-specific tests (covered locally) and the non-root rejection case; local runs
24
  skip the real Linux/XLSX dependencies. Ruff and shell syntax checks passed.
25
- The actual company node, full dataset compatibility, live model rollout, training
26
- throughput, and Excel reward equivalence remain unverified.
 
 
27
 
28
  Run these commands **on the service node**, using its configured company proxy:
 
 
29
 
30
  ```bash
31
  SPREADSHEET_BUNDLE_BASE=https://huggingface.co/datasets/codemaivanngu/spreadsheet-gym-libreoffice-runtime/resolve/a4bb83d536bc3512ffa7e60bac4dcd6b0461c3d1
@@ -165,6 +169,28 @@ on the service node. Pin the Hugging Face dataset commit and verify its files.
165
  Extract the archive outside the public bundle and Python chroot. Do not include
166
  both Hermes and Qwen-Coder versions of the same tasks.
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  The following paths are examples; replace them with the node's actual paths.
169
  Use the wheelhouse to install pyarrow into the service venv without network:
170
 
@@ -199,18 +225,33 @@ prompt with the actual tool/LibreOffice contract while retaining user task text.
199
 
200
  ## Configure and run
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  Create private keys/config locally on the service node:
203
 
204
  ```bash
205
  ../service-venv/bin/python -m resources_servers.spreadsheet.init_service \
206
  --data-root /srv/spreadsheet/data \
207
  --manifest /srv/spreadsheet/prepared/manifest.qualified.jsonl \
208
- --state-root /srv/spreadsheet/state --config-dir /srv/spreadsheet/private \
209
- --python-rootfs "$(cd ../python-root && pwd)" \
210
  --service-url http://SERVICE_IP:8088
211
 
212
  ../service-venv/bin/python -m resources_servers.spreadsheet.service.app \
213
- --config /srv/spreadsheet/private/service.json
214
  ```
215
 
216
  The service binds `0.0.0.0:8088`; advertise its routable IP to the train container.
 
22
  after offline installation in a clean Ubuntu container. The Linux runs skip
23
  Gym-specific tests (covered locally) and the non-root rejection case; local runs
24
  skip the real Linux/XLSX dependencies. Ruff and shell syntax checks passed.
25
+ An operator-provided target-container run also passed 34 tests with the same two
26
+ expected skips after placing the isolated Python root on node-local storage.
27
+ Full dataset compatibility, live model rollout, training throughput, and Excel
28
+ reward equivalence remain unverified.
29
 
30
  Run these commands **on the service node**, using its configured company proxy:
31
+ download and extract the runtime on node-local executable storage. Dataset files
32
+ and prepared manifests may remain on shared storage.
33
 
34
  ```bash
35
  SPREADSHEET_BUNDLE_BASE=https://huggingface.co/datasets/codemaivanngu/spreadsheet-gym-libreoffice-runtime/resolve/a4bb83d536bc3512ffa7e60bac4dcd6b0461c3d1
 
169
  Extract the archive outside the public bundle and Python chroot. Do not include
170
  both Hermes and Qwen-Coder versions of the same tasks.
171
 
172
+ For the pinned public dataset revision
173
+ `6f274cd4cbc27e656d7ddae7c3b591669866dc84`,
174
+ [`packaging/prepare_dataset.py`](packaging/prepare_dataset.py) combines extraction,
175
+ preparation, full oracle qualification and filtering of both Hermes splits. Run
176
+ this standalone helper with the installed service Python, `PYTHONPATH` pointing
177
+ at bundled source, `--download-root` pointing at the three downloaded dataset
178
+ files, and `--work-root` pointing at node-local storage. Install bundled
179
+ `pyarrow==22.0.0` offline first. It works with the published `9dcc7e1` source;
180
+ rebuilding the runtime archive is unnecessary.
181
+
182
+ The helper verifies the pinned downloads, validates archive paths/CRCs, and
183
+ publishes completed extractions and preparation results atomically. Qualification
184
+ prints progress and checkpoints every 25 tasks by default. Rerun the same command
185
+ after interruption to reuse completed batches; keep the same helper, engine and
186
+ batch size. An interrupted batch is recalculated from original oracle copies.
187
+ Results are under `prepared-SP06/libreoffice/`: `manifest.qualified.jsonl`,
188
+ `train.qualified.jsonl`, `test.qualified.jsonl`, and `compatibility.json`. The final
189
+ `SP06_DATASET_READY` event follows a fresh check of qualified seed/oracle hashes.
190
+ This gate does not establish Excel equivalence or arbitrary future formula
191
+ compatibility. Keep reports private; the helper does not upload data or start
192
+ the service.
193
+
194
  The following paths are examples; replace them with the node's actual paths.
195
  Use the wheelhouse to install pyarrow into the service venv without network:
196
 
 
225
 
226
  ## Configure and run
227
 
228
+ Keep the Python root filesystem and service state on node-local storage. The
229
+ state directory contains SQLite databases and locks; do not put it on Lustre or
230
+ NFS. A target canary failed to execute Python from its shared filesystem after
231
+ dropping privileges, but passed with the same root copied to local storage with
232
+ clean ownership, modes, ACLs, and extended attributes. This does not establish
233
+ that every shared filesystem is mounted `noexec`.
234
+
235
+ If the offline installer has already installed dependencies and created
236
+ `service-venv`, a failed final isolation probe does not require reinstalling.
237
+ Copy the Python root to a fresh node-local directory, preserve root ownership and
238
+ the builder's directory/file modes, remove inherited ACLs and extended
239
+ attributes, and repeat the real isolation canary. Configure the service with the
240
+ local root only after that canary passes. Do not relax isolation policies to
241
+ work around filesystem execution failures.
242
+
243
  Create private keys/config locally on the service node:
244
 
245
  ```bash
246
  ../service-venv/bin/python -m resources_servers.spreadsheet.init_service \
247
  --data-root /srv/spreadsheet/data \
248
  --manifest /srv/spreadsheet/prepared/manifest.qualified.jsonl \
249
+ --state-root /opt/spreadsheet-gym/state --config-dir /opt/spreadsheet-gym/private \
250
+ --python-rootfs /opt/spreadsheet-gym/python-root \
251
  --service-url http://SERVICE_IP:8088
252
 
253
  ../service-venv/bin/python -m resources_servers.spreadsheet.service.app \
254
+ --config /opt/spreadsheet-gym/private/service.json
255
  ```
256
 
257
  The service binds `0.0.0.0:8088`; advertise its routable IP to the train container.
helpers/prepare_dataset.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "helper_source_commit": "65b2f3483e78e4831ee6dc45dd5cf7bc10752034",
3
+ "compatible_runtime_source_commit": "9dcc7e1aef517af8da352fcb7a56cf5baba28e1d",
4
+ "dataset_revision": "6f274cd4cbc27e656d7ddae7c3b591669866dc84",
5
+ "file": "helpers/prepare_dataset.py",
6
+ "bytes": 11655,
7
+ "sha256": "d85586d9ddf69264e39050df15cd7af1d581b25b2628742ba7f17d45449acc48",
8
+ "validation": "8 offline orchestration tests passed; target full dataset run pending"
9
+ }
helpers/prepare_dataset.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prepare the pinned public dataset and checkpoint full LibreOffice qualification.
2
+
3
+ Run with the installed service Python and PYTHONPATH pointing at bundled source.
4
+ This helper downloads nothing and does not start the service or modify oracles.
5
+ """
6
+
7
+ import argparse
8
+ import fcntl
9
+ import hashlib
10
+ import json
11
+ import shutil
12
+ import signal
13
+ import stat
14
+ import tempfile
15
+ import zipfile
16
+ from collections import Counter
17
+ from pathlib import Path, PurePosixPath
18
+
19
+
20
+ REVISION = "6f274cd4cbc27e656d7ddae7c3b591669866dc84"
21
+ FILES = {
22
+ "spreadsheets.zip": (1221095226, "d69a7ebc62cb3bd0c7e0430124f6c526e2b66696c32f99c172d5b6169db2f276"),
23
+ "train_hermes.parquet": (3551543, "e7537324ee79cfbbd9598b21b71d6ec865701630682e3929f8784abb1d53cfe6"),
24
+ "test_hermes.parquet": (439551, "14c8d7e07497653e32f136453a14b3c6d6d34c4f9546621ea9b7110605b47972"),
25
+ }
26
+
27
+
28
+ def digest(path):
29
+ with path.open("rb") as stream:
30
+ return hashlib.file_digest(stream, "sha256").hexdigest()
31
+
32
+
33
+ def read_json(path):
34
+ return json.loads(path.read_text())
35
+
36
+
37
+ def write_json(path, value):
38
+ path.write_text(json.dumps(value, indent=2) + "\n")
39
+
40
+
41
+ def emit(event, **values):
42
+ print(json.dumps({"event": event, **values}), flush=True)
43
+
44
+
45
+ def extract_archive(archive, destination, archive_sha):
46
+ """Publish a complete extraction atomically; interrupted staging stays separate."""
47
+ receipt = {"archive_sha256": archive_sha}
48
+ if destination.exists():
49
+ if read_json(destination / ".extraction.json") != receipt:
50
+ raise ValueError("Existing extraction has a different receipt")
51
+ return
52
+ with zipfile.ZipFile(archive) as source:
53
+ members, names = [], set()
54
+ for member in source.infolist():
55
+ name = PurePosixPath(member.filename)
56
+ if name.is_absolute() or ".." in name.parts or "\\" in member.filename:
57
+ raise ValueError("Unsafe archive path")
58
+ if stat.S_ISLNK(member.external_attr >> 16):
59
+ raise ValueError("Archive symlinks are not supported")
60
+ if member.is_dir() or name.name == ".DS_Store" or "__MACOSX" in name.parts:
61
+ continue
62
+ if str(name) in names or not name.parts:
63
+ raise ValueError("Duplicate or empty archive path")
64
+ names.add(str(name))
65
+ members.append(member)
66
+ needed = sum(member.file_size for member in members)
67
+ if shutil.disk_usage(destination.parent).free < needed + 1024**3:
68
+ raise ValueError("Not enough free disk for extraction plus 1 GiB")
69
+ stage = Path(tempfile.mkdtemp(prefix=".extract-SP06-", dir=destination.parent))
70
+ emit("extract_start", files=len(members), uncompressed_bytes=needed)
71
+ for index, member in enumerate(members, 1):
72
+ source.extract(member, stage) # ZipFile validates CRC as each file is read.
73
+ if index % 2000 == 0:
74
+ emit("extract_progress", done=index, total=len(members))
75
+ write_json(stage / ".extraction.json", receipt)
76
+ stage.rename(destination)
77
+
78
+
79
+ def find_data_root(extracted, threads):
80
+ threads = list(dict.fromkeys(threads))
81
+ for thread in threads:
82
+ name = PurePosixPath(thread)
83
+ if name.is_absolute() or ".." in name.parts:
84
+ raise ValueError("Unsafe task path")
85
+ candidates = [extracted] + sorted(path for path in extracted.iterdir() if path.is_dir())
86
+ # Discover the optional archive wrapper; prepare() validates every task below it.
87
+ probes = threads[:16] + threads[-16:]
88
+ matches = [
89
+ root for root in candidates if probes and all((root / thread / "output.xlsx").is_file() for thread in probes)
90
+ ]
91
+ if len(matches) != 1:
92
+ raise ValueError("Cannot uniquely locate the dataset root in the archive")
93
+ return matches[0]
94
+
95
+
96
+ def prepare_inputs(download, extracted, prepared, identity):
97
+ if prepared.exists():
98
+ if read_json(prepared / "node-preparation.json") != identity:
99
+ raise ValueError("Existing prepared data belongs to a different run")
100
+ return
101
+ import pyarrow.parquet as pq
102
+
103
+ from resources_servers.spreadsheet.prepare import prepare
104
+
105
+ parquets = [download / name for name in ("train_hermes.parquet", "test_hermes.parquet")]
106
+ threads = [
107
+ row["reward_model"]["ground_truth"] for parquet in parquets for row in pq.read_table(parquet).to_pylist()
108
+ ]
109
+ data_root = find_data_root(extracted, threads)
110
+ stage = Path(tempfile.mkdtemp(prefix=".prepare-SP06-", dir=prepared.parent))
111
+ count = prepare(parquets, data_root, stage, REVISION)
112
+ write_json(stage / "node-preparation.json", identity)
113
+ write_json(stage / "data-root.json", {"data_root": str(data_root)})
114
+ stage.rename(prepared)
115
+ emit("prepared", tasks=count, data_root=str(data_root))
116
+
117
+
118
+ def qualify_batches(manifest, data_root, batches, engine, batch_size, helper_sha):
119
+ from resources_servers.spreadsheet.qualify import qualify
120
+
121
+ lines = manifest.read_text().splitlines(keepends=True)
122
+ batches.mkdir(exist_ok=True)
123
+ accepted, diagnostics = [], []
124
+ for start in range(0, len(lines), batch_size):
125
+ payload = "".join(lines[start : start + batch_size])
126
+ source_hash = hashlib.sha256(payload.encode()).hexdigest()
127
+ identity = {"input_sha256": source_hash, "engine": engine.version, "helper_sha256": helper_sha}
128
+ final = batches / f"{start:06d}"
129
+ resumed = final.exists()
130
+ if not resumed:
131
+ emit("qualify_batch_start", done=start, total=len(lines))
132
+ stage = Path(tempfile.mkdtemp(prefix=f".{start:06d}-", dir=batches))
133
+ source = stage / "input.jsonl"
134
+ source.write_text(payload)
135
+ qualify(source, data_root, stage / "accepted.jsonl", stage / "report.json", engine)
136
+ write_json(stage / "checkpoint.json", identity)
137
+ stage.rename(final)
138
+ if read_json(final / "checkpoint.json") != identity:
139
+ raise ValueError("Qualification checkpoint contract changed; use a fresh output directory")
140
+ report = read_json(final / "report.json")
141
+ selected = [json.loads(line) for line in (final / "accepted.jsonl").read_text().splitlines()]
142
+ expected_ids = [json.loads(line)["task_id"] for line in payload.splitlines()]
143
+ if (
144
+ report["source_manifest_sha256"] != source_hash
145
+ or report["engine"] != engine.version
146
+ or report["total"] != len(expected_ids)
147
+ or report["qualified"] != len(selected)
148
+ or [task["task_id"] for task in report["tasks"]] != expected_ids
149
+ or [task["task_id"] for task in selected]
150
+ != [task["task_id"] for task in report["tasks"] if task["qualified"]]
151
+ or any(not task["libreoffice_qualified"] for task in selected)
152
+ ):
153
+ raise ValueError("Qualification checkpoint is inconsistent")
154
+ accepted.extend(selected)
155
+ diagnostics.extend(report["tasks"])
156
+ emit("qualify_progress", done=len(diagnostics), total=len(lines), qualified=len(accepted), resumed=resumed)
157
+ return accepted, diagnostics
158
+
159
+
160
+ def publish_results(prepared, accepted, diagnostics, identity):
161
+ destination = prepared / "libreoffice"
162
+ if destination.exists():
163
+ if read_json(destination / "completion.json") != identity:
164
+ raise ValueError("Existing qualification results have a different contract")
165
+ return destination
166
+ stage = Path(tempfile.mkdtemp(prefix=".results-SP06-", dir=prepared))
167
+ (stage / "manifest.qualified.jsonl").write_text("".join(json.dumps(row) + "\n" for row in accepted))
168
+ reasons = dict(Counter(row.get("reason", "qualified") for row in diagnostics))
169
+ write_json(
170
+ stage / "compatibility.json",
171
+ {
172
+ **identity,
173
+ "qualified": len(accepted),
174
+ "total": len(diagnostics),
175
+ "reasons": reasons,
176
+ "tasks": diagnostics,
177
+ },
178
+ )
179
+ allowed = {row["task_id"] for row in accepted}
180
+ for split in ("train", "test"):
181
+ rows = [json.loads(line) for line in (prepared / f"{split}_hermes.jsonl").read_text().splitlines()]
182
+ if any(row["dataset_revision"] != REVISION for row in rows):
183
+ raise ValueError("Dataset and catalog revision mismatch")
184
+ kept = [row for row in rows if row["task_id"] in allowed]
185
+ (stage / f"{split}.qualified.jsonl").write_text(
186
+ "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in kept)
187
+ )
188
+ emit("filtered", split=split, kept=len(kept), excluded=len(rows) - len(kept))
189
+ write_json(stage / "completion.json", identity)
190
+ stage.rename(destination)
191
+ return destination
192
+
193
+
194
+ def run(download, work_root, batch_size):
195
+ from resources_servers.spreadsheet.service.catalog import Catalog
196
+ from resources_servers.spreadsheet.service.engines import LibreOfficePool
197
+
198
+ download, work_root = download.resolve(), work_root.resolve()
199
+ work_root.mkdir(parents=True, exist_ok=True)
200
+ lock = (work_root / "prepare.lock").open("a")
201
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
202
+ temporary = work_root / "tmp"
203
+ temporary.mkdir(exist_ok=True)
204
+ tempfile.tempdir = str(temporary)
205
+ for name, (size, sha) in FILES.items():
206
+ path = download / name
207
+ if path.stat().st_size != size or digest(path) != sha:
208
+ raise ValueError(f"Download checksum mismatch: {name}")
209
+ emit("download_verified", file=name)
210
+ extracted = download / "workbooks"
211
+ extract_archive(download / "spreadsheets.zip", extracted, FILES["spreadsheets.zip"][1])
212
+ helper_sha = digest(Path(__file__))
213
+ prepared = download / "prepared-SP06"
214
+ preparation_identity = {"revision": REVISION, "helper_sha256": helper_sha}
215
+ prepare_inputs(download, extracted, prepared, preparation_identity)
216
+ data_root = Path(read_json(prepared / "data-root.json")["data_root"])
217
+ manifest = prepared / "manifest.unqualified.jsonl"
218
+ profile = Path(tempfile.mkdtemp(prefix="workers-", dir=work_root))
219
+ engine = LibreOfficePool(profile, workers=1, timeout=120)
220
+ try:
221
+ engine.probe()
222
+ emit("engine_ready", version=engine.version)
223
+ accepted, diagnostics = qualify_batches(
224
+ manifest, data_root, prepared / "qualification-batches", engine, batch_size, helper_sha
225
+ )
226
+ identity = {
227
+ "source_manifest_sha256": digest(manifest),
228
+ "engine": engine.version,
229
+ "dataset_revision": REVISION,
230
+ "helper_sha256": helper_sha,
231
+ "data_root": str(data_root),
232
+ }
233
+ result = publish_results(prepared, accepted, diagnostics, identity)
234
+ finally:
235
+ engine.close()
236
+ # Recheck original seed/oracle hashes, qualification flags and nonempty catalog.
237
+ catalog = Catalog(result / "manifest.qualified.jsonl", data_root)
238
+ emit(
239
+ "SP06_DATASET_READY",
240
+ qualified=len(catalog.tasks),
241
+ total=len(diagnostics),
242
+ data_root=str(data_root),
243
+ results=str(result),
244
+ )
245
+
246
+
247
+ def main():
248
+ parser = argparse.ArgumentParser(description=__doc__)
249
+ parser.add_argument("--download-root", type=Path, required=True)
250
+ parser.add_argument("--work-root", type=Path, required=True, help="Node-local storage for LO profiles and scratch")
251
+ parser.add_argument("--batch-size", type=int, default=25)
252
+ args = parser.parse_args()
253
+ if not 1 <= args.batch_size <= 1000:
254
+ parser.error("batch-size must be between 1 and 1000")
255
+
256
+ def interrupted(_signum, _frame):
257
+ raise KeyboardInterrupt
258
+
259
+ signal.signal(signal.SIGTERM, interrupted)
260
+ run(args.download_root, args.work_root, args.batch_size)
261
+
262
+
263
+ if __name__ == "__main__":
264
+ main()