File size: 12,469 Bytes
6aa6c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Create-only official-source deployment; no historical private asset manifest.

The checked-in asset inventory comes from the official Hugging Face Git/LFS
tree, not from an operator's local files. Existing assets are reused only after
their bytes match that inventory. Preparation never launches Isaac or accepts
its licence, and never edits the supplied source, dependencies or asset tree.
"""
from __future__ import annotations

import argparse
import io
import json
import re
from pathlib import Path
import subprocess
import tarfile

from benchmarks.simBenchmarks.RoboDojo.environment.reference_eef_runtime import (
    VERSIONS, canonical_digest, git, inventory, pins, safe_relative, sha,
    verify_layouts, verify_rows,
)

SCHEMA = "starvla-rsi.robodojo-official-runtime/v1"
PROTOCOL = "robodojo-official-hf91f76c28-rgb-proprio28-eef16-feedback-v1"
ASSET_REPOSITORY = "RoboDojo-Benchmark/RoboDojo"
ASSET_REVISION = "91f76c28d93dd20c5fa46ce6a5a1d96a4f384acd"
ASSET_GIT_TREE = "c83388f8d8300ad7bf09f5970e7822f024c4d4cd"
ASSET_INVENTORY_SHA256 = "2737e6458b05286210587a15023176845376ffbc02def02ab58716e28cbc487b"
ASSET_FILE = Path(__file__).with_name("official_assets.json")
DEPENDENCIES = {
    "isaaclab": ("https://github.com/yuechen0614/IsaacLab.git", "afca7b09d60d8beb9c1cb28b43066499940b969b"),
    "curobo": ("https://github.com/yuechen0614/curobo.git", "d17b54ce32cba095c0b000c4c58777075d11de0e"),
}
OFFICIAL_TASKS = ("classify_objects", "stack_bowls")


def task_layout_rows(task: str) -> list[dict]:
    """Bind exact numbered candidate names to the official Git/LFS inventory.

    No layout JSON is parsed. Candidate count is independent of eval_num.
    """
    if task not in OFFICIAL_TASKS:
        raise ValueError("unsupported official RoboDojo task")
    pattern = re.compile(rf"Eval_Layout/RoboDojo/arx_x5/0/{re.escape(task)}_\d+\.json")
    rows = [{"name": row["path"].rsplit("/", 1)[1], "bytes": row["bytes"], "sha256": row["sha256"]}
            for row in asset_rows() if pattern.fullmatch(row["path"])]
    rows.sort(key=lambda row: int(row["name"].rsplit("_", 1)[1][:-5]))
    if not rows or [r["name"] for r in rows] != [f"{task}_{i}.json" for i in range(len(rows))]:
        raise ValueError("official task layout names are not a contiguous native schedule")
    return rows


def official_task_spec(task: str) -> dict:
    from benchmarks.simBenchmarks.RoboDojo.bench_server.protocol.task_catalog import task_spec
    spec = task_spec(task)
    rows = task_layout_rows(task)
    if spec["layout_binding"]["inventory_count"] != len(rows):
        raise ValueError("official task catalog candidate count differs from pinned assets")
    if task == "stack_bowls" and spec["layout_binding"] != {
            "inventory_count": len(rows), "id": "official-hf91f76c28-stack-bowls",
            "snapshot_sha256": sha(ASSET_FILE)}:
        raise ValueError("official task catalog and asset snapshot differ")
    return spec


def verify_task_layouts(source: Path, task: str) -> list[dict]:
    """Hash selected task files without interpreting private reset contents."""
    expected = task_layout_rows(task)
    directory = source / "Assets/Eval_Layout/RoboDojo/arx_x5/0"
    actual_names = sorted(p.name for p in directory.iterdir()
                          if re.fullmatch(rf"{re.escape(task)}_\d+\.json", p.name))
    if actual_names != sorted(row["name"] for row in expected):
        raise ValueError("official task layout candidate set changed")
    for row in expected:
        path = directory / row["name"]
        if path.is_symlink() or not path.is_file() or path.stat().st_size != row["bytes"] or sha(path) != row["sha256"]:
            raise ValueError("official task layout bytes changed")
    return expected


def asset_rows() -> list[dict]:
    rows = json.loads(ASSET_FILE.read_text())
    if canonical_digest(rows) != ASSET_INVENTORY_SHA256:
        raise ValueError("official HF asset inventory changed")
    return rows


def verify_asset_rows(root: Path, rows: list[dict]) -> None:
    # Path sorts components (Water/ before Water.mdl); the HF inventory sorts
    # complete POSIX names (Water.mdl before Water/). Compare canonical order
    # without changing either the required file set or any content hash.
    actual = sorted(inventory(root), key=lambda row: row["path"])
    if actual != rows:
        raise ValueError("official asset file inventory or bytes changed")


def _canonical(path: Path) -> Path:
    if not path.is_absolute() or path.resolve() != path or path.is_symlink():
        raise ValueError("official runtime paths must be canonical")
    return path


def verify_dependencies(document: dict) -> None:
    for name, (_, revision) in DEPENDENCIES.items():
        root = _canonical(Path(document[name + "_root"]))
        if (Path(git(root, "rev-parse", "--show-toplevel")) != root
                or git(root, "rev-parse", "HEAD") != revision
                or git(root, "status", "--porcelain", "--untracked-files=all")):
            raise ValueError(f"official {name} requires the clean pinned upstream checkout")
        verify_rows(root, document[name + "_files"], exclude=(".git",))
    for name in ("python", "recording_support", "asset_root"):
        _canonical(Path(document[name]))
    if not Path(document["python"]).is_file():
        raise ValueError("official native interpreter missing")
    verify_rows(Path(document["recording_support"]), document["recording_support_files"])


def worker_pythonpath(document: dict) -> list[str]:
    isaac = Path(document["isaaclab_root"])
    return [document["recording_support"],
            *(str(isaac / "source" / name) for name in
              ("isaaclab", "isaaclab_assets", "isaaclab_tasks", "isaaclab_mimic", "isaaclab_rl")),
            document["curobo_root"]]


def verify_import_locations(document: dict) -> None:
    """Reject editable-package paths that resolve to a different installation."""
    import importlib.util
    expected = {"isaaclab": Path(document["isaaclab_root"]) / "source/isaaclab/isaaclab",
                "curobo": Path(document["curobo_root"]) / "curobo",
                "numpy": Path(document["recording_support"]) / "numpy",
                "av": Path(document["recording_support"]) / "av"}
    for name, root in expected.items():
        spec = importlib.util.find_spec(name)
        if spec is None or not spec.origin or not Path(spec.origin).resolve().is_relative_to(root):
            raise ValueError(f"{name} import resolves outside the declared official runtime")


def load_runtime(manifest: Path, expected_sha256: str) -> dict:
    if (manifest.is_symlink() or not manifest.is_file() or manifest.stat().st_size > 32 * 1024 * 1024
            or sha(manifest) != expected_sha256):
        raise ValueError("official runtime manifest hash or file changed")
    value = json.loads(manifest.read_text())
    expected = {"schema": SCHEMA, "protocol": PROTOCOL,
                "native_revision": pins()["native_revision"], "versions": VERSIONS,
                "asset_repository": ASSET_REPOSITORY, "asset_revision": ASSET_REVISION,
                "asset_git_tree": ASSET_GIT_TREE, "asset_inventory_sha256": ASSET_INVENTORY_SHA256,
                "dependency_patches": {}, "historical_reference_equivalent": False}
    if any(value.get(key) != item for key, item in expected.items()):
        raise ValueError("official deployment identity changed")
    if value.get("asset_files") != asset_rows():
        raise ValueError("official deployment asset inventory changed")
    return value


def verify_runtime(manifest: Path, expected_sha256: str) -> dict:
    value = load_runtime(manifest, expected_sha256)
    source = manifest.parent.resolve() / "RoboDojo"
    verify_rows(source, value["source_files"], exclude=("Assets",))
    for row in pins()["source_files"]:
        if sha(source / row["path"]) != row["sha256"]:
            raise ValueError(f"official native source changed: {row['path']}")
    assets = _canonical(Path(value["asset_root"]))
    if not (source / "Assets").is_symlink() or (source / "Assets").resolve() != assets:
        raise ValueError("official external asset binding changed")
    verify_asset_rows(assets, asset_rows())
    verify_layouts(source)
    verify_dependencies(value)
    return value


def prepare(*, native_repository: Path, assets: Path, runtime_root: Path,
            python: Path, isaaclab_root: Path, curobo_root: Path, recording_support: Path) -> dict:
    runtime_root = runtime_root.absolute()
    if runtime_root.exists() or runtime_root.is_symlink() or not runtime_root.parent.is_dir():
        raise ValueError("official deployment must use a new directory under an existing parent")
    expected = pins()
    value = {"schema": SCHEMA, "protocol": PROTOCOL, "native_revision": expected["native_revision"],
             "native_source_url": "https://github.com/RoboDojo-Benchmark/RoboDojo.git",
             "versions": VERSIONS, "asset_repository": ASSET_REPOSITORY, "asset_revision": ASSET_REVISION,
             "asset_git_tree": ASSET_GIT_TREE, "asset_inventory_sha256": ASSET_INVENTORY_SHA256,
             "asset_files": asset_rows(), "asset_root": str(assets.resolve()),
             "python": str(python.resolve()), "recording_support": str(recording_support.resolve()),
             "recording_support_files": inventory(recording_support.resolve()),
             "dependency_patches": {}, "historical_reference_equivalent": False,
             "native_execution": False, "external_assets": True,
             "limitations": ["Native GPU readiness and renderer parity require separate diagnostics.",
                 "External asset bytes are verified before and after reset; this is not an OS access sandbox."]}
    for name, path in (("isaaclab", isaaclab_root), ("curobo", curobo_root)):
        root = path.resolve()
        value[name + "_root"] = str(root)
        value[name + "_files"] = inventory(root, exclude=(".git",))
        value[name + "_source"] = dict(zip(("url", "revision"), DEPENDENCIES[name]))
    verify_dependencies(value)
    verify_asset_rows(assets.resolve(), value["asset_files"])
    payload = subprocess.check_output(["git", "-C", str(native_repository), "archive", expected["native_revision"]])
    runtime_root.mkdir(mode=0o700)
    source = runtime_root / "RoboDojo"
    source.mkdir()
    with tarfile.open(fileobj=io.BytesIO(payload)) as bundle:
        for entry in bundle:
            target = source / safe_relative(entry.name.rstrip("/"))
            if entry.isdir():
                target.mkdir(parents=True, exist_ok=True)
            elif entry.isfile():
                target.parent.mkdir(parents=True, exist_ok=True)
                with bundle.extractfile(entry) as src, target.open("xb") as dst:
                    dst.write(src.read())
                target.chmod(entry.mode & 0o755)
            else:
                raise ValueError("native archive contains a link or special file")
    value["source_files"] = inventory(source)
    (source / "Assets").symlink_to(assets.resolve(), target_is_directory=True)
    manifest = runtime_root / "runtime_manifest.json"
    with manifest.open("x") as stream:
        json.dump(value, stream, indent=2, allow_nan=False)
        stream.write("\n")
    digest = sha(manifest)
    verify_runtime(manifest, digest)
    return {"runtime_manifest": str(manifest), "runtime_manifest_sha256": digest,
            "deployment_track": "official", "protocol": PROTOCOL, "native_execution": False}


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest="command", required=True)
    build = sub.add_parser("prepare")
    for name in ("native-repository", "assets", "runtime-root", "python", "isaaclab-root", "curobo-root", "recording-support"):
        build.add_argument("--" + name, required=True, type=Path)
    check = sub.add_parser("verify")
    check.add_argument("--manifest", required=True, type=Path)
    check.add_argument("--sha256", required=True)
    args = vars(parser.parse_args(argv))
    command = args.pop("command")
    result = prepare(**args) if command == "prepare" else verify_runtime(args["manifest"], args["sha256"])
    if command == "verify":
        result = {"verified": True, "protocol": result["protocol"], "native_execution": False}
    print(json.dumps(result, indent=2))
    return 0


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