File size: 7,677 Bytes
05d6af6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Validate sf_release before publishing to Hugging Face.

Checks:
  - manifest.jsonl and metadata.json exist and are consistent
  - every required artifact path in the manifest exists on disk
  - optional artifacts are reported but do not fail validation when absent
  - config.json files contain no machine-local absolute paths
  - .gitattributes routes *.pkl through Git LFS

Usage:
    python scripts/validate_release.py
    python scripts/validate_release.py --root /path/to/sf_release --strict
"""

from __future__ import annotations

import argparse
import json
import re
from pathlib import Path
from typing import Any

LOCAL_PATH_RE = re.compile(
    r"(/users/|/oscar/|/scratch/|/home/|[A-Za-z]:\\\\)"
)

REQUIRED_ROW_FLAGS = ("has_config",)
REQUIRED_PATH_KEYS = ("config_path",)
# Instances must carry EITHER a primitive_assembly OR a primitive_assembly_error
# pickle. Failed fits are released for completeness.
ASSEMBLY_OR_ERROR_KEYS = ("primitive_assembly_path", "primitive_assembly_error_path")
OPTIONAL_PATH_KEYS = (
    "primitive_assembly_path",
    "primitive_assembly_eval_path",
    "primitive_assembly_error_path",
    "primitive_assembly_textured_path",
)


def load_manifest(root: Path) -> list[dict[str, Any]]:
    manifest_path = root / "manifest.jsonl"
    if not manifest_path.is_file():
        raise FileNotFoundError(f"Missing {manifest_path}")
    rows: list[dict[str, Any]] = []
    with manifest_path.open() as fh:
        for i, line in enumerate(fh, 1):
            line = line.strip()
            if not line:
                continue
            try:
                rows.append(json.loads(line))
            except json.JSONDecodeError as exc:
                raise ValueError(f"manifest.jsonl line {i}: {exc}") from exc
    return rows


def validate_manifest_paths(root: Path, rows: list[dict[str, Any]]) -> tuple[list[str], list[str]]:
    errors: list[str] = []
    warnings: list[str] = []

    for row in rows:
        inst = row.get("instance_dir", "?")
        for flag in REQUIRED_ROW_FLAGS:
            if not row.get(flag):
                errors.append(f"{inst}: missing required flag {flag}")
        for key in REQUIRED_PATH_KEYS:
            rel = row.get(key)
            if not rel:
                errors.append(f"{inst}: missing {key}")
                continue
            if not (root / rel).is_file():
                errors.append(f"{inst}: file not found: {rel}")

        if not any(row.get(k) for k in ASSEMBLY_OR_ERROR_KEYS):
            errors.append(
                f"{inst}: missing both primitive_assembly_path and primitive_assembly_error_path"
            )

        for key in OPTIONAL_PATH_KEYS:
            rel = row.get(key)
            flag = key.replace("_path", "")
            has_flag = row.get(f"has_{flag}", row.get(key.replace("_path", "").replace("primitive_assembly_", "has_primitive_assembly_")))
            # normalize flag name from path key
            if key == "primitive_assembly_eval_path":
                has_flag = row.get("has_primitive_assembly_eval")
            elif key == "primitive_assembly_error_path":
                has_flag = row.get("has_primitive_assembly_error")
            elif key == "primitive_assembly_textured_path":
                has_flag = row.get("has_primitive_assembly_textured")

            if has_flag and rel and not (root / rel).is_file():
                errors.append(f"{inst}: flagged present but missing: {rel}")
            if not has_flag and rel:
                warnings.append(f"{inst}: {key} set but has_* flag is false")

    return errors, warnings


def validate_metadata(root: Path, rows: list[dict[str, Any]]) -> list[str]:
    errors: list[str] = []
    meta_path = root / "metadata.json"
    if not meta_path.is_file():
        return [f"Missing {meta_path}"]
    with meta_path.open() as fh:
        meta = json.load(fh)
    if meta.get("total_instances") != len(rows):
        errors.append(
            f"metadata total_instances={meta.get('total_instances')} "
            f"!= manifest rows={len(rows)}"
        )
    return errors


def validate_configs(root: Path) -> list[str]:
    errors: list[str] = []
    for cfg in root.rglob("config.json"):
        try:
            data = json.loads(cfg.read_text())
        except json.JSONDecodeError as exc:
            errors.append(f"{cfg}: invalid JSON: {exc}")
            continue
        if not isinstance(data, dict):
            continue
        for key, value in data.items():
            if isinstance(value, str) and LOCAL_PATH_RE.search(value):
                errors.append(f"{cfg}: local path in {key}: {value[:80]}")
    return errors


def validate_gitattributes(root: Path) -> list[str]:
    errors: list[str] = []
    ga = root / ".gitattributes"
    if not ga.is_file():
        return ["Missing .gitattributes"]
    text = ga.read_text()
    if "*.pkl" not in text or "filter=lfs" not in text:
        errors.append(".gitattributes does not route *.pkl through Git LFS")
    return errors


def validate_readme(root: Path) -> list[str]:
    errors: list[str] = []
    readme = root / "README.md"
    if not readme.is_file():
        return ["Missing README.md"]
    head = readme.read_text()[:800]
    if not head.startswith("---"):
        errors.append("README.md missing YAML front matter (---)")
    for token in ("license:", "task_categories:", "tags:"):
        if token not in head:
            errors.append(f"README.md front matter missing `{token}`")
    if "pickle" not in readme.read_text().lower():
        errors.append("README.md should document pickle safety")
    return errors


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    default_root = Path(__file__).resolve().parent.parent
    parser.add_argument("--root", type=Path, default=default_root)
    parser.add_argument(
        "--strict",
        action="store_true",
        help="Treat warnings as errors.",
    )
    parser.add_argument(
        "--skip-config-scan",
        action="store_true",
        help="Skip scanning all config.json files (faster).",
    )
    args = parser.parse_args()
    root = args.root.resolve()

    print(f"Validating release at {root}")
    all_errors: list[str] = []
    all_warnings: list[str] = []

    try:
        rows = load_manifest(root)
        print(f"  manifest rows: {len(rows)}")
    except (FileNotFoundError, ValueError) as exc:
        print(f"FAIL: {exc}")
        raise SystemExit(1) from exc

    all_errors.extend(validate_metadata(root, rows))
    path_errors, path_warnings = validate_manifest_paths(root, rows)
    all_errors.extend(path_errors)
    all_warnings.extend(path_warnings)

    if not args.skip_config_scan:
        print("  scanning config.json files for local paths...")
        all_errors.extend(validate_configs(root))

    all_errors.extend(validate_gitattributes(root))
    all_errors.extend(validate_readme(root))

    for w in all_warnings:
        print(f"WARN: {w}")
    for e in all_errors:
        print(f"ERROR: {e}")

    if all_warnings and args.strict:
        all_errors.extend([f"(strict) {w}" for w in all_warnings])

    if all_errors:
        print(f"\nValidation FAILED ({len(all_errors)} error(s))")
        report = root / "release_report.txt"
        try:
            report.write_text("\n".join(["ERRORS:"] + all_errors + ["", "WARNINGS:"] + all_warnings))
            print(f"Wrote {report}")
        except OSError:
            pass
        raise SystemExit(1)

    print("\nValidation PASSED")
    if all_warnings:
        print(f"  ({len(all_warnings)} warning(s); re-run with --strict to fail on warnings)")


if __name__ == "__main__":
    main()