File size: 6,509 Bytes
a0fd5b3 | 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 | #!/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())
|