File size: 10,788 Bytes
0185029
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Fail closed when the OraRL public tree contains release hygiene hazards."""

from __future__ import annotations

import argparse
import os
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, Sequence

DEFAULT_MAX_BYTES = 5 * 1024 * 1024
EVALUATION_JSONL_MAX_BYTES = 64 * 1024 * 1024
_METHOD_TERMS = (
    "".join(("c", "p", "p", "o")),
    "".join(("g", "t", "p", "o")),
    "".join(("build_", "g", "t")),
    "".join(("lu", "ff", "y")),
)
# Benchmark evaluators name upstream annotation fields after ground truth, so
# this prefix is only a tripwire outside the vendored evaluation runtime.
_LEGACY_ORACLE_TERMS = ("".join(("g", "t", "_")),)
_EXCLUDED_TERMS = _METHOD_TERMS + _LEGACY_ORACLE_TERMS
_IGNORED_LOCAL_DIRECTORIES = {".git", "checkpoint"}
_GENERATED_DIRECTORIES = {
    ".nox",
    ".tox",
    ".venv",
    ".mypy_cache",
    ".pytest_cache",
    ".ruff_cache",
    "__pycache__",
    "artifacts",
    "build",
    "cache",
    "checkpoints",
    "dist",
    "htmlcov",
    "logs",
    "outputs",
    "runs",
    "venv",
}
_GENERATED_FILES = {".coverage", "orarl-eval-summary.json"}
_ALLOWED_RELEASE_BINARIES = {
    Path("assets/orarl-data-scaling.gif"),
    Path("assets/orarl-hero.gif"),
    Path("assets/orarl-method.gif"),
    Path("assets/orarl-model-scaling.gif"),
    Path("assets/orarl-teaser.mp4"),
    Path("assets/paper-data-scaling.png"),
    Path("assets/paper-framework.png"),
    Path("assets/paper-model-scaling.png"),
    Path("assets/paper-results.png"),
    Path("orarl.pdf"),
}
_ARTIFACT_SUFFIXES = {
    ".arrow",
    ".avi",
    ".bin",
    ".ckpt",
    ".jsonl",
    ".mkv",
    ".mov",
    ".mp4",
    ".npy",
    ".npz",
    ".parquet",
    ".pt",
    ".pth",
    ".pyc",
    ".safetensors",
    ".so",
    ".webm",
}
_RELEASE_BINARY_FILES = {
    Path("assets/orarl-data-scaling.gif"),
    Path("assets/orarl-hero.gif"),
    Path("assets/orarl-method.gif"),
    Path("assets/orarl-model-scaling.gif"),
    Path("assets/orarl-teaser.mp4"),
    Path("assets/paper-data-scaling.png"),
    Path("assets/paper-framework.png"),
    Path("assets/paper-model-scaling.png"),
    Path("assets/paper-results.png"),
    Path("orarl.pdf"),
}
_PRIVATE_PATH_PATTERNS = (
    re.compile("/(?:" + "|".join(("mnt", "home", "Users")) + r")/[A-Za-z0-9._-]+(?:/[^\s'\"`]+)?"),
    re.compile(
        "/" + "data" + "/(?:" + "|".join(("home", "user", "users")) + r")/"
        r"[A-Za-z0-9._-]+(?:/[^\s'\"`]+)?"
    ),
    re.compile(
        "/(?:" + "|".join(("apd" + "cephfs" + r"[^/\s]*", "jizhi" + "cfs")) + r")(?:/[^\s'\"`]+)?"
    ),
    re.compile("/" + "root" + r"(?:/[^\s'\"`]+)?"),
)
_SECRET_PATTERNS = (
    re.compile(
        r"(?i)\b(?:api[_-]?key|access[_-]?token|auth[_-]?token|password|secret)"
        r"\b\s*[:=]\s*['\"]?[A-Za-z0-9_./+=-]{12,}"
    ),
    re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
    re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}\b"),
    re.compile(r"\bhf_[A-Za-z0-9]{20,}\b"),
    re.compile(r"://[^/\s:@]+:[^@\s/]+@"),
)
_PRIVATE_KEY_MARKER = "".join(("-" * 5, "BEGIN ", "PRIVATE", " KEY", "-" * 5))


@dataclass(frozen=True, slots=True)
class Finding:
    """One release gate failure."""

    path: Path
    reason: str


def _line_number(text: str, index: int) -> int:
    return text.count("\n", 0, index) + 1


def _text_findings(
    path: Path,
    text: str,
    *,
    check_excluded_terms: bool = True,
    allow_ground_truth_names: bool = False,
) -> Iterable[Finding]:
    if check_excluded_terms:
        lowered = text.casefold()
        terms = _METHOD_TERMS if allow_ground_truth_names else _EXCLUDED_TERMS
        for term in terms:
            index = lowered.find(term)
            if index >= 0:
                yield Finding(
                    path,
                    f"excluded method term at line {_line_number(text, index)}",
                )

    for pattern in _PRIVATE_PATH_PATTERNS:
        match = pattern.search(text)
        if match:
            yield Finding(
                path,
                f"private absolute path at line {_line_number(text, match.start())}",
            )

    if _PRIVATE_KEY_MARKER in text:
        yield Finding(path, "private key material")
    for pattern in _SECRET_PATTERNS:
        match = pattern.search(text)
        if match:
            yield Finding(
                path,
                f"credential-like value at line {_line_number(text, match.start())}",
            )


def _ignored_generated_directory(root: Path, generated_root: Path) -> bool:
    """Return whether root-level gitignore rules exclude generated state."""

    ignore_file = root / ".gitignore"
    if not ignore_file.is_file():
        return False
    try:
        patterns = {
            line.strip()
            for line in ignore_file.read_text(encoding="utf-8").splitlines()
            if line.strip() and not line.lstrip().startswith(("#", "!"))
        }
    except OSError:
        return False
    name = generated_root.name
    if name.endswith(".egg-info") and "*.egg-info/" in patterns:
        return True
    return f"{name}/" in patterns or f"/{name}/" in patterns


def check_release(root: Path, max_bytes: int = DEFAULT_MAX_BYTES) -> list[Finding]:
    """Return every release hygiene problem under ``root``."""

    root = root.expanduser().resolve()
    findings: list[Finding] = []
    reported_generated: set[Path] = set()
    for path in sorted(root.rglob("*")):
        relative = path.relative_to(root)
        relative_text = relative.as_posix()
        lowered_parts = tuple(part.casefold() for part in relative.parts)
        release_binary = relative in _RELEASE_BINARY_FILES
        release_eval_data = lowered_parts[:2] == ("data", "eval")
        release_eval_runtime = lowered_parts[:2] == ("eval", "task")

        if any(part in _IGNORED_LOCAL_DIRECTORIES for part in lowered_parts):
            continue

        generated_index = next(
            (
                index
                for index, part in enumerate(lowered_parts)
                if part in _GENERATED_DIRECTORIES or part.endswith(".egg-info")
            ),
            None,
        )
        if generated_index is not None:
            generated_root = Path(*relative.parts[: generated_index + 1])
            if _ignored_generated_directory(root, generated_root):
                continue
            if generated_root not in reported_generated:
                findings.append(Finding(generated_root, "generated directory"))
                reported_generated.add(generated_root)
            continue

        path_terms = _METHOD_TERMS if release_eval_runtime else _EXCLUDED_TERMS
        if any(term in relative_text.casefold() for term in path_terms):
            findings.append(Finding(relative, "excluded method term in path"))

        if path.is_symlink():
            target = os.readlink(path)
            if not path.exists():
                findings.append(Finding(relative, "broken symbolic link"))
            else:
                resolved_target = path.resolve()
                try:
                    resolved_target.relative_to(root)
                except ValueError:
                    findings.append(Finding(relative, "symbolic link escapes release tree"))
            for pattern in _PRIVATE_PATH_PATTERNS:
                if pattern.search(target):
                    findings.append(Finding(relative, "symbolic link contains a private path"))
                    break
            continue

        if path.is_dir():
            if (
                lowered_parts
                and lowered_parts[0] == "data"
                and len(lowered_parts) > 1
                and not release_eval_data
            ):
                findings.append(Finding(relative, "generated root data directory"))
            continue
        if not path.is_file():
            findings.append(Finding(relative, "unsupported filesystem entry"))
            continue
        if relative in _ALLOWED_RELEASE_BINARIES:
            continue

        if path.name.casefold() in _GENERATED_FILES:
            findings.append(Finding(relative, "generated output file"))
        if (
            path.suffix.casefold() in _ARTIFACT_SUFFIXES
            and not release_binary
            and not (
                release_eval_data
                and path.suffix.casefold() == ".jsonl"
            )
        ):
            findings.append(Finding(relative, "generated or binary artifact"))

        size = path.stat().st_size
        effective_max_bytes = (
            max(max_bytes, EVALUATION_JSONL_MAX_BYTES)
            if release_eval_data and path.suffix.casefold() == ".jsonl"
            else max_bytes
        )
        if size > effective_max_bytes and not release_binary:
            findings.append(
                Finding(
                    relative,
                    f"file is too large ({size} bytes; limit {effective_max_bytes})",
                )
            )
            continue
        try:
            text = path.read_text(encoding="utf-8")
        except UnicodeDecodeError:
            if not release_binary:
                findings.append(Finding(relative, "non-text file"))
            continue
        findings.extend(
            _text_findings(
                relative,
                text,
                check_excluded_terms=not release_eval_data,
                allow_ground_truth_names=release_eval_runtime,
            )
        )
    return findings


def create_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "root",
        nargs="?",
        default=str(Path(__file__).resolve().parents[1]),
        help="Release tree to inspect (default: OraRL source root).",
    )
    parser.add_argument(
        "--max-bytes",
        type=int,
        default=DEFAULT_MAX_BYTES,
        help="Maximum permitted size for one source file.",
    )
    return parser


def main(argv: Sequence[str] | None = None) -> int:
    namespace = create_parser().parse_args(argv)
    root = Path(namespace.root).expanduser()
    if not root.is_dir():
        print(f"ERROR: release root is not a directory: {root}")
        return 2
    if namespace.max_bytes <= 0:
        print("ERROR: --max-bytes must be positive")
        return 2

    findings = check_release(root, namespace.max_bytes)
    if findings:
        for finding in findings:
            print(f"ERROR: {finding.path}: {finding.reason}")
        print(f"release hygiene failed with {len(findings)} finding(s)")
        return 1
    file_count = sum(1 for path in root.rglob("*") if path.is_file())
    print(f"release hygiene passed ({file_count} files)")
    return 0


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