aisim-data / scripts /validate.py
nv-simonec's picture
Bootstrap category-first AISimulate data storage
a0fd5b3
Raw
History Blame
6.51 kB
#!/usr/bin/env python3
"""Validate manifests, artifact integrity, category paths, and generated catalogs."""
from __future__ import annotations
import argparse
import hashlib
import sys
from pathlib import Path
from typing import Any
import jsonschema
import yaml
from referencing import Registry, Resource
ROOT = Path(__file__).resolve().parents[1]
SCHEMAS = ROOT / "schemas"
DATA = ROOT / "data"
CATEGORY_DEPTH = {"op-latency": 4, "e2e": 5, "fpm": 5}
def load_yaml(path: Path) -> Any:
with path.open(encoding="utf-8") as stream:
return yaml.safe_load(stream)
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def schema_validator(category: str) -> jsonschema.Draft202012Validator:
filename = f"{category}-manifest-v1.schema.yaml"
schema = load_yaml(SCHEMAS / filename)
common = load_yaml(SCHEMAS / "common-v1.schema.yaml")
registry = Registry().with_resources(
[
(common["$id"], Resource.from_contents(common)),
((SCHEMAS / common["$id"]).as_uri(), Resource.from_contents(common)),
]
)
return jsonschema.Draft202012Validator(schema, registry=registry)
def validate_hierarchy(manifest_path: Path, document: dict[str, Any]) -> list[str]:
errors: list[str] = []
relative = manifest_path.relative_to(DATA)
category = relative.parts[0]
expected = CATEGORY_DEPTH[category]
identity_parts = relative.parts[1:-1]
if len(identity_parts) != expected:
errors.append(f"expected {expected} identity components, got {len(identity_parts)}")
return errors
identity = document["identity"]
if category == "op-latency":
hardware, operation, framework, version = identity_parts
expected_values = (identity["hardware"], document["operation_family"], identity["framework"], identity["framework_version"])
if any(key in document for key in ("model", "parallelism")):
errors.append("operation-latency manifest contains model or parallelism identity")
else:
model, hardware, framework, version, parallelism = identity_parts
expected_values = (
document["model"]["id"].replace("/", "--"), identity["hardware"],
identity["framework"], identity["framework_version"], document["parallelism"]["label"],
)
if tuple(identity_parts) != expected_values:
errors.append(f"path identity {tuple(identity_parts)!r} != manifest identity {expected_values!r}")
return errors
def validate_artifacts(leaf: Path, artifacts: list[dict[str, Any]]) -> list[str]:
errors: list[str] = []
seen: set[str] = set()
for artifact in artifacts:
artifact_id = artifact["id"]
if artifact_id in seen:
errors.append(f"duplicate artifact id: {artifact_id}")
seen.add(artifact_id)
target = (leaf / artifact["path"]).resolve()
try:
target.relative_to(leaf.resolve())
except ValueError:
errors.append(f"unsafe artifact path: {artifact['path']}")
continue
if not target.is_file():
errors.append(f"missing artifact: {artifact['path']}")
continue
if target.stat().st_size != artifact["bytes"]:
errors.append(f"byte-size mismatch: {artifact['path']}")
if sha256(target) != artifact["sha256"]:
errors.append(f"SHA-256 mismatch: {artifact['path']}")
if artifact.get("format") == "parquet" and "rows" in artifact:
try:
import pyarrow.parquet as parquet
if parquet.read_metadata(target).num_rows != artifact["rows"]:
errors.append(f"row-count mismatch: {artifact['path']}")
except ImportError:
pass
return errors
def validate_manifest(path: Path) -> list[str]:
errors: list[str] = []
try:
document = load_yaml(path)
category = path.relative_to(DATA).parts[0]
if category not in CATEGORY_DEPTH:
return ["unknown category"]
for error in schema_validator(category).iter_errors(document):
location = ".".join(str(part) for part in error.absolute_path) or "<root>"
errors.append(f"schema {location}: {error.message}")
if errors:
return errors
errors.extend(validate_hierarchy(path, document))
errors.extend(validate_artifacts(path.parent, document["artifacts"]))
if any(source["project"].lower() == "inferencex" for source in document.get("sources", [])):
source = next(source for source in document["sources"] if source["project"].lower() == "inferencex")
if source["license"] != "Apache-2.0" or not source["unofficial"]:
errors.append("InferenceX source must declare Apache-2.0 and unofficial: true")
except (OSError, yaml.YAMLError, KeyError, TypeError) as error:
errors.append(str(error))
return errors
def validate(root: Path = DATA) -> list[str]:
failures: list[str] = []
for manifest in sorted(root.glob("*/**/manifest.yaml")):
for error in validate_manifest(manifest):
failures.append(f"{manifest.relative_to(ROOT)}: {error}")
if not list(root.glob("*/**/manifest.yaml")):
failures.append("no manifests found")
gap_schema = load_yaml(SCHEMAS / "gap-analysis-v1.schema.yaml")
common = load_yaml(SCHEMAS / "common-v1.schema.yaml")
registry = Registry().with_resources(
[
(common["$id"], Resource.from_contents(common)),
((SCHEMAS / common["$id"]).as_uri(), Resource.from_contents(common)),
]
)
gap_validator = jsonschema.Draft202012Validator(gap_schema, registry=registry)
for gap in sorted(root.glob("e2e/**/evaluations/*/gap-analysis.yaml")):
for error in gap_validator.iter_errors(load_yaml(gap)):
failures.append(f"{gap.relative_to(ROOT)}: schema: {error.message}")
return failures
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--root", type=Path, default=DATA)
args = parser.parse_args()
failures = validate(args.root)
if failures:
print("\n".join(failures), file=sys.stderr)
return 1
print("All manifests are valid.")
return 0
if __name__ == "__main__":
raise SystemExit(main())