File size: 29,813 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
"""Server-side preparation of the model-independent EVI core v2 data.

This command intentionally stops after building the local release and training
inputs.  It never uploads to Hugging Face and never launches a GPU training
run.  The checked-in server runbook continues from its output.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tarfile
import urllib.error
import urllib.request
import zipfile
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import IO, Any

import yaml

from ..atomic_io import atomic_write_json
from ..paths import repo_root

_CHUNK_BYTES = 8 * 1024 * 1024
_PROGRESS_BYTES = 256 * 1024 * 1024


class ServerPreparationError(RuntimeError):
    """The server cannot safely complete the registered preparation plan."""


@dataclass(frozen=True)
class ServerLayout:
    root: Path
    downloads: Path
    raw: Path
    tools: Path
    plotqa_release: Path
    release: Path
    training_inputs: Path
    gqa_image_cache: Path
    clevr_dataset_gen: Path
    blender_root: Path


def _mapping(value: Any, label: str) -> Mapping[str, Any]:
    if not isinstance(value, Mapping):
        raise ServerPreparationError(f"{label} must be a mapping")
    return value


def _load_json(path: Path) -> dict[str, Any]:
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise ServerPreparationError(f"cannot read {path}: {exc}") from exc
    return dict(_mapping(value, str(path)))


def _load_yaml(path: Path) -> dict[str, Any]:
    try:
        value = yaml.safe_load(path.read_text(encoding="utf-8"))
    except (OSError, yaml.YAMLError) as exc:
        raise ServerPreparationError(f"cannot read {path}: {exc}") from exc
    return dict(_mapping(value, str(path)))


def _git_head(root: Path) -> str:
    completed = _run(
        ["git", "rev-parse", "HEAD"],
        cwd=root,
        capture=True,
    )
    revision = completed.stdout.strip()
    if len(revision) != 40 or any(char not in "0123456789abcdef" for char in revision):
        raise ServerPreparationError(f"repository HEAD is not a full Git revision: {revision!r}")
    return revision


def _verify_clean_master(root: Path, expected_commit: str) -> None:
    if _git_head(root) != expected_commit:
        raise ServerPreparationError("--code-commit differs from the current repository HEAD")
    branch = _run(
        ["git", "branch", "--show-current"],
        cwd=root,
        capture=True,
    ).stdout.strip()
    if branch != "master":
        raise ServerPreparationError(f"server preparation requires master, found {branch!r}")
    dirty = _run(
        ["git", "status", "--porcelain"],
        cwd=root,
        capture=True,
    ).stdout.strip()
    if dirty:
        raise ServerPreparationError("server preparation requires a clean Git checkout")


def _layout(workspace: Path, published: Mapping[str, Any], code_commit: str) -> ServerLayout:
    extracted = _mapping(published["extracted_artifacts"], "extracted_artifacts")
    release_relative = _safe_relative_path(
        str(extracted["release_directory"]),
        label="PlotQA seed release_directory",
    )
    return ServerLayout(
        root=workspace,
        downloads=workspace / "downloads",
        raw=workspace / "raw",
        tools=workspace / "tools",
        plotqa_release=workspace / "plotqa-seed" / release_relative,
        release=workspace / "releases" / f"evi-core-v2-{code_commit[:12]}",
        training_inputs=workspace / "training-inputs" / f"evi-core-v2-{code_commit[:12]}",
        gqa_image_cache=workspace / "cache" / "gqa-selected-images",
        clevr_dataset_gen=workspace / "tools" / "clevr-dataset-gen",
        blender_root=workspace / "tools" / "blender-2.79b",
    )


def _safe_relative_path(value: str, *, label: str) -> Path:
    path = PurePosixPath(value)
    if path.is_absolute() or not path.parts or any(part in {"", ".", ".."} for part in path.parts):
        raise ServerPreparationError(f"{label} is not a safe relative path: {value!r}")
    return Path(*path.parts)


def _assert_workspace_outside_repo(workspace: Path, root: Path) -> None:
    resolved = workspace.resolve()
    repository = root.resolve()
    try:
        resolved.relative_to(repository)
    except ValueError:
        return
    raise ServerPreparationError(
        f"data workspace must be outside the Git checkout so data cannot be committed: {resolved}"
    )


def _run(
    command: Sequence[str],
    *,
    cwd: Path | None = None,
    env: Mapping[str, str] | None = None,
    capture: bool = False,
) -> subprocess.CompletedProcess[str]:
    try:
        completed = subprocess.run(
            list(command),
            cwd=cwd,
            env=dict(env) if env is not None else None,
            check=False,
            text=True,
            capture_output=capture,
        )
    except OSError as exc:
        raise ServerPreparationError(f"cannot run {command[0]}: {exc}") from exc
    if completed.returncode != 0:
        details = (completed.stderr or completed.stdout or "").strip()
        if len(details) > 2000:
            details = details[-2000:]
        raise ServerPreparationError(
            f"command failed ({completed.returncode}): {' '.join(command)}"
            + (f"\n{details}" if details else "")
        )
    return completed


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        while chunk := handle.read(_CHUNK_BYTES):
            digest.update(chunk)
    return digest.hexdigest()


def _verify_download(
    path: Path,
    *,
    expected_bytes: int,
    expected_sha256: str,
    label: str,
) -> None:
    if not path.is_file():
        raise ServerPreparationError(f"{label} is missing: {path}")
    actual_bytes = path.stat().st_size
    if actual_bytes != expected_bytes:
        raise ServerPreparationError(
            f"{label} byte count differs: {actual_bytes} != {expected_bytes}"
        )
    actual_sha256 = _sha256(path)
    if actual_sha256 != expected_sha256:
        raise ServerPreparationError(
            f"{label} download checksum differs: {actual_sha256} != {expected_sha256}"
        )


def _download(
    *,
    url: str,
    destination: Path,
    expected_bytes: int,
    expected_sha256: str,
    label: str,
) -> Path:
    if destination.is_file():
        _verify_download(
            destination,
            expected_bytes=expected_bytes,
            expected_sha256=expected_sha256,
            label=label,
        )
        print(f"[prepare] reuse {label}: {destination}", file=sys.stderr, flush=True)
        return destination
    destination.parent.mkdir(parents=True, exist_ok=True)
    partial = destination.with_name(destination.name + ".part")
    request = urllib.request.Request(
        url,
        headers={"User-Agent": "explicit-learning-server-prepare/1"},
    )
    written = 0
    next_progress = _PROGRESS_BYTES
    try:
        with urllib.request.urlopen(request, timeout=120) as response, partial.open("wb") as output:
            while chunk := response.read(_CHUNK_BYTES):
                output.write(chunk)
                written += len(chunk)
                if written >= next_progress:
                    print(
                        f"[prepare] {label}: {written / (1024**3):.2f} GiB",
                        file=sys.stderr,
                        flush=True,
                    )
                    next_progress += _PROGRESS_BYTES
        os.replace(partial, destination)
    except (OSError, urllib.error.URLError) as exc:
        partial.unlink(missing_ok=True)
        raise ServerPreparationError(f"cannot download {label}: {exc}") from exc
    _verify_download(
        destination,
        expected_bytes=expected_bytes,
        expected_sha256=expected_sha256,
        label=label,
    )
    return destination


def _download_plotqa_seed(
    *,
    published: Mapping[str, Any],
    destination_root: Path,
) -> Path:
    repository = _mapping(published["dataset_repository"], "dataset_repository")
    bundle = _mapping(published["bundle"], "bundle")
    relative = _safe_relative_path(str(bundle["path_in_repo"]), label="HF bundle path")
    destination_root.mkdir(parents=True, exist_ok=True)
    try:
        from huggingface_hub import hf_hub_download
    except ImportError as exc:
        raise ServerPreparationError(
            "huggingface-hub is required; install requirements/data.in"
        ) from exc
    try:
        downloaded = Path(
            hf_hub_download(
                repo_id=str(repository["repo_id"]),
                repo_type="dataset",
                filename=relative.as_posix(),
                revision=str(repository["revision"]),
                token=os.environ.get("HF_TOKEN"),
                local_dir=destination_root,
            )
        )
    except Exception as exc:
        raise ServerPreparationError(f"cannot download private PlotQA seed: {exc}") from exc
    _verify_download(
        downloaded,
        expected_bytes=int(bundle["bytes"]),
        expected_sha256=str(bundle["sha256"]),
        label="private PlotQA seed bundle",
    )
    return downloaded


def _write_stream_atomic(source: IO[bytes], destination: Path) -> None:
    destination.parent.mkdir(parents=True, exist_ok=True)
    partial = destination.with_name(destination.name + ".part")
    try:
        with partial.open("wb") as output:
            shutil.copyfileobj(source, output, length=_CHUNK_BYTES)
        os.replace(partial, destination)
    except OSError:
        partial.unlink(missing_ok=True)
        raise


def _extract_zip_members(
    archive: Path,
    destination: Path,
    members: Mapping[str, str],
) -> None:
    destination.mkdir(parents=True, exist_ok=True)
    try:
        with zipfile.ZipFile(archive) as source:
            available = set(source.namelist())
            missing = sorted(set(members) - available)
            if missing:
                raise ServerPreparationError(
                    f"{archive.name} is missing required members: {missing}"
                )
            for member_name, output_name in members.items():
                target = destination / _safe_relative_path(output_name, label="ZIP output path")
                info = source.getinfo(member_name)
                if target.is_file() and target.stat().st_size == info.file_size:
                    continue
                with source.open(info) as handle:
                    _write_stream_atomic(handle, target)
    except (OSError, zipfile.BadZipFile) as exc:
        raise ServerPreparationError(f"cannot extract {archive}: {exc}") from exc


def _extract_tar_prefix(archive: Path, destination: Path, prefix: str) -> None:
    safe_prefix = PurePosixPath(prefix)
    if safe_prefix.is_absolute() or ".." in safe_prefix.parts:
        raise ServerPreparationError(f"unsafe TAR prefix: {prefix!r}")
    found = False
    try:
        with tarfile.open(archive, mode="r:*") as source:
            for member in source:
                member_path = PurePosixPath(member.name)
                if member_path == safe_prefix:
                    relative = PurePosixPath(".")
                else:
                    try:
                        relative = member_path.relative_to(safe_prefix)
                    except ValueError:
                        continue
                found = True
                target = destination / Path(*relative.parts)
                if member.isdir():
                    target.mkdir(parents=True, exist_ok=True)
                    continue
                if not member.isfile():
                    raise ServerPreparationError(
                        f"unsupported link/device in PlotQA seed archive: {member.name}"
                    )
                handle = source.extractfile(member)
                if handle is None:
                    raise ServerPreparationError(f"cannot read TAR member: {member.name}")
                with handle:
                    _write_stream_atomic(handle, target)
    except (OSError, tarfile.TarError) as exc:
        raise ServerPreparationError(f"cannot extract {archive}: {exc}") from exc
    if not found:
        raise ServerPreparationError(f"PlotQA seed archive has no {prefix!r} subtree")


def _extract_tar_all(archive: Path, destination: Path) -> None:
    try:
        with tarfile.open(archive, mode="r:*") as source:
            for member in source:
                relative = _safe_relative_path(member.name, label="TAR member")
                target = destination / relative
                if member.isdir():
                    target.mkdir(parents=True, exist_ok=True)
                    continue
                if not member.isfile():
                    raise ServerPreparationError(
                        f"unsupported link/device in tool archive: {member.name}"
                    )
                if target.is_file() and target.stat().st_size == member.size:
                    continue
                handle = source.extractfile(member)
                if handle is None:
                    raise ServerPreparationError(f"cannot read TAR member: {member.name}")
                with handle:
                    _write_stream_atomic(handle, target)
    except (OSError, tarfile.TarError) as exc:
        raise ServerPreparationError(f"cannot extract {archive}: {exc}") from exc


def _prepare_repository(
    *,
    destination: Path,
    url: str,
    revision: str,
) -> None:
    if (destination / ".git").is_dir():
        head = _git_head(destination)
        if head == revision:
            return
        _run(["git", "fetch", "--depth", "1", "origin", revision], cwd=destination)
        _run(["git", "checkout", "--detach", revision], cwd=destination)
    elif destination.exists():
        raise ServerPreparationError(
            f"official CLEVR tool path exists but is not a Git checkout: {destination}"
        )
    else:
        destination.parent.mkdir(parents=True, exist_ok=True)
        _run(["git", "clone", "--no-checkout", url, str(destination)])
        _run(["git", "checkout", "--detach", revision], cwd=destination)
    if _git_head(destination) != revision:
        raise ServerPreparationError("official CLEVR generator did not resolve to pinned revision")


def _blender_environment(runtime_library_dir: Path | None) -> dict[str, str]:
    environment = dict(os.environ)
    if runtime_library_dir is not None:
        current = environment.get("LD_LIBRARY_PATH")
        environment["LD_LIBRARY_PATH"] = (
            f"{runtime_library_dir}{os.pathsep}{current}" if current else str(runtime_library_dir)
        )
    return environment


def _check_blender(executable: Path, runtime_library_dir: Path | None) -> None:
    if not executable.is_file():
        raise ServerPreparationError(f"Blender executable is missing: {executable}")
    try:
        completed = subprocess.run(
            [str(executable), "--version"],
            env=_blender_environment(runtime_library_dir),
            check=False,
            text=True,
            capture_output=True,
            timeout=30,
        )
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise ServerPreparationError(f"cannot execute Blender 2.79b: {exc}") from exc
    if completed.returncode != 0:
        details = (completed.stderr or completed.stdout or "").strip()[-2000:]
        raise ServerPreparationError(
            "Blender 2.79b runtime check failed. Install libglu1-mesa or pass "
            f"--blender-runtime-library-dir. Details: {details}"
        )


def _validate_existing_training_inputs(path: Path) -> bool:
    manifest_path = path / "manifest.json"
    if not manifest_path.is_file():
        return False
    manifest = _load_json(manifest_path)
    expected = {
        "kind": "certified_model_independent_training_inputs",
        "trained": False,
        "group_count": 12000,
        "view_count": 46000,
        "comparison_slot_count": 46000,
        "full_only_raw_rows": 12000,
        "full_plus_intervention_raw_rows": 46000,
        "admission_mode": "structural_no_content_hash_replay",
        "reasoning_vlm_calls": 0,
        "per_example_human_decisions": 0,
    }
    if any(manifest.get(key) != value for key, value in expected.items()):
        return False
    return all(
        (path / name).is_file()
        for name in (
            "comparison-slots.jsonl",
            "full-only.raw.jsonl",
            "full-plus-intervention.raw.jsonl",
        )
    )


def _plan(
    *,
    layout: ServerLayout,
    published: Mapping[str, Any],
    resources: Mapping[str, Any],
    code_commit: str,
) -> dict[str, Any]:
    repository = _mapping(published["dataset_repository"], "dataset_repository")
    gqa = _mapping(_mapping(resources["structured_sources"], "structured_sources")["gqa"], "gqa")
    clevr = _mapping(
        _mapping(resources["structured_sources"], "structured_sources")["clevr"],
        "clevr",
    )
    return {
        "contract": "server_prepare_evi_core_v2",
        "code_commit": code_commit,
        "workspace": str(layout.root),
        "inputs": {
            "plotqa_seed": {
                "repo_id": repository["repo_id"],
                "revision": repository["revision"],
                "groups": 4000,
            },
            "gqa": {
                "revision": gqa["revision"],
                "groups": 6000,
            },
            "clevr": {
                "revision": clevr["revision"],
                "groups": 5000,
                "renderer": "official Blender 2.79b Cycles",
            },
        },
        "outputs": {
            "release": str(layout.release),
            "training_inputs": str(layout.training_inputs),
            "train_groups": 12000,
            "validation_groups": 2000,
            "certified_eval_groups": 1000,
            "views": 58000,
            "training_slots": 46000,
        },
        "reasoning_vlm_calls": 0,
        "per_example_human_decisions": 0,
        "content_hash_replay_required": False,
        "hf_upload_performed": False,
    }


def prepare_server_data(args: argparse.Namespace) -> dict[str, Any]:
    root = repo_root()
    workspace = args.workspace.resolve()
    _assert_workspace_outside_repo(workspace, root)
    resources = _load_yaml(root / "configs" / "resources.yaml")
    published = _load_json(root / "configs" / "published_release.json")
    code_commit = args.code_commit or _git_head(root)
    layout = _layout(workspace, published, code_commit)
    plan = _plan(
        layout=layout,
        published=published,
        resources=resources,
        code_commit=code_commit,
    )
    if args.dry_run:
        return plan
    _verify_clean_master(root, code_commit)

    layout.root.mkdir(parents=True, exist_ok=True)
    structured = _mapping(resources["structured_sources"], "structured_sources")
    gqa = _mapping(structured["gqa"], "structured_sources.gqa")
    gqa_archives = _mapping(gqa["source_archives"], "gqa.source_archives")
    clevr = _mapping(structured["clevr"], "structured_sources.clevr")
    clevr_archive = _mapping(clevr["no_images_archive"], "clevr.no_images_archive")
    renderer = _mapping(clevr["official_renderer"], "clevr.official_renderer")
    repositories = _mapping(resources["repositories"], "repositories")
    generator = _mapping(
        repositories[str(renderer["repository"])],
        "repositories.clevr_dataset_gen",
    )

    print("[prepare] download/extract pinned PlotQA seed", file=sys.stderr, flush=True)
    plotqa_archive = _download_plotqa_seed(
        published=published,
        destination_root=layout.downloads / "plotqa-seed",
    )
    if not (layout.plotqa_release / "manifest.json").is_file():
        release_prefix = str(
            _mapping(published["extracted_artifacts"], "extracted_artifacts")["release_directory"]
        )
        _extract_tar_prefix(
            plotqa_archive,
            layout.plotqa_release,
            release_prefix,
        )

    print("[prepare] download/extract official GQA annotations", file=sys.stderr, flush=True)
    gqa_question_spec = _mapping(gqa_archives["questions"], "GQA questions archive")
    gqa_scene_spec = _mapping(gqa_archives["scene_graphs"], "GQA scene archive")
    gqa_questions = _download(
        url=str(gqa_question_spec["url"]),
        destination=layout.downloads / "gqa" / str(gqa_question_spec["filename"]),
        expected_bytes=int(gqa_question_spec["bytes"]),
        expected_sha256=str(gqa_question_spec["sha256"]),
        label="GQA 1.2 questions",
    )
    gqa_scenes = _download(
        url=str(gqa_scene_spec["url"]),
        destination=layout.downloads / "gqa" / str(gqa_scene_spec["filename"]),
        expected_bytes=int(gqa_scene_spec["bytes"]),
        expected_sha256=str(gqa_scene_spec["sha256"]),
        label="GQA 1.2 scene graphs",
    )
    gqa_root = layout.raw / "gqa"
    _extract_zip_members(
        gqa_questions,
        gqa_root,
        {
            "train_balanced_questions.json": "train_balanced_questions.json",
            "val_balanced_questions.json": "val_balanced_questions.json",
            "readme.txt": "questions-readme.txt",
        },
    )
    _extract_zip_members(
        gqa_scenes,
        gqa_root,
        {
            "train_sceneGraphs.json": "train_sceneGraphs.json",
            "val_sceneGraphs.json": "val_sceneGraphs.json",
            "readme.txt": "scene-graphs-readme.txt",
        },
    )

    print("[prepare] download/extract official CLEVR annotations", file=sys.stderr, flush=True)
    clevr_zip = _download(
        url=str(clevr_archive["url"]),
        destination=layout.downloads / "clevr" / str(clevr_archive["filename"]),
        expected_bytes=int(clevr_archive["bytes"]),
        expected_sha256=str(clevr_archive["sha256"]),
        label="CLEVR v1 no-images annotations",
    )
    clevr_root = layout.raw / "clevr" / "CLEVR_v1.0"
    _extract_zip_members(
        clevr_zip,
        clevr_root,
        {
            "CLEVR_v1.0/questions/CLEVR_train_questions.json": (
                "questions/CLEVR_train_questions.json"
            ),
            "CLEVR_v1.0/questions/CLEVR_val_questions.json": ("questions/CLEVR_val_questions.json"),
            "CLEVR_v1.0/scenes/CLEVR_train_scenes.json": ("scenes/CLEVR_train_scenes.json"),
            "CLEVR_v1.0/scenes/CLEVR_val_scenes.json": "scenes/CLEVR_val_scenes.json",
            "CLEVR_v1.0/LICENSE.txt": "LICENSE.txt",
        },
    )

    print("[prepare] install pinned official CLEVR renderer", file=sys.stderr, flush=True)
    _prepare_repository(
        destination=layout.clevr_dataset_gen,
        url=str(generator["url"]),
        revision=str(generator["revision"]),
    )
    blender_archive = _download(
        url=str(renderer["blender_url"]),
        destination=layout.downloads / "clevr" / str(renderer["blender_archive"]),
        expected_bytes=int(renderer["blender_archive_bytes"]),
        expected_sha256=str(renderer["blender_archive_sha256"]),
        label="Blender 2.79b Linux archive",
    )
    blender_executable = layout.blender_root / "blender"
    if not blender_executable.is_file():
        _extract_tar_all(blender_archive, layout.tools)
    runtime_library_dir = (
        args.blender_runtime_library_dir.resolve()
        if args.blender_runtime_library_dir is not None
        else layout.blender_root / "lib"
    )
    _check_blender(blender_executable, runtime_library_dir)

    if layout.release.exists():
        _run(
            [
                sys.executable,
                "-m",
                "explicit_learning.cli.data",
                "validate-evi-core-release",
                "--release",
                str(layout.release),
            ],
            cwd=root,
        )
        print(f"[prepare] reuse validated release: {layout.release}", file=sys.stderr)
    else:
        print("[prepare] build PlotQA+GQA+CLEVR EVI core release", file=sys.stderr, flush=True)
        _run(
            [
                sys.executable,
                "-m",
                "explicit_learning.cli.data",
                "build-evi-core-release",
                "--plotqa-release",
                str(layout.plotqa_release),
                "--gqa-train-questions",
                str(gqa_root / "train_balanced_questions.json"),
                "--gqa-train-scene-graphs",
                str(gqa_root / "train_sceneGraphs.json"),
                "--gqa-val-questions",
                str(gqa_root / "val_balanced_questions.json"),
                "--gqa-val-scene-graphs",
                str(gqa_root / "val_sceneGraphs.json"),
                "--gqa-image-cache",
                str(layout.gqa_image_cache),
                "--clevr-train-questions",
                str(clevr_root / "questions" / "CLEVR_train_questions.json"),
                "--clevr-train-scenes",
                str(clevr_root / "scenes" / "CLEVR_train_scenes.json"),
                "--clevr-val-questions",
                str(clevr_root / "questions" / "CLEVR_val_questions.json"),
                "--clevr-val-scenes",
                str(clevr_root / "scenes" / "CLEVR_val_scenes.json"),
                "--clevr-blender-executable",
                str(blender_executable),
                "--clevr-dataset-gen-root",
                str(layout.clevr_dataset_gen),
                "--clevr-blender-runtime-library-dir",
                str(runtime_library_dir),
                "--output",
                str(layout.release),
                "--release-config",
                str(root / "configs" / "release.evi-core-v2.json"),
                "--code-commit",
                code_commit,
                "--workers",
                str(args.workers),
                "--download-workers",
                str(args.download_workers),
            ],
            cwd=root,
        )
        _run(
            [
                sys.executable,
                "-m",
                "explicit_learning.cli.data",
                "validate-evi-core-release",
                "--release",
                str(layout.release),
            ],
            cwd=root,
        )

    if layout.training_inputs.exists():
        if not _validate_existing_training_inputs(layout.training_inputs):
            raise ServerPreparationError(
                f"existing training-input directory is incomplete: {layout.training_inputs}"
            )
        print(
            f"[prepare] reuse validated training inputs: {layout.training_inputs}",
            file=sys.stderr,
        )
    else:
        print("[prepare] build 46K registered training slots", file=sys.stderr, flush=True)
        _run(
            [
                sys.executable,
                "-m",
                "explicit_learning.cli.train",
                "build-training-inputs",
                "--dataset",
                str(layout.release / "train" / "groups.jsonl"),
                "--asset-root",
                str(layout.release),
                "--release-manifest",
                str(layout.release / "manifest.json"),
                "--output-dir",
                str(layout.training_inputs),
                "--code-commit",
                code_commit,
                "--max-slots",
                "46000",
                "--workers",
                str(args.workers),
            ],
            cwd=root,
        )
    if not _validate_existing_training_inputs(layout.training_inputs):
        raise ServerPreparationError("final training-input validation failed")

    completed = {
        **plan,
        "status": "ready_for_model_dependent_server_steps",
        "release_manifest": str(layout.release / "manifest.json"),
        "training_inputs_manifest": str(layout.training_inputs / "manifest.json"),
    }
    atomic_write_json(layout.root / "server-preparation-summary.json", completed)
    return completed


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="explicit-prepare",
        description=(
            "Download the PlotQA seed and official GQA/CLEVR sources, build the local "
            "EVI core v2 release with official Blender, and create training inputs. "
            "No Hugging Face upload is performed."
        ),
    )
    parser.add_argument("--workspace", type=Path, required=True)
    parser.add_argument("--code-commit")
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--download-workers", type=int, default=24)
    parser.add_argument("--blender-runtime-library-dir", type=Path)
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Print the immutable plan without network, files, rendering, or training.",
    )
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    if args.workers < 1 or args.download_workers < 1:
        print("explicit-prepare: worker counts must be positive", file=sys.stderr)
        return 2
    if args.code_commit is not None and (
        len(args.code_commit) != 40
        or any(char not in "0123456789abcdef" for char in args.code_commit)
    ):
        print("explicit-prepare: --code-commit must be a full lowercase 40-hex", file=sys.stderr)
        return 2
    try:
        result = prepare_server_data(args)
    except ServerPreparationError as exc:
        print(f"explicit-prepare: {exc}", file=sys.stderr)
        return 1
    print(json.dumps(result, sort_keys=True))
    return 0


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