LocateAnything-Data / tools /verify_release.py
exiawsh's picture
Add files using upload-large-folder tool
b2d4e74 verified
Raw
History Blame Contribute Delete
113 kB
#!/usr/bin/env python3
"""Fail-closed verifier for a LocateAnything-Data Hugging Face staging tree.
The verifier intentionally has two operating modes:
* ``unit`` validates the complete topology, all cheap metadata, every JSONL
index, every Parquet schema, and deterministic record/mapping samples.
* ``final`` additionally scans every JSONL and Parquet row, performs exact
record-to-mapping and mapping foreign-key joins, and verifies every manifest
SHA-256. It is the publication gate.
The verification receipt is written outside the staging tree by default. A
receipt inside the staging tree would itself violate the release closure.
"""
from __future__ import annotations
import argparse
import concurrent.futures
import contextlib
import datetime as dt
import hashlib
import json
import mmap
import os
import re
import sqlite3
import struct
import sys
import tempfile
import time
import traceback
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from typing import Any, Iterable, Iterator, Mapping, Sequence
VERIFIER_VERSION = "1.0.2"
RECEIPT_SCHEMA = "locate-anything.release-verification-receipt/v1"
EXPECTED = {
"dataset_count": 42,
"view_count": 47,
"record_count": 10_136_648,
"media_pool_count": 41,
"hosted_dataset_count": 35,
"hosted_media_pool_count": 34,
"hosted_tar_count": 583,
"hosted_record_count": 7_719_677,
"restricted_media_pool_count": 7,
"restricted_record_count": 2_416_971,
}
ALLOWED_TASK_TYPES = {
"detection_grounding",
"detection_grounding_pointing",
"pointing",
}
ALLOWED_MEDIA_KINDS = {
"image",
"video",
"audio",
"depth",
"tensor",
"document",
}
# This list is deliberately embedded in the verifier. Merely editing the
# release policy must never be sufficient to publish a forbidden media pool.
RESTRICTED: dict[str, dict[str, Any]] = {
"locany--crowdhuman--train--source_image--v000001": {
"upstream_name": "CrowdHuman",
"dataset_id": "crowdhuman",
"view_id": "locate_anything_crowdhuman_crowdhuman",
"record_count": 15_000,
"physical_media_count": 14_999,
"tar_count_excluded": 3,
"official_url": "https://www.crowdhuman.org/download.html",
},
"locany--deepfashion2--train--source_image--v000001": {
"upstream_name": "DeepFashion2",
"dataset_id": "deepfashion2",
"view_id": "locate_anything_deepfashion2_deepfashion2",
"record_count": 191_961,
"physical_media_count": 191_961,
"tar_count_excluded": 3,
"official_url": "https://github.com/switchablenorms/DeepFashion2",
},
"locany--flickr30k--train--source_image--v000001": {
"upstream_name": "Flickr30K",
"dataset_id": "flickr30k",
"view_id": "locate_anything_flickr30k_flickr30k",
"record_count": 29_781,
"physical_media_count": 29_781,
"tar_count_excluded": 1,
"official_url": (
"https://shannon.cs.illinois.edu/DenotationGraph/data/index.html"
),
},
"locany--imagenet--train--source_image--v000001": {
"upstream_name": "ImageNet",
"dataset_id": "partimagenet",
"view_id": "locate_anything_partimagenet_partimagenet",
"record_count": 100_000,
"physical_media_count": 99_781,
"tar_count_excluded": 3,
"official_url": "https://www.image-net.org/download.php",
},
"locany--object365--train--source_image--v000001": {
"upstream_name": "Objects365",
"dataset_id": "object365",
"view_id": "locate_anything_object365_object365",
"record_count": 1_742_289,
"physical_media_count": 1_723_931,
"tar_count_excluded": 84,
"official_url": "https://www.objects365.org/download.html",
},
"locany--sku110k--train--source_image--v000001": {
"upstream_name": "SKU-110K",
"availability_upstream_name": "SKU110K",
"dataset_id": "sku110k",
"view_id": "locate_anything_sku110k_sku110k",
"record_count": 8_219,
"physical_media_count": 8_219,
"tar_count_excluded": 3,
"official_url": "https://github.com/eg4000/SKU110K_CVPR19",
},
"locany--unsplash--train--source_image--v000001": {
"upstream_name": "Unsplash",
"dataset_id": "unsplash",
"view_id": "locate_anything_unsplash_unsplash",
"record_count": 329_721,
"physical_media_count": 329_687,
"tar_count_excluded": 246,
"official_url": "https://unsplash.com/data",
},
}
MEDIA_MAP_FIELDS = {
"schema",
"pool_id",
"source_id",
"source_dataset",
"source_snapshot_id",
"source_media_name",
"source_relative_path",
"source_bytes",
"source_sha256",
"identity_status",
"member_name",
"content_sha256",
"media_kind",
"encoding",
"encoded_bytes",
"availability",
"tar_relpath",
"payload_offset",
"payload_length",
}
VIEW_MAP_FIELDS = {
"schema",
"dataset_id",
"view_id",
"row_id",
"source_sample_id",
"source_annotation",
"source_file_index",
"source_row",
"source_record_sha256",
"occurrence",
"json_pointer",
"aux_source",
"pool_id",
"source_id",
"member_name",
"media_kind",
}
INTEGER_MEDIA_FIELDS = {
"source_id",
"source_bytes",
"encoded_bytes",
"payload_offset",
"payload_length",
}
INTEGER_VIEW_FIELDS = {
"row_id",
"source_file_index",
"source_row",
"occurrence",
"source_id",
}
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
MEMBER_RE = re.compile(r"^m/[0-9]{12}\.[A-Za-z0-9]+$")
PART_RE = re.compile(r"^part-[0-9]{5}\.parquet$")
TAR_RE = re.compile(r"^image-[0-9]{8}\.tar$")
POOL_RE = re.compile(r"^locany--[A-Za-z0-9_.-]+--train--[A-Za-z0-9_.-]+--v[0-9]{6}$")
FORBIDDEN_COMPONENT_RE = re.compile(
r"(?:^|[-_.])(vqa|test|tests|testset|benchmark|benchmarks|validation)"
r"(?:$|[-_.])",
re.IGNORECASE,
)
PRIVATE_ARTIFACT_COMPONENT_RE = re.compile(
r"(?:^|[-_.])(?:provenance|receipts?|build[-_]binding)(?:$|[-_.])",
re.IGNORECASE,
)
INTERNAL_PATH_RE = re.compile(
r"(?i)(?:file://|^(?:lustre|home|users)(?:/|$)|"
r"(?:^|[\"'\s:=])/"
r"(?:lustre|home|users|mnt|workspace|scratch|gpfs|fsx)(?:/|$))"
)
WINDOWS_ABS_RE = re.compile(r"^[A-Za-z]:[\\/]")
SECRET_RE = re.compile(
r"(?i)(?:hf_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|"
r"aws_secret_access_key|authorization\s*[:=]\s*bearer|"
r"x-amz-(?:credential|signature)|[?&](?:signature|token)=)"
)
PRIVATE_KEY_NAMES = {
"source_absolute_path",
"absolute_path",
"original_path",
"source_root_json",
"evidence_json",
"inode",
"device",
"symlink_target",
"access_token",
"cookie",
}
# ``query`` is the public task-label map. These three ordinary class/OCR
# labels collide with filesystem/session vocabulary, but they are not
# metadata fields. The exception is intentionally limited to direct children
# of the top-level query object in a validated training record.
QUERY_LABEL_PRIVATE_KEY_EXCEPTIONS = {
"cookie",
"device",
"inode",
}
@dataclass
class ViewInfo:
dataset_id: str
view_id: str
path: Path
aux: dict[str, str]
pools: set[str]
record_count: int = 0
media_occurrence_count: int = 0
mapping_row_count: int = 0
@dataclass
class PoolInfo:
pool_id: str
path: Path
restricted: bool
tar_paths: list[Path] = field(default_factory=list)
tar_sizes: dict[str, int] = field(default_factory=dict)
mapping_row_count: int = 0
class Verification:
def __init__(
self,
root: Path,
mode: str,
receipt_path: Path,
sample_records: int,
hash_mode: str,
hash_jobs: int,
temp_dir: Path | None,
max_errors: int,
) -> None:
self.root = root.resolve()
self.mode = mode
self.receipt_path = receipt_path
self.sample_records = max(1, sample_records)
self.hash_mode = hash_mode
self.hash_jobs = max(1, hash_jobs)
self.temp_dir = temp_dir
self.max_errors = max(1, max_errors)
self.started = time.monotonic()
self.error_count = 0
self.warning_count = 0
self.errors: list[dict[str, str]] = []
self.warnings: list[dict[str, str]] = []
self.phases: list[dict[str, Any]] = []
self.metrics: dict[str, Any] = {}
self.files: dict[str, os.stat_result] = {}
self.views: dict[tuple[str, str], ViewInfo] = {}
self.pools: dict[str, PoolInfo] = {}
self.policy: dict[str, Any] | None = None
self.manifest_rows: dict[str, dict[str, Any]] = {}
self._yaml: Any = None
self._pa: Any = None
self._pq: Any = None
self._pds: Any = None
self._pc: Any = None
def error(self, code: str, message: str, path: Path | str | None = None) -> None:
self.error_count += 1
if len(self.errors) < self.max_errors:
item = {"code": code, "message": message}
if path is not None:
item["path"] = self.display(path)
self.errors.append(item)
def warn(self, code: str, message: str, path: Path | str | None = None) -> None:
self.warning_count += 1
if len(self.warnings) < self.max_errors:
item = {"code": code, "message": message}
if path is not None:
item["path"] = self.display(path)
self.warnings.append(item)
def display(self, path: Path | str) -> str:
if isinstance(path, str):
return path
with contextlib.suppress(ValueError):
return path.resolve().relative_to(self.root).as_posix()
return str(path)
@contextlib.contextmanager
def phase(self, name: str) -> Iterator[None]:
before = self.error_count
started = time.monotonic()
entry: dict[str, Any] = {"name": name}
try:
yield
except Exception as exc: # fail closed and keep a useful receipt
self.error(
"internal_phase_error",
f"{type(exc).__name__}: {exc}",
name,
)
entry["exception"] = traceback.format_exc(limit=12)
entry["status"] = "passed" if self.error_count == before else "failed"
entry["new_errors"] = self.error_count - before
entry["duration_seconds"] = round(time.monotonic() - started, 3)
self.phases.append(entry)
def load_dependencies(self) -> None:
try:
import yaml # type: ignore
self._yaml = yaml
except Exception as exc:
self.error("missing_dependency", f"PyYAML is required: {exc}")
try:
import pyarrow as pa # type: ignore
import pyarrow.compute as pc # type: ignore
import pyarrow.dataset as pds # type: ignore
import pyarrow.parquet as pq # type: ignore
self._pa, self._pc, self._pds, self._pq = pa, pc, pds, pq
except Exception as exc:
self.error("missing_dependency", f"pyarrow is required: {exc}")
def run(self) -> bool:
with self.phase("dependencies"):
self.load_dependencies()
with self.phase("root_and_policy"):
self.check_root_and_policy()
with self.phase("filesystem_closure"):
self.scan_filesystem()
with self.phase("catalog_and_aux_paths"):
self.check_catalog()
with self.phase("media_pools"):
self.check_media_pools()
with self.phase("root_metadatasets"):
self.check_root_metadatasets()
with self.phase("annotations_and_view_mappings"):
self.check_views_and_view_mappings()
with self.phase("media_mappings"):
self.check_media_mappings()
with self.phase("mapping_foreign_keys"):
self.check_mapping_foreign_keys()
with self.phase("manifest_closure_and_hashes"):
self.check_manifest()
self.check_expected_metrics()
return self.error_count == 0
# ------------------------------------------------------------------
# Root, policy, and filesystem closure
# ------------------------------------------------------------------
def check_root_and_policy(self) -> None:
if not self.root.is_dir():
self.error("missing_root", "staging root does not exist", self.root)
return
policy_path = self.root / "release-policy.json"
policy = self.read_json(policy_path)
if not isinstance(policy, dict):
return
self.policy = policy
if policy.get("schema") != "locate-anything.public-release-policy/v1":
self.error("bad_policy_schema", "unexpected release policy schema", policy_path)
scope = policy.get("scope")
hosted = policy.get("hosted_media")
external = policy.get("external_media")
if not isinstance(scope, dict) or not isinstance(hosted, dict) or not isinstance(
external, dict
):
self.error("bad_policy", "policy scope/hosted_media/external_media must be objects")
return
policy_expected = {
("scope", "dataset_count"): EXPECTED["dataset_count"],
("scope", "view_count"): EXPECTED["view_count"],
("scope", "record_count"): EXPECTED["record_count"],
("scope", "media_pool_count"): EXPECTED["media_pool_count"],
("hosted_media", "dataset_count"): EXPECTED["hosted_dataset_count"],
("hosted_media", "record_count"): EXPECTED["hosted_record_count"],
("hosted_media", "media_pool_count"): EXPECTED["hosted_media_pool_count"],
("hosted_media", "tar_count"): EXPECTED["hosted_tar_count"],
("external_media", "record_count"): EXPECTED["restricted_record_count"],
}
groups = {"scope": scope, "hosted_media": hosted, "external_media": external}
for (group, key), wanted in policy_expected.items():
actual = groups[group].get(key)
if actual != wanted:
self.error(
"policy_count_mismatch",
f"{group}.{key}={actual!r}, expected {wanted}",
policy_path,
)
if scope.get("task_types") != sorted(ALLOWED_TASK_TYPES):
self.error(
"policy_task_types",
f"scope.task_types must be {sorted(ALLOWED_TASK_TYPES)!r}",
policy_path,
)
if scope.get("vqa_included") is not False:
self.error("policy_vqa", "scope.vqa_included must be false", policy_path)
if scope.get("test_benchmark_validation_included") is not False:
self.error(
"policy_eval_data",
"scope.test_benchmark_validation_included must be false",
policy_path,
)
pools = external.get("pools")
if not isinstance(pools, list):
self.error("bad_policy", "external_media.pools must be a list", policy_path)
return
observed: dict[str, dict[str, Any]] = {}
for row in pools:
if not isinstance(row, dict) or not isinstance(row.get("pool_id"), str):
self.error("bad_policy_pool", "invalid external pool entry", policy_path)
continue
pool_id = row["pool_id"]
if pool_id in observed:
self.error("duplicate_policy_pool", f"duplicate pool {pool_id}", policy_path)
observed[pool_id] = row
if set(observed) != set(RESTRICTED):
self.error(
"restricted_policy_mismatch",
f"restricted pool set differs: actual={sorted(observed)}, "
f"expected={sorted(RESTRICTED)}",
policy_path,
)
for pool_id, expected in RESTRICTED.items():
row = observed.get(pool_id)
if row is None:
continue
for key in (
"upstream_name",
"dataset_id",
"view_id",
"record_count",
"physical_media_count",
"tar_count_excluded",
"official_url",
):
actual = row.get(key)
if type(actual) is not type(expected[key]) or actual != expected[key]:
self.error(
"restricted_policy_mismatch",
f"{pool_id}.{key}={actual!r}, expected {expected[key]!r}",
policy_path,
)
def scan_filesystem(self) -> None:
if not self.root.is_dir():
return
casefold_paths: dict[str, str] = {}
tar_inodes: dict[tuple[int, int], str] = {}
for dirpath, dirnames, filenames in os.walk(self.root, followlinks=False):
base = Path(dirpath)
for name in list(dirnames):
path = base / name
try:
st = path.lstat()
except OSError as exc:
self.error("stat_failed", str(exc), path)
dirnames.remove(name)
continue
if path.is_symlink():
self.error("symlink_forbidden", "symlinks are forbidden", path)
dirnames.remove(name)
for name in filenames:
path = base / name
rel = path.relative_to(self.root).as_posix()
try:
st = path.lstat()
except OSError as exc:
self.error("stat_failed", str(exc), path)
continue
if path.is_symlink():
self.error("symlink_forbidden", "symlinks are forbidden", path)
continue
if not path.is_file():
self.error("non_regular_file", "only regular files are allowed", path)
continue
self.files[rel] = st
folded = rel.casefold()
other = casefold_paths.get(folded)
if other is not None and other != rel:
self.error(
"case_collision",
f"case-insensitive path collision with {other}",
path,
)
casefold_paths[folded] = rel
self.check_forbidden_release_path(rel)
if path.suffix == ".tar":
inode = (st.st_dev, st.st_ino)
other_tar = tar_inodes.get(inode)
if other_tar is not None:
self.error(
"duplicate_tar_inode",
f"TAR has another repository path: {other_tar}",
path,
)
tar_inodes[inode] = rel
self.metrics["regular_file_count"] = len(self.files)
self.metrics["symlink_count"] = sum(
1 for item in self.errors if item["code"] == "symlink_forbidden"
)
def check_forbidden_release_path(self, rel: str) -> None:
parts = PurePosixPath(rel).parts
lower = rel.casefold()
if len(parts) >= 3 and parts[0] == "datasets" and parts[2] == "media":
self.error(
"dataset_local_media",
"dataset-local media projection is forbidden",
rel,
)
for part in parts:
if FORBIDDEN_COMPONENT_RE.search(part):
self.error(
"forbidden_scope_path",
"VQA/test/benchmark/validation path is forbidden",
rel,
)
break
if any(PRIVATE_ARTIFACT_COMPONENT_RE.search(part) for part in parts):
self.error(
"private_artifact_path",
"provenance/receipt/build-binding artifacts are forbidden",
rel,
)
if lower.endswith((".sqlite", ".sqlite3", ".db")):
if not re.fullmatch(r"media/[^/]+/\.nv-meta/index\.sqlite", rel):
self.error(
"private_sqlite",
"only Energon media/<pool>/.nv-meta/index.sqlite is allowed",
rel,
)
# ------------------------------------------------------------------
# Catalog and YAML paths
# ------------------------------------------------------------------
def check_catalog(self) -> None:
if self._yaml is None:
return
datasets_root = self.root / "datasets"
if not datasets_root.is_dir():
self.error("missing_datasets", "datasets/ directory is required", datasets_root)
return
dataset_dirs = sorted(p for p in datasets_root.iterdir() if p.is_dir())
stray = sorted(p for p in datasets_root.iterdir() if not p.is_dir())
for path in stray:
self.error("dataset_root_stray", "only dataset directories are allowed", path)
for dataset_dir in dataset_dirs:
dataset_id = dataset_dir.name
views_root = dataset_dir / "views"
if not views_root.is_dir():
self.error("missing_views", "dataset views/ directory is required", views_root)
continue
view_dirs = sorted(p for p in views_root.iterdir() if p.is_dir())
for path in views_root.iterdir():
if not path.is_dir():
self.error("view_root_stray", "only view directories are allowed", path)
for view_dir in view_dirs:
view_id = view_dir.name
key = (dataset_id, view_id)
if key in self.views:
self.error("duplicate_view", f"duplicate view {key}", view_dir)
continue
required = [
view_dir / "records.jsonl",
view_dir / "records.jsonl.idx",
view_dir / "metadataset.yaml",
]
for path in required:
if not path.is_file():
self.error("missing_view_file", "required view file is missing", path)
doc = self.read_yaml(view_dir / "metadataset.yaml")
aux: dict[str, str] = {}
if isinstance(doc, dict):
train = self.yaml_train(doc, view_dir / "metadataset.yaml")
if train is not None:
if train.get("path") != "./records.jsonl":
self.error(
"view_record_path",
"view train.path must be exactly ./records.jsonl",
view_dir / "metadataset.yaml",
)
raw_aux = train.get("aux")
if not isinstance(raw_aux, dict) or not raw_aux:
self.error(
"missing_view_aux",
"view train.aux must be a non-empty mapping",
view_dir / "metadataset.yaml",
)
else:
for aux_name, target in raw_aux.items():
if not isinstance(aux_name, str) or not isinstance(
target, str
):
self.error(
"bad_view_aux",
"aux names and targets must be strings",
view_dir / "metadataset.yaml",
)
continue
match = re.fullmatch(
r"\.\./\.\./\.\./\.\./media/([^/]+)", target
)
if match is None:
self.error(
"bad_view_aux_path",
"aux target must be exactly "
"../../../../media/<pool_id>",
view_dir / "metadataset.yaml",
)
continue
pool_id = match.group(1)
if not POOL_RE.fullmatch(pool_id):
self.error(
"bad_pool_id",
f"invalid pool ID {pool_id!r}",
view_dir / "metadataset.yaml",
)
resolved = Path(os.path.normpath(view_dir / target))
expected = self.root / "media" / pool_id
if resolved != expected:
self.error(
"aux_escape",
f"aux resolves to {resolved}, expected {expected}",
view_dir / "metadataset.yaml",
)
aux[aux_name] = pool_id
subflavors = train.get("subflavors")
if not isinstance(subflavors, dict):
self.error(
"missing_subflavors",
"view train.subflavors must be an object",
view_dir / "metadataset.yaml",
)
else:
if subflavors.get("dataset_id") != dataset_id:
self.error(
"dataset_id_mismatch",
"subflavors.dataset_id does not match directory",
view_dir / "metadataset.yaml",
)
if subflavors.get("view_id") != view_id:
self.error(
"view_id_mismatch",
"subflavors.view_id does not match directory",
view_dir / "metadataset.yaml",
)
self.views[key] = ViewInfo(
dataset_id=dataset_id,
view_id=view_id,
path=view_dir,
aux=aux,
pools=set(aux.values()),
)
dataset_meta = dataset_dir / "metadataset.yaml"
refs = self.read_blend_paths(dataset_meta)
expected_refs = {
f"./views/{view_dir.name}/metadataset.yaml" for view_dir in view_dirs
}
if refs is not None and refs != expected_refs:
self.error(
"dataset_metadataset_closure",
f"view refs={sorted(refs)}, expected={sorted(expected_refs)}",
dataset_meta,
)
self.metrics["dataset_count"] = len(dataset_dirs)
self.metrics["view_count"] = len(self.views)
mapping_root = self.root / "mappings" / "views"
actual_mapping_views: set[tuple[str, str]] = set()
if not mapping_root.is_dir():
self.error(
"missing_view_mappings",
"mappings/views directory is required",
mapping_root,
)
else:
for dataset_dir in mapping_root.iterdir():
if not dataset_dir.is_dir():
self.error("mapping_stray", "unexpected mapping file", dataset_dir)
continue
for view_dir in dataset_dir.iterdir():
if not view_dir.is_dir():
self.error("mapping_stray", "unexpected mapping file", view_dir)
continue
actual_mapping_views.add((dataset_dir.name, view_dir.name))
if actual_mapping_views != set(self.views):
self.error(
"view_mapping_closure",
"mapping view directories do not exactly match annotation views; "
f"missing={sorted(set(self.views) - actual_mapping_views)}, "
f"extra={sorted(actual_mapping_views - set(self.views))}",
mapping_root,
)
def yaml_train(self, doc: dict[str, Any], path: Path) -> dict[str, Any] | None:
if doc.get("__module__") != "megatron.energon":
self.error("bad_energon_yaml", "__module__ must be megatron.energon", path)
if doc.get("__class__") != "MetadatasetV2":
self.error("bad_energon_yaml", "__class__ must be MetadatasetV2", path)
splits = doc.get("splits")
if not isinstance(splits, dict) or set(splits) != {"train"}:
self.error("bad_energon_yaml", "splits must contain exactly train", path)
return None
train = splits["train"]
if not isinstance(train, dict):
self.error("bad_energon_yaml", "splits.train must be an object", path)
return None
self.scan_structured_value(train, path)
return train
def read_blend_paths(self, path: Path) -> set[str] | None:
doc = self.read_yaml(path)
if not isinstance(doc, dict):
return None
train = self.yaml_train(doc, path)
if train is None:
return None
blend = train.get("blend_epochized")
if not isinstance(blend, list) or not blend:
self.error(
"bad_energon_blend",
"train.blend_epochized must be a non-empty list",
path,
)
return None
refs: set[str] = set()
for item in blend:
if not isinstance(item, dict) or set(item) != {"repetitions", "path"}:
self.error(
"bad_energon_blend",
"each blend item must contain only repetitions and path",
path,
)
continue
if item.get("repetitions") != 1:
self.error("bad_energon_blend", "repetitions must equal 1", path)
ref = item.get("path")
if not isinstance(ref, str) or self.is_absolute_or_escaping(ref):
self.error("absolute_or_escaping_path", f"invalid blend path {ref!r}", path)
continue
if ref in refs:
self.error("duplicate_blend_path", f"duplicate blend path {ref}", path)
refs.add(ref)
return refs
def check_root_metadatasets(self) -> None:
if not self.views:
return
all_datasets = {dataset_id for dataset_id, _ in self.views}
restricted_pools = set(RESTRICTED)
hosted_datasets: set[str] = set()
external_datasets: set[str] = set()
for dataset_id in all_datasets:
pool_ids = set().union(
*(
view.pools
for (candidate, _), view in self.views.items()
if candidate == dataset_id
)
)
if pool_ids & restricted_pools:
external_datasets.add(dataset_id)
else:
hosted_datasets.add(dataset_id)
expected_external = {row["dataset_id"] for row in RESTRICTED.values()}
if external_datasets != expected_external:
self.error(
"external_dataset_set",
f"actual={sorted(external_datasets)}, expected={sorted(expected_external)}",
)
hosted_refs = self.read_blend_paths(self.root / "metadataset.yaml")
full_refs = self.read_blend_paths(self.root / "metadataset-full.yaml")
expected_hosted_refs = {
f"./datasets/{dataset_id}/metadataset.yaml"
for dataset_id in hosted_datasets
}
expected_full_refs = {
f"./datasets/{dataset_id}/metadataset.yaml" for dataset_id in all_datasets
}
if hosted_refs is not None and hosted_refs != expected_hosted_refs:
self.error(
"hosted_root_closure",
f"hosted root refs differ; missing="
f"{sorted(expected_hosted_refs - hosted_refs)}, "
f"extra={sorted(hosted_refs - expected_hosted_refs)}",
self.root / "metadataset.yaml",
)
if full_refs is not None and full_refs != expected_full_refs:
self.error(
"full_root_closure",
f"full root refs differ; missing={sorted(expected_full_refs - full_refs)}, "
f"extra={sorted(full_refs - expected_full_refs)}",
self.root / "metadataset-full.yaml",
)
self.metrics["hosted_dataset_count"] = len(hosted_datasets)
self.metrics["restricted_dataset_count"] = len(external_datasets)
# ------------------------------------------------------------------
# Media pools, TAR indexes, and Energon public indexes
# ------------------------------------------------------------------
def check_media_pools(self) -> None:
media_root = self.root / "media"
if not media_root.is_dir():
self.error("missing_media", "media/ directory is required", media_root)
return
pool_dirs = sorted(path for path in media_root.iterdir() if path.is_dir())
for path in media_root.iterdir():
if not path.is_dir():
self.error("media_root_stray", "only media pool directories are allowed", path)
actual_ids = {path.name for path in pool_dirs}
if not set(RESTRICTED).issubset(actual_ids):
self.error(
"missing_restricted_pool",
f"missing restricted pool directories: {sorted(set(RESTRICTED)-actual_ids)}",
media_root,
)
for pool_dir in pool_dirs:
pool_id = pool_dir.name
restricted = pool_id in RESTRICTED
pool = PoolInfo(pool_id=pool_id, path=pool_dir, restricted=restricted)
self.pools[pool_id] = pool
if not POOL_RE.fullmatch(pool_id):
self.error("bad_pool_id", f"invalid pool ID {pool_id!r}", pool_dir)
availability_path = pool_dir / "availability.json"
if restricted:
availability = self.read_json(availability_path)
if isinstance(availability, dict):
expected = RESTRICTED[pool_id]
expected_fields = {
"schema": "locate-anything.media-availability/v1",
"availability": "external_download_required",
"pool_id": pool_id,
"payload_in_hf_release": False,
"dataset_ids": [expected["dataset_id"]],
"view_ids": [expected["view_id"]],
"upstream_name": expected.get(
"availability_upstream_name", expected["upstream_name"]
),
"expected_source_alias_count": expected["record_count"],
"expected_media_count": expected["physical_media_count"],
"expected_tar_count_not_published": expected[
"tar_count_excluded"
],
"official_download_url": expected["official_url"],
}
for key, wanted in expected_fields.items():
actual = availability.get(key)
if type(actual) is not type(wanted) or actual != wanted:
self.error(
"availability_binding",
f"{key}={actual!r}, expected {wanted!r}",
availability_path,
)
tar_bytes = availability.get("expected_tar_bytes_not_published")
if not isinstance(tar_bytes, int) or isinstance(tar_bytes, bool) or (
tar_bytes <= 0
):
self.error(
"availability_tar_bytes",
"expected_tar_bytes_not_published must be a positive integer",
availability_path,
)
for key in ("note", "source_relative_path_pattern"):
if not isinstance(availability.get(key), str) or not availability[
key
]:
self.error(
"availability_text",
f"{key} must be nonempty text",
availability_path,
)
elif availability_path.exists():
self.error(
"hosted_availability_unexpected",
"hosted pools must publish shards and must not use availability.json",
availability_path,
)
if restricted:
entries = sorted(
path.relative_to(pool_dir).as_posix()
for path in pool_dir.rglob("*")
if path.is_file() or path.is_symlink()
)
if entries != ["availability.json"]:
self.error(
"restricted_pool_payload",
"restricted pool must contain only availability.json; "
f"found {entries}",
pool_dir,
)
forbidden = [
path
for path in pool_dir.rglob("*")
if path.suffix in {".tar", ".idx"}
or path.name == ".nv-meta"
or ".nv-meta" in path.parts
]
for path in forbidden:
self.error(
"restricted_pool_payload",
"restricted pool cannot contain TAR/index/.nv-meta",
path,
)
continue
shards = pool_dir / "shards"
nv_meta = pool_dir / ".nv-meta"
if not shards.is_dir():
self.error("missing_shards", "hosted pool requires shards/", shards)
continue
if not nv_meta.is_dir():
self.error("missing_nv_meta", "hosted pool requires .nv-meta/", nv_meta)
else:
required_nv = {
"index.sqlite",
"index.uuid",
"dataset.yaml",
"split.yaml",
".info.json",
}
for name in required_nv:
if not (nv_meta / name).is_file():
self.error(
"missing_nv_meta_file",
f"required Energon metadata file {name} is missing",
nv_meta / name,
)
self.check_energon_sqlite(nv_meta / "index.sqlite")
tars = sorted(shards.glob("*.tar"))
indexes = sorted(shards.glob("*.tar.idx"))
indexed_sample_counts: dict[str, int] = {}
for tar_path in tars:
if not TAR_RE.fullmatch(tar_path.name):
self.error("bad_tar_name", "unexpected TAR filename", tar_path)
idx = Path(str(tar_path) + ".idx")
if not idx.is_file():
self.error("missing_tar_index", "TAR index is missing", idx)
else:
sample_count = self.check_tar_index(tar_path, idx)
if sample_count is not None:
indexed_sample_counts[f"shards/{tar_path.name}"] = sample_count
info_path = nv_meta / ".info.json"
if info_path.is_file():
info = self.read_json(info_path)
if isinstance(info, dict):
if info.get("energon_version") != "7.4.0":
self.error(
"energon_info_version",
"energon_version must be '7.4.0'",
info_path,
)
shard_counts = info.get("shard_counts")
if not isinstance(shard_counts, dict):
self.error(
"energon_shard_counts",
"shard_counts must be an object",
info_path,
)
elif any(
not isinstance(count, int)
or isinstance(count, bool)
or count < 1
or not re.fullmatch(r"shards/image-[0-9]{8}\.tar", name)
for name, count in shard_counts.items()
):
self.error(
"energon_shard_counts",
"shard_counts keys and positive integer values are invalid",
info_path,
)
elif shard_counts != indexed_sample_counts:
self.error(
"energon_shard_counts",
"shard_counts must exactly equal the N non-terminal "
"offsets in each TAR index",
info_path,
)
tar_names = {path.name for path in tars}
for idx in indexes:
if idx.name.removesuffix(".idx") not in tar_names:
self.error("orphan_tar_index", "index has no matching TAR", idx)
for path in shards.iterdir():
if not path.is_file() or not (
path.name.endswith(".tar") or path.name.endswith(".tar.idx")
):
self.error(
"hosted_shards_stray",
"shards/ may contain only TAR and matching TAR indexes",
path,
)
pool.tar_paths = tars
pool.tar_sizes = {
f"media/{pool_id}/shards/{path.name}": path.stat().st_size
for path in tars
}
self.metrics["media_pool_count"] = len(self.pools)
self.metrics["restricted_media_pool_count"] = sum(
pool.restricted for pool in self.pools.values()
)
self.metrics["hosted_media_pool_count"] = sum(
not pool.restricted for pool in self.pools.values()
)
self.metrics["hosted_tar_count"] = sum(
len(pool.tar_paths) for pool in self.pools.values() if not pool.restricted
)
def check_tar_index(self, tar_path: Path, idx_path: Path) -> int | None:
try:
tar_size = tar_path.stat().st_size
idx_size = idx_path.stat().st_size
if idx_size < 16 or idx_size % 8:
self.error(
"bad_tar_index_size",
"TAR index must contain N+1 little-endian uint64 offsets",
idx_path,
)
return None
previous = -1
sampled: list[int] = []
count = idx_size // 8
first: int | None = None
terminal: int | None = None
with idx_path.open("rb") as handle:
while True:
block = handle.read(8 * 131_072)
if not block:
break
values = struct.unpack(f"<{len(block)//8}Q", block)
for value in values:
if first is None:
first = value
if value <= previous:
self.error(
"nonmonotonic_tar_index",
f"offset {value} follows {previous}",
idx_path,
)
return None
if value % 512:
self.error(
"unaligned_tar_index",
f"offset {value} is not 512-byte aligned",
idx_path,
)
return None
if value >= tar_size:
self.error(
"tar_index_out_of_bounds",
f"offset {value} is outside TAR size {tar_size}",
idx_path,
)
return None
previous = value
terminal = value
if first != 0:
self.error("bad_tar_index", "first TAR offset must be zero", idx_path)
if terminal is None or terminal + 1024 != tar_size:
self.error(
"bad_tar_terminator",
"terminal offset must be exactly 1024 bytes before TAR EOF",
idx_path,
)
return None
with tar_path.open("rb") as handle:
handle.seek(terminal)
while chunk := handle.read(8 * 1024 * 1024):
if any(chunk):
self.error(
"bad_tar_terminator",
"bytes from terminal offset through EOF must be zero",
tar_path,
)
return None
# Energon's TAR index contains N sample-start offsets followed by
# one terminal offset. The terminal points at the two zero blocks,
# so it is intentionally not a TAR header.
sample_count = count - 1
if sample_count:
positions = sorted({0, sample_count // 2, sample_count - 1})
with idx_path.open("rb") as handle:
for position in positions:
handle.seek(position * 8)
sampled.append(struct.unpack("<Q", handle.read(8))[0])
with tar_path.open("rb") as handle:
for offset in sampled:
handle.seek(offset)
header = handle.read(512)
if not self.valid_tar_header(header):
self.error(
"bad_tar_header",
f"index offset {offset} is not a valid TAR header",
tar_path,
)
return sample_count
except OSError as exc:
self.error("tar_index_io", str(exc), idx_path)
return None
@staticmethod
def valid_tar_header(header: bytes) -> bool:
if len(header) != 512 or header == b"\0" * 512:
return False
try:
raw = header[148:156].rstrip(b"\0 ")
stored = int(raw or b"0", 8)
except ValueError:
return False
check = bytearray(header)
check[148:156] = b" " * 8
return sum(check) == stored and bool(header[:100].split(b"\0", 1)[0])
def check_energon_sqlite(self, path: Path) -> None:
if not path.is_file():
return
try:
conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
try:
quick = conn.execute("PRAGMA quick_check").fetchone()
if quick != ("ok",):
self.error("energon_sqlite_corrupt", f"quick_check={quick!r}", path)
tables = {
row[0]
for row in conn.execute(
"SELECT name FROM sqlite_master "
"WHERE type='table' AND name NOT LIKE 'sqlite_%'"
)
}
if tables != {"samples", "sample_parts"}:
self.error(
"energon_sqlite_schema",
f"unexpected tables {sorted(tables)}",
path,
)
for table, column in (("samples", "sample_key"), ("sample_parts", "part_name")):
if table not in tables:
continue
limit = "" if self.mode == "final" else " LIMIT 256"
for (value,) in conn.execute(
f'SELECT "{column}" FROM "{table}"{limit}'
):
if isinstance(value, str):
self.check_string_leak(value, path, column)
finally:
conn.close()
except sqlite3.Error as exc:
self.error("energon_sqlite_error", str(exc), path)
# ------------------------------------------------------------------
# Annotation JSONL and view mapping
# ------------------------------------------------------------------
def check_views_and_view_mappings(self) -> None:
for key in sorted(self.views):
view = self.views[key]
count, sample_rows = self.check_indexed_jsonl(view)
view.record_count = count
mapping_dir = (
self.root
/ "mappings"
/ "views"
/ view.dataset_id
/ view.view_id
)
if self._pa is None:
continue
files = self.check_parquet_files(
mapping_dir, VIEW_MAP_FIELDS, INTEGER_VIEW_FIELDS
)
if not files:
continue
if self.mode == "final":
self.check_view_mapping_final(view, files)
else:
self.check_view_mapping_unit(view, files, sample_rows)
total = sum(view.record_count for view in self.views.values())
hosted = sum(
view.record_count
for view in self.views.values()
if not (view.pools & set(RESTRICTED))
)
restricted = total - hosted
self.metrics["record_count"] = total
self.metrics["hosted_record_count"] = hosted
self.metrics["restricted_record_count"] = restricted
self.metrics["view_mapping_row_count"] = sum(
view.mapping_row_count for view in self.views.values()
)
restricted_view_by_pool = {
pool_id: self.views.get((row["dataset_id"], row["view_id"]))
for pool_id, row in RESTRICTED.items()
}
for pool_id, view in restricted_view_by_pool.items():
if view is None:
self.error(
"missing_restricted_view",
f"restricted view for {pool_id} is missing",
)
continue
expected = RESTRICTED[pool_id]["record_count"]
if view.record_count != expected:
self.error(
"restricted_view_record_count",
f"{view.dataset_id}/{view.view_id} has {view.record_count}, "
f"expected {expected}",
view.path,
)
if view.pools != {pool_id}:
self.error(
"restricted_view_pool",
f"restricted view pools={sorted(view.pools)}, expected [{pool_id}]",
view.path / "metadataset.yaml",
)
def check_indexed_jsonl(self, view: ViewInfo) -> tuple[int, dict[int, list[dict[str, Any]]]]:
data_path = view.path / "records.jsonl"
idx_path = view.path / "records.jsonl.idx"
samples: dict[int, list[dict[str, Any]]] = {}
if not data_path.is_file() or not idx_path.is_file():
return 0, samples
try:
size = data_path.stat().st_size
idx_size = idx_path.stat().st_size
if idx_size < 16 or idx_size % 8:
self.error(
"bad_jsonl_index_size",
"index must contain N+1 little-endian uint64 offsets",
idx_path,
)
return 0, samples
count = idx_size // 8 - 1
with idx_path.open("rb") as idx_handle:
with mmap.mmap(idx_handle.fileno(), 0, access=mmap.ACCESS_READ) as index:
first = struct.unpack_from("<Q", index, 0)[0]
last = struct.unpack_from("<Q", index, count * 8)[0]
if first != 0:
self.error("bad_jsonl_index", "first offset must be zero", idx_path)
if last != size:
self.error(
"bad_jsonl_index",
f"last offset {last} does not equal JSONL size {size}",
idx_path,
)
previous = -1
for position in range(count + 1):
value = struct.unpack_from("<Q", index, position * 8)[0]
if value <= previous and position:
self.error(
"nonmonotonic_jsonl_index",
f"offset {value} follows {previous} at index {position}",
idx_path,
)
break
if value > size:
self.error(
"jsonl_index_out_of_bounds",
f"offset {value} exceeds JSONL size {size}",
idx_path,
)
break
previous = value
positions = self.sample_positions(count)
if self.mode == "final":
occurrences = self.scan_all_records(view, data_path, index, count)
view.media_occurrence_count = occurrences
else:
with data_path.open("rb") as data:
for row_id in positions:
start = struct.unpack_from("<Q", index, row_id * 8)[0]
end = struct.unpack_from("<Q", index, (row_id + 1) * 8)[0]
data.seek(start)
raw = data.read(end - start)
record = self.parse_record(raw, view, row_id, data_path)
if record is not None:
samples[row_id] = self.media_occurrences(
record, view, row_id
)
return count, samples
except (OSError, ValueError, struct.error) as exc:
self.error("jsonl_index_io", str(exc), idx_path)
return 0, samples
def scan_all_records(
self, view: ViewInfo, data_path: Path, index: mmap.mmap, count: int
) -> int:
occurrence_count = 0
offset = 0
with data_path.open("rb") as handle:
for row_id in range(count):
expected = struct.unpack_from("<Q", index, row_id * 8)[0]
if offset != expected:
self.error(
"jsonl_index_boundary",
f"row {row_id} starts at {offset}, index says {expected}",
data_path,
)
handle.seek(expected)
offset = expected
raw = handle.readline()
offset += len(raw)
expected_end = struct.unpack_from("<Q", index, (row_id + 1) * 8)[0]
if offset != expected_end:
self.error(
"jsonl_index_boundary",
f"row {row_id} ends at {offset}, index says {expected_end}",
data_path,
)
handle.seek(expected_end)
offset = expected_end
record = self.parse_record(raw, view, row_id, data_path)
if record is not None:
occurrence_count += len(self.media_occurrences(record, view, row_id))
if handle.read(1):
self.error("jsonl_trailing_data", "data remains after indexed rows", data_path)
return occurrence_count
def parse_record(
self, raw: bytes, view: ViewInfo, row_id: int, path: Path
) -> dict[str, Any] | None:
if not raw.endswith(b"\n"):
self.error("jsonl_newline", f"row {row_id} lacks final newline", path)
try:
record = json.loads(raw)
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
self.error("invalid_jsonl", f"row {row_id}: {exc}", path)
return None
if not isinstance(record, dict):
self.error("invalid_record", f"row {row_id} is not an object", path)
return None
source = record.get("_source")
if not isinstance(source, dict):
self.error("missing_record_source", f"row {row_id} lacks _source", path)
else:
if source.get("dataset_id") != view.dataset_id:
self.error(
"record_dataset_id",
f"row {row_id} dataset_id mismatch",
path,
)
if source.get("view_id") != view.view_id:
self.error("record_view_id", f"row {row_id} view_id mismatch", path)
if source.get("schema") != "eagle-energon.source-record/v1":
self.error("record_schema", f"row {row_id} source schema mismatch", path)
source_annotation = source.get("source_annotation")
if not isinstance(source_annotation, str) or self.is_absolute_or_escaping(
source_annotation
):
self.error(
"record_source_annotation",
f"row {row_id} source_annotation must be relative",
path,
)
if record.get("task_type") not in ALLOWED_TASK_TYPES:
self.error(
"record_task_type",
f"row {row_id} has forbidden task_type {record.get('task_type')!r}",
path,
)
self.scan_structured_value(
record,
path,
allow_query_label_keys=True,
)
return record
def media_occurrences(
self, record: Any, view: ViewInfo, row_id: int
) -> list[dict[str, Any]]:
found: list[dict[str, Any]] = []
def walk(value: Any, pointer: str) -> None:
if isinstance(value, dict):
if {"kind", "source", "path"}.issubset(value):
kind = value.get("kind")
aux_source = value.get("source")
member = value.get("path")
if kind not in ALLOWED_MEDIA_KINDS:
self.error(
"record_media_kind",
f"row {row_id} pointer {pointer} has kind {kind!r}",
view.path / "records.jsonl",
)
if aux_source not in view.aux:
self.error(
"record_aux_source",
f"row {row_id} pointer {pointer} uses unknown aux "
f"{aux_source!r}",
view.path / "records.jsonl",
)
pool_id = ""
else:
pool_id = view.aux[aux_source]
if not isinstance(member, str) or not MEMBER_RE.fullmatch(member):
self.error(
"record_member_name",
f"row {row_id} pointer {pointer} has invalid member {member!r}",
view.path / "records.jsonl",
)
found.append(
{
"row_id": row_id,
"occurrence": len(found),
"json_pointer": pointer or "/",
"aux_source": aux_source,
"pool_id": pool_id,
"member_name": member,
"media_kind": kind,
}
)
return
for key, child in value.items():
escaped = str(key).replace("~", "~0").replace("/", "~1")
walk(child, f"{pointer}/{escaped}")
elif isinstance(value, list):
for index, child in enumerate(value):
walk(child, f"{pointer}/{index}")
walk(record, "")
if not found:
self.error(
"record_without_media",
f"row {row_id} has no media locator",
view.path / "records.jsonl",
)
return found
def check_view_mapping_unit(
self,
view: ViewInfo,
files: Sequence[Path],
sampled_records: dict[int, list[dict[str, Any]]],
) -> None:
row_count = self.parquet_row_count(files)
view.mapping_row_count = row_count
row_ids = sorted(sampled_records)
if not row_ids:
return
try:
dataset = self._pds.dataset([str(path) for path in files], format="parquet")
table = dataset.to_table(
filter=self._pds.field("row_id").isin(row_ids)
)
rows = table.to_pylist()
self.validate_view_rows(view, rows, full=False)
expected = {
(
item["row_id"],
item["occurrence"],
item["json_pointer"],
item["aux_source"],
item["pool_id"],
item["member_name"],
item["media_kind"],
)
for values in sampled_records.values()
for item in values
}
actual = {
(
row["row_id"],
row["occurrence"],
row["json_pointer"],
row["aux_source"],
row["pool_id"],
row["member_name"],
row["media_kind"],
)
for row in rows
}
if actual != expected:
self.error(
"sample_record_mapping_mismatch",
f"sample mapping differs; missing={list(expected-actual)[:5]}, "
f"extra={list(actual-expected)[:5]}",
files[0].parent,
)
except Exception as exc:
self.error("view_mapping_sample", str(exc), files[0].parent)
def check_view_mapping_final(
self, view: ViewInfo, files: Sequence[Path]
) -> None:
fd, db_name = tempfile.mkstemp(
prefix="locany-view-", suffix=".sqlite", dir=self.temp_dir
)
os.close(fd)
db_path = Path(db_name)
try:
conn = sqlite3.connect(db_path)
conn.execute("PRAGMA journal_mode=OFF")
conn.execute("PRAGMA synchronous=OFF")
conn.execute("PRAGMA temp_store=FILE")
conn.execute(
"CREATE TABLE edge("
"row_id INTEGER NOT NULL, occurrence INTEGER NOT NULL, "
"json_pointer TEXT NOT NULL, aux_source TEXT NOT NULL, "
"pool_id TEXT NOT NULL, member_name TEXT NOT NULL, "
"media_kind TEXT NOT NULL, source_id INTEGER NOT NULL, "
"PRIMARY KEY(row_id, occurrence)) WITHOUT ROWID"
)
last: tuple[int, int] | None = None
rows_total = 0
for batch in self.iter_parquet_batches(files):
rows = batch.to_pylist()
self.validate_view_rows(view, rows, full=True)
inserts = []
for row in rows:
key = (int(row["row_id"]), int(row["occurrence"]))
if last is not None and key <= last:
self.error(
"view_mapping_sort",
f"mapping key {key} follows {last}",
files[0].parent,
)
last = key
inserts.append(
(
*key,
row["json_pointer"],
row["aux_source"],
row["pool_id"],
row["member_name"],
row["media_kind"],
row["source_id"],
)
)
try:
conn.executemany(
"INSERT INTO edge VALUES(?,?,?,?,?,?,?,?)", inserts
)
except sqlite3.IntegrityError as exc:
self.error(
"duplicate_view_mapping_key",
str(exc),
files[0].parent,
)
rows_total += len(rows)
conn.commit()
view.mapping_row_count = rows_total
# Re-read records into a bounded, per-view relation. The largest
# join is one view, never the entire 10M-record collection.
conn.execute(
"CREATE TABLE observed("
"row_id INTEGER NOT NULL, occurrence INTEGER NOT NULL, "
"json_pointer TEXT NOT NULL, aux_source TEXT NOT NULL, "
"pool_id TEXT NOT NULL, member_name TEXT NOT NULL, "
"media_kind TEXT NOT NULL, "
"PRIMARY KEY(row_id, occurrence)) WITHOUT ROWID"
)
self.insert_observed_occurrences(view, conn)
observed_count = conn.execute("SELECT count(*) FROM observed").fetchone()[0]
view.media_occurrence_count = observed_count
if rows_total != observed_count:
self.error(
"view_mapping_count",
f"mapping rows={rows_total}, media occurrences={observed_count}",
files[0].parent,
)
missing = conn.execute(
"SELECT count(*) FROM observed o LEFT JOIN edge e "
"USING(row_id, occurrence) WHERE e.row_id IS NULL"
).fetchone()[0]
extra = conn.execute(
"SELECT count(*) FROM edge e LEFT JOIN observed o "
"USING(row_id, occurrence) WHERE o.row_id IS NULL"
).fetchone()[0]
mismatch = conn.execute(
"SELECT count(*) FROM observed o JOIN edge e USING(row_id, occurrence) "
"WHERE o.json_pointer<>e.json_pointer OR o.aux_source<>e.aux_source "
"OR o.pool_id<>e.pool_id OR o.member_name<>e.member_name "
"OR o.media_kind<>e.media_kind"
).fetchone()[0]
if missing or extra or mismatch:
self.error(
"record_mapping_exactness",
f"missing_edges={missing}, extra_edges={extra}, "
f"field_mismatches={mismatch}",
files[0].parent,
)
except (OSError, sqlite3.Error) as exc:
self.error("view_mapping_join", str(exc), files[0].parent)
finally:
with contextlib.suppress(Exception):
conn.close() # type: ignore[possibly-undefined]
db_path.unlink(missing_ok=True)
def insert_observed_occurrences(
self, view: ViewInfo, conn: sqlite3.Connection
) -> None:
data_path = view.path / "records.jsonl"
with data_path.open("rb") as handle:
batch: list[tuple[Any, ...]] = []
for row_id, raw in enumerate(handle):
record = self.parse_record(raw, view, row_id, data_path)
if record is None:
continue
for item in self.media_occurrences(record, view, row_id):
batch.append(
(
item["row_id"],
item["occurrence"],
item["json_pointer"],
item["aux_source"],
item["pool_id"],
item["member_name"],
item["media_kind"],
)
)
if len(batch) >= 65_536:
conn.executemany(
"INSERT INTO observed VALUES(?,?,?,?,?,?,?)", batch
)
batch.clear()
if batch:
conn.executemany("INSERT INTO observed VALUES(?,?,?,?,?,?,?)", batch)
conn.commit()
def validate_view_rows(
self, view: ViewInfo, rows: Sequence[dict[str, Any]], full: bool
) -> None:
path = self.root / "mappings" / "views" / view.dataset_id / view.view_id
for row in rows:
if set(row) != VIEW_MAP_FIELDS:
self.error("view_mapping_fields", "row fields differ from schema", path)
continue
if row.get("schema") != "locate-anything.public-view-source-map/v1":
self.error("view_mapping_schema", "bad row schema", path)
if row.get("dataset_id") != view.dataset_id:
self.error("view_mapping_dataset", "dataset_id mismatch", path)
if row.get("view_id") != view.view_id:
self.error("view_mapping_view", "view_id mismatch", path)
if row.get("pool_id") not in view.pools:
self.error("view_mapping_pool", "pool_id not declared by view aux", path)
if row.get("aux_source") not in view.aux:
self.error("view_mapping_aux", "aux_source not declared by view", path)
elif view.aux[row["aux_source"]] != row.get("pool_id"):
self.error("view_mapping_aux", "aux_source/pool_id binding mismatch", path)
self.validate_mapping_common(row, path, view_mapping=True)
row_id = row.get("row_id")
if isinstance(row_id, int) and not 0 <= row_id < view.record_count:
self.error(
"view_mapping_row_id",
f"row_id {row_id} outside [0,{view.record_count})",
path,
)
# ------------------------------------------------------------------
# Media mapping and foreign keys
# ------------------------------------------------------------------
def check_media_mappings(self) -> None:
if self._pa is None:
return
root = self.root / "mappings" / "media"
if not root.is_dir():
self.error("missing_media_mappings", "mappings/media is required", root)
return
actual_dirs = {path.name for path in root.iterdir() if path.is_dir()}
for path in root.iterdir():
if not path.is_dir():
self.error("mapping_stray", "unexpected file in mappings/media", path)
if actual_dirs != set(self.pools):
self.error(
"media_mapping_closure",
f"missing={sorted(set(self.pools)-actual_dirs)}, "
f"extra={sorted(actual_dirs-set(self.pools))}",
root,
)
for pool_id in sorted(set(self.pools) & actual_dirs):
pool = self.pools[pool_id]
files = self.check_parquet_files(
root / pool_id, MEDIA_MAP_FIELDS, INTEGER_MEDIA_FIELDS
)
if not files:
continue
if self.mode == "final":
count = self.validate_media_mapping_final(pool, files)
else:
count = self.parquet_row_count(files)
rows = self.sample_parquet_rows(files)
self.validate_media_rows(pool, rows)
pool.mapping_row_count = count
if pool.restricted:
expected = RESTRICTED[pool_id]["record_count"]
if count != expected:
self.error(
"restricted_mapping_count",
f"mapping rows={count}, expected source aliases={expected}",
files[0].parent,
)
self.metrics["media_mapping_row_count"] = sum(
pool.mapping_row_count for pool in self.pools.values()
)
def validate_media_mapping_final(
self, pool: PoolInfo, files: Sequence[Path]
) -> int:
total = 0
last_source_id: int | None = None
seen_tar_paths: set[str] = set()
for batch in self.iter_parquet_batches(files):
rows = batch.to_pylist()
self.validate_media_rows(pool, rows)
for row in rows:
source_id = row.get("source_id")
if isinstance(source_id, int):
if last_source_id is not None and source_id <= last_source_id:
self.error(
"media_mapping_sort",
f"source_id {source_id} follows {last_source_id}",
files[0].parent,
)
last_source_id = source_id
tar_relpath = row.get("tar_relpath")
if isinstance(tar_relpath, str):
seen_tar_paths.add(tar_relpath)
total += len(rows)
expected_tars = {
f"media/{pool.pool_id}/shards/{path.name}" for path in pool.tar_paths
}
if not pool.restricted and seen_tar_paths != expected_tars:
self.error(
"mapping_tar_closure",
f"mapping TAR refs differ; missing={sorted(expected_tars-seen_tar_paths)}, "
f"extra={sorted(seen_tar_paths-expected_tars)}",
files[0].parent,
)
return total
def validate_media_rows(
self, pool: PoolInfo, rows: Sequence[dict[str, Any]]
) -> None:
path = self.root / "mappings" / "media" / pool.pool_id
expected_availability = (
"upstream_download_required" if pool.restricted else "hosted"
)
for row in rows:
if set(row) != MEDIA_MAP_FIELDS:
self.error("media_mapping_fields", "row fields differ from schema", path)
continue
if row.get("schema") != "locate-anything.public-media-source-map/v1":
self.error("media_mapping_schema", "bad row schema", path)
if row.get("pool_id") != pool.pool_id:
self.error("media_mapping_pool", "pool_id mismatch", path)
if row.get("availability") != expected_availability:
self.error(
"media_mapping_availability",
f"availability must be {expected_availability!r}",
path,
)
self.validate_mapping_common(row, path, view_mapping=False)
if row.get("source_media_name") == row.get("member_name") or (
isinstance(row.get("source_media_name"), str)
and MEMBER_RE.fullmatch(row["source_media_name"])
):
self.error(
"packed_name_as_source",
"source_media_name must be the original filename, not packed member",
path,
)
if pool.restricted:
for key in ("tar_relpath", "payload_offset", "payload_length"):
if row.get(key) is not None:
self.error(
"restricted_mapping_payload",
f"{key} must be null for restricted media",
path,
)
else:
tar_relpath = row.get("tar_relpath")
offset = row.get("payload_offset")
length = row.get("payload_length")
if not isinstance(tar_relpath, str) or not re.fullmatch(
rf"media/{re.escape(pool.pool_id)}/"
r"shards/image-[0-9]{8}\.tar",
tar_relpath,
):
self.error(
"hosted_mapping_tar_path",
"tar_relpath must be repository-relative "
f"media/{pool.pool_id}/shards/image-NNNNNNNN.tar",
path,
)
else:
tar_size = pool.tar_sizes.get(tar_relpath)
if tar_size is None:
self.error(
"hosted_mapping_missing_tar",
f"referenced TAR {tar_relpath} is missing",
path,
)
elif isinstance(offset, int) and isinstance(length, int):
if offset < 512 or length < 0 or offset + length > tar_size:
self.error(
"hosted_mapping_payload_bounds",
f"payload [{offset},{offset+length}) outside {tar_relpath}",
path,
)
if not isinstance(offset, int) or not isinstance(length, int):
self.error(
"hosted_mapping_payload",
"hosted payload_offset/payload_length must be integers",
path,
)
def validate_mapping_common(
self, row: Mapping[str, Any], path: Path, view_mapping: bool
) -> None:
integer_fields = INTEGER_VIEW_FIELDS if view_mapping else INTEGER_MEDIA_FIELDS
for key in integer_fields:
value = row.get(key)
if value is not None and (not isinstance(value, int) or value < 0):
self.error("mapping_integer", f"{key} must be a nonnegative integer", path)
for key in ("source_record_sha256",) if view_mapping else (
"source_sha256",
"content_sha256",
):
value = row.get(key)
if not isinstance(value, str) or not SHA256_RE.fullmatch(value):
self.error("mapping_sha256", f"{key} must be lowercase SHA-256", path)
member = row.get("member_name")
if not isinstance(member, str) or not MEMBER_RE.fullmatch(member):
self.error("mapping_member", "invalid member_name", path)
if row.get("media_kind") not in ALLOWED_MEDIA_KINDS:
self.error("mapping_media_kind", "invalid media_kind", path)
relative_fields = (
("source_annotation",) if view_mapping else ("source_relative_path",)
)
for key in relative_fields:
value = row.get(key)
if not isinstance(value, str) or self.is_absolute_or_escaping(value):
self.error("mapping_relative_path", f"{key} must be relative", path)
if view_mapping:
pointer = row.get("json_pointer")
if not isinstance(pointer, str) or not pointer.startswith("/"):
self.error("mapping_json_pointer", "json_pointer must start with /", path)
self.scan_structured_value(dict(row), path)
def check_mapping_foreign_keys(self) -> None:
if self._pa is None or not self.views or not self.pools:
return
if self.mode == "unit":
self.check_mapping_foreign_keys_unit()
return
for pool_id in sorted(self.pools):
pool_files = self.parquet_parts(
self.root / "mappings" / "media" / pool_id
)
if not pool_files:
continue
fd, db_name = tempfile.mkstemp(
prefix="locany-fk-", suffix=".sqlite", dir=self.temp_dir
)
os.close(fd)
db_path = Path(db_name)
try:
conn = sqlite3.connect(db_path)
conn.execute("PRAGMA journal_mode=OFF")
conn.execute("PRAGMA synchronous=OFF")
conn.execute("PRAGMA temp_store=FILE")
conn.execute(
"CREATE TABLE media("
"source_id INTEGER PRIMARY KEY, member_name TEXT NOT NULL, "
"media_kind TEXT NOT NULL)"
)
for batch in self.iter_parquet_batches(
pool_files, columns=["source_id", "member_name", "media_kind"]
):
try:
conn.executemany(
"INSERT INTO media VALUES(?,?,?)",
zip(
batch.column(0).to_pylist(),
batch.column(1).to_pylist(),
batch.column(2).to_pylist(),
),
)
except sqlite3.IntegrityError as exc:
self.error(
"duplicate_media_source_id",
str(exc),
pool_files[0].parent,
)
conn.execute(
"CREATE TABLE edge("
"source_id INTEGER NOT NULL, member_name TEXT NOT NULL, "
"media_kind TEXT NOT NULL)"
)
expected_views = [
view for view in self.views.values() if pool_id in view.pools
]
for view in expected_views:
files = self.parquet_parts(
self.root
/ "mappings"
/ "views"
/ view.dataset_id
/ view.view_id
)
for batch in self.iter_parquet_batches(
files,
columns=["pool_id", "source_id", "member_name", "media_kind"],
):
rows = zip(
batch.column(0).to_pylist(),
batch.column(1).to_pylist(),
batch.column(2).to_pylist(),
batch.column(3).to_pylist(),
)
conn.executemany(
"INSERT INTO edge VALUES(?,?,?)",
(
(source_id, member_name, media_kind)
for row_pool, source_id, member_name, media_kind in rows
if row_pool == pool_id
),
)
conn.commit()
missing = conn.execute(
"SELECT count(*) FROM edge e LEFT JOIN media m USING(source_id) "
"WHERE m.source_id IS NULL"
).fetchone()[0]
mismatch = conn.execute(
"SELECT count(*) FROM edge e JOIN media m USING(source_id) "
"WHERE e.member_name<>m.member_name OR e.media_kind<>m.media_kind"
).fetchone()[0]
if missing or mismatch:
self.error(
"mapping_foreign_key",
f"pool {pool_id}: missing={missing}, mismatched={mismatch}",
pool_files[0].parent,
)
except (OSError, sqlite3.Error) as exc:
self.error("mapping_foreign_key", str(exc), pool_files[0].parent)
finally:
with contextlib.suppress(Exception):
conn.close() # type: ignore[possibly-undefined]
db_path.unlink(missing_ok=True)
def check_mapping_foreign_keys_unit(self) -> None:
for view in self.views.values():
files = self.parquet_parts(
self.root
/ "mappings"
/ "views"
/ view.dataset_id
/ view.view_id
)
if not files:
continue
for row in self.sample_parquet_rows(files):
pool_id = row.get("pool_id")
source_id = row.get("source_id")
if pool_id not in self.pools or not isinstance(source_id, int):
continue
media_files = self.parquet_parts(
self.root / "mappings" / "media" / pool_id
)
if not media_files:
continue
try:
dataset = self._pds.dataset(
[str(path) for path in media_files], format="parquet"
)
table = dataset.to_table(
columns=["source_id", "member_name", "media_kind"],
filter=self._pds.field("source_id") == source_id,
)
matches = table.to_pylist()
if len(matches) != 1:
self.error(
"sample_mapping_foreign_key",
f"({pool_id},{source_id}) has {len(matches)} media rows",
files[0].parent,
)
elif (
matches[0]["member_name"] != row.get("member_name")
or matches[0]["media_kind"] != row.get("media_kind")
):
self.error(
"sample_mapping_foreign_key",
f"({pool_id},{source_id}) member/kind mismatch",
files[0].parent,
)
except Exception as exc:
self.error("sample_mapping_foreign_key", str(exc), files[0].parent)
# ------------------------------------------------------------------
# Parquet helpers
# ------------------------------------------------------------------
def check_parquet_files(
self,
directory: Path,
expected_fields: set[str],
integer_fields: set[str],
) -> list[Path]:
files = self.parquet_parts(directory)
if not files:
self.error(
"missing_parquet_parts",
"at least one part-NNNNN.parquet is required",
directory,
)
return []
for position, path in enumerate(files):
expected_name = f"part-{position:05d}.parquet"
if path.name != expected_name:
self.error(
"parquet_part_sequence",
f"expected {expected_name}, found {path.name}",
path,
)
try:
parquet = self._pq.ParquetFile(path)
names = set(parquet.schema_arrow.names)
if names != expected_fields:
self.error(
"parquet_schema_fields",
f"fields differ; missing={sorted(expected_fields-names)}, "
f"extra={sorted(names-expected_fields)}",
path,
)
for field in parquet.schema_arrow:
if field.name in integer_fields:
if not self._pa.types.is_integer(field.type):
self.error(
"parquet_schema_type",
f"{field.name} must be integer, got {field.type}",
path,
)
elif not self._pa.types.is_string(field.type):
self.error(
"parquet_schema_type",
f"{field.name} must be string, got {field.type}",
path,
)
metadata = parquet.metadata
if metadata.num_rows == 0:
self.error("empty_parquet_part", "Parquet part cannot be empty", path)
for row_group in range(metadata.num_row_groups):
for column in range(metadata.num_columns):
compression = metadata.row_group(row_group).column(column).compression
if compression.upper() != "ZSTD":
self.error(
"parquet_compression",
f"row group {row_group} column {column} uses "
f"{compression}, expected ZSTD",
path,
)
except Exception as exc:
self.error("invalid_parquet", str(exc), path)
return files
def parquet_parts(self, directory: Path) -> list[Path]:
if not directory.is_dir():
return []
files = sorted(directory.glob("*.parquet"))
for path in directory.iterdir():
if path.is_file() and path.suffix == ".parquet" and not PART_RE.fullmatch(
path.name
):
self.error("bad_parquet_part_name", "unexpected Parquet filename", path)
elif not path.is_file():
self.error("mapping_nested_path", "mapping parts cannot be nested", path)
elif path.suffix != ".parquet":
self.error("mapping_duplicate_format", "only Parquet parts are allowed", path)
return [path for path in files if PART_RE.fullmatch(path.name)]
def parquet_row_count(self, files: Sequence[Path]) -> int:
total = 0
for path in files:
try:
total += self._pq.ParquetFile(path).metadata.num_rows
except Exception as exc:
self.error("parquet_metadata", str(exc), path)
return total
def iter_parquet_batches(
self,
files: Sequence[Path],
columns: Sequence[str] | None = None,
) -> Iterator[Any]:
for path in files:
parquet = self._pq.ParquetFile(path)
yield from parquet.iter_batches(batch_size=65_536, columns=columns)
def sample_parquet_rows(self, files: Sequence[Path]) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for path in files:
parquet = self._pq.ParquetFile(path)
if parquet.metadata.num_rows == 0:
self.error("empty_parquet_part", "Parquet part cannot be empty", path)
continue
first = next(parquet.iter_batches(batch_size=min(32, self.sample_records)))
rows.extend(first.to_pylist())
if parquet.metadata.num_rows > len(first):
last_group = parquet.read_row_group(parquet.metadata.num_row_groups - 1)
tail_count = min(32, self.sample_records, len(last_group))
last = last_group.slice(len(last_group) - tail_count, tail_count)
rows.extend(last.to_pylist())
return rows
# ------------------------------------------------------------------
# Manifest and immutable hashes
# ------------------------------------------------------------------
def check_manifest(self) -> None:
manifest_root = self.root / "manifests"
required = {
"release.json",
"files.jsonl",
"datasets.jsonl",
"views.jsonl",
"media-pools.jsonl",
"restricted-media.json",
}
for name in required:
if not (manifest_root / name).is_file():
self.error("missing_manifest", f"required manifest {name} is missing", manifest_root)
self.check_catalog_manifest(
manifest_root / "datasets.jsonl",
"dataset_id",
{dataset_id for dataset_id, _ in self.views},
)
self.check_catalog_manifest(
manifest_root / "views.jsonl",
("dataset_id", "view_id"),
set(self.views),
)
self.check_catalog_manifest(
manifest_root / "media-pools.jsonl",
"pool_id",
set(self.pools),
)
restricted_doc = self.read_json(manifest_root / "restricted-media.json")
restricted_rows: Any = restricted_doc
if isinstance(restricted_doc, dict):
restricted_rows = restricted_doc.get("pools")
if isinstance(restricted_rows, list):
ids = {
row.get("pool_id")
for row in restricted_rows
if isinstance(row, dict) and isinstance(row.get("pool_id"), str)
}
if ids != set(RESTRICTED):
self.error(
"restricted_manifest_set",
f"actual={sorted(ids)}, expected={sorted(RESTRICTED)}",
manifest_root / "restricted-media.json",
)
elif restricted_doc is not None:
self.error(
"restricted_manifest_shape",
"restricted-media.json must be a list or {pools:[...]}",
manifest_root / "restricted-media.json",
)
files_path = manifest_root / "files.jsonl"
rows = self.read_jsonl_manifest(files_path)
for row_no, row in enumerate(rows):
rel = row.get("path", row.get("relpath"))
size = row.get("bytes", row.get("size"))
digest = row.get("sha256")
if not isinstance(rel, str) or self.is_absolute_or_escaping(rel):
self.error(
"manifest_path",
f"row {row_no} has invalid path {rel!r}",
files_path,
)
continue
normalized = PurePosixPath(rel).as_posix()
if normalized in self.manifest_rows:
self.error(
"manifest_duplicate_path",
f"duplicate manifest path {normalized}",
files_path,
)
continue
if not isinstance(size, int) or size < 0:
self.error(
"manifest_size",
f"{normalized}: invalid byte size {size!r}",
files_path,
)
if not isinstance(digest, str) or not SHA256_RE.fullmatch(digest):
self.error(
"manifest_sha256",
f"{normalized}: invalid SHA-256",
files_path,
)
self.manifest_rows[normalized] = row
# A hash manifest cannot contain its own final byte size and digest
# without a recursive fixed point. It is the sole allowed unlisted
# upload object; all other regular files must be listed exactly once.
self_path = "manifests/files.jsonl"
actual = set(self.files) - {self_path}
listed = set(self.manifest_rows)
if actual != listed:
self.error(
"manifest_file_closure",
f"missing={sorted(actual-listed)[:50]}, "
f"nonexistent={sorted(listed-actual)[:50]}",
files_path,
)
for rel in sorted(actual & listed):
expected_size = self.manifest_rows[rel].get(
"bytes", self.manifest_rows[rel].get("size")
)
if self.files[rel].st_size != expected_size:
self.error(
"manifest_size_mismatch",
f"actual={self.files[rel].st_size}, manifest={expected_size}",
rel,
)
tar_hashes: dict[str, str] = {}
for rel, row in self.manifest_rows.items():
if rel.endswith(".tar") and isinstance(row.get("sha256"), str):
digest = row["sha256"]
other = tar_hashes.get(digest)
if other is not None:
self.error(
"duplicate_tar_content",
f"TAR content duplicates {other}",
rel,
)
tar_hashes[digest] = rel
candidates = self.hash_candidates(actual & listed)
self.metrics["manifest_file_count"] = len(self.manifest_rows)
self.metrics["hash_verified_file_count"] = len(candidates)
if candidates:
with concurrent.futures.ThreadPoolExecutor(
max_workers=self.hash_jobs
) as executor:
futures = {
executor.submit(self.sha256_file, self.root / rel): rel
for rel in candidates
}
for future in concurrent.futures.as_completed(futures):
rel = futures[future]
try:
actual_digest = future.result()
except OSError as exc:
self.error("hash_io", str(exc), rel)
continue
expected_digest = self.manifest_rows[rel].get("sha256")
if actual_digest != expected_digest:
self.error(
"manifest_hash_mismatch",
f"actual={actual_digest}, manifest={expected_digest}",
rel,
)
def check_catalog_manifest(
self,
path: Path,
key: str | tuple[str, str],
expected: set[Any],
) -> None:
rows = self.read_jsonl_manifest(path)
actual: set[Any] = set()
for row in rows:
if isinstance(key, tuple):
value = tuple(row.get(item) for item in key)
else:
value = row.get(key)
if value in actual:
self.error("catalog_manifest_duplicate", f"duplicate key {value!r}", path)
actual.add(value)
if path.is_file() and actual != expected:
self.error(
"catalog_manifest_closure",
f"missing={sorted(expected-actual)[:50]}, "
f"extra={sorted(actual-expected)[:50]}",
path,
)
def hash_candidates(self, paths: set[str]) -> set[str]:
if self.hash_mode == "all":
return paths
if self.hash_mode == "none":
if self.mode == "final":
self.error(
"final_hashes_disabled",
"final mode requires --hash-mode all",
)
return set()
# unit/sample: hash all small control files plus deterministic media
# samples. This is never accepted by final mode.
selected = {
rel for rel in paths if self.files[rel].st_size <= 64 * 1024 * 1024
}
by_pool: dict[str, list[str]] = {}
for rel in paths:
match = re.fullmatch(r"media/([^/]+)/shards/.*\.tar", rel)
if match:
by_pool.setdefault(match.group(1), []).append(rel)
for values in by_pool.values():
values.sort()
selected.add(values[0])
selected.add(values[-1])
return selected
# ------------------------------------------------------------------
# Global metric gates and receipt
# ------------------------------------------------------------------
def check_expected_metrics(self) -> None:
for key, expected in EXPECTED.items():
actual = self.metrics.get(key)
if actual is None:
self.error("missing_metric", f"could not establish metric {key}")
elif actual != expected:
self.error(
"count_mismatch",
f"{key}={actual}, expected {expected}",
)
if self.mode == "final" and self.hash_mode != "all":
self.error("final_hash_mode", "final mode requires --hash-mode all")
def receipt(self) -> dict[str, Any]:
finished = dt.datetime.now(dt.timezone.utc).isoformat()
return {
"schema": RECEIPT_SCHEMA,
"verifier_version": VERIFIER_VERSION,
"generated_at": finished,
"root": str(self.root),
"mode": self.mode,
"hash_mode": self.hash_mode,
"status": "passed" if self.error_count == 0 else "failed",
"expected": EXPECTED,
"observed": self.metrics,
"error_count": self.error_count,
"warning_count": self.warning_count,
"errors_truncated": self.error_count > len(self.errors),
"warnings_truncated": self.warning_count > len(self.warnings),
"errors": self.errors,
"warnings": self.warnings,
"phases": self.phases,
"duration_seconds": round(time.monotonic() - self.started, 3),
}
def write_receipt(self) -> Path:
path = self.receipt_path.resolve()
try:
path.relative_to(self.root)
except ValueError:
pass
else:
fallback = self.root.parent / f"{self.root.name}.verify-receipt.json"
self.error(
"receipt_inside_release",
f"receipt requested inside release; redirected to {fallback}",
path,
)
path = fallback
path.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(
self.receipt(), ensure_ascii=False, indent=2, sort_keys=True
) + "\n"
fd, tmp_name = tempfile.mkstemp(
prefix=f".{path.name}.", dir=path.parent
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(payload)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_name, path)
finally:
with contextlib.suppress(FileNotFoundError):
os.unlink(tmp_name)
return path
# ------------------------------------------------------------------
# Generic parsers and leak scanning
# ------------------------------------------------------------------
def read_json(self, path: Path) -> Any:
if not path.is_file():
self.error("missing_json", "required JSON file is missing", path)
return None
try:
with path.open("r", encoding="utf-8") as handle:
value = json.load(handle)
self.scan_structured_value(value, path)
return value
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
self.error("invalid_json", str(exc), path)
return None
def read_yaml(self, path: Path) -> Any:
if not path.is_file():
self.error("missing_yaml", "required YAML file is missing", path)
return None
try:
with path.open("r", encoding="utf-8") as handle:
value = self._yaml.safe_load(handle)
self.scan_structured_value(value, path)
return value
except Exception as exc:
self.error("invalid_yaml", str(exc), path)
return None
def read_jsonl_manifest(self, path: Path) -> list[dict[str, Any]]:
if not path.is_file():
return []
rows: list[dict[str, Any]] = []
try:
with path.open("rb") as handle:
for row_no, raw in enumerate(handle):
try:
row = json.loads(raw)
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
self.error("invalid_jsonl", f"row {row_no}: {exc}", path)
continue
if not isinstance(row, dict):
self.error("invalid_jsonl", f"row {row_no} is not an object", path)
continue
self.scan_structured_value(row, path)
rows.append(row)
except OSError as exc:
self.error("jsonl_io", str(exc), path)
return rows
def scan_structured_value(
self,
value: Any,
path: Path,
key: str | None = None,
*,
json_path: tuple[str, ...] = (),
allow_query_label_keys: bool = False,
) -> None:
if isinstance(value, dict):
for child_key, child in value.items():
key_name = str(child_key)
normalized_key = key_name.casefold()
is_public_query_label = (
allow_query_label_keys
and json_path == ("query",)
and normalized_key in QUERY_LABEL_PRIVATE_KEY_EXCEPTIONS
)
if (
normalized_key in PRIVATE_KEY_NAMES
and not is_public_query_label
):
self.error(
"private_field",
f"forbidden private field {key_name!r}",
path,
)
self.scan_structured_value(
child,
path,
key_name,
json_path=(*json_path, key_name),
allow_query_label_keys=allow_query_label_keys,
)
elif isinstance(value, list):
for child in value:
self.scan_structured_value(
child,
path,
key,
json_path=(*json_path, "[]"),
allow_query_label_keys=allow_query_label_keys,
)
elif isinstance(value, str):
self.check_string_leak(value, path, key)
def check_string_leak(
self, value: str, path: Path, key: str | None
) -> None:
# JSON pointers are path-shaped by definition; e.g. ``/Home/...`` is
# a valid pointer, not evidence of a filesystem locator.
if key != "json_pointer" and INTERNAL_PATH_RE.search(value):
self.error("internal_path_leak", "internal absolute path detected", path)
if SECRET_RE.search(value):
self.error("credential_leak", "credential or signed URL detected", path)
if key is None:
return
key_lower = key.casefold()
path_like = (
key_lower == "path"
or key_lower.endswith("_path")
or key_lower.endswith("_relpath")
or key_lower in {"source_annotation", "root"}
)
if path_like and key_lower != "json_pointer":
if self.is_absolute_or_escaping(value):
self.error(
"absolute_or_escaping_path",
f"{key} must be a repository-relative path",
path,
)
@staticmethod
def is_absolute_or_escaping(value: str) -> bool:
if value.startswith("/") or WINDOWS_ABS_RE.match(value):
return True
parts = PurePosixPath(value.replace("\\", "/")).parts
return ".." in parts
def sample_positions(self, count: int) -> list[int]:
if count <= 0:
return []
wanted = min(count, self.sample_records)
if wanted == 1:
return [0]
return sorted(
{round(index * (count - 1) / (wanted - 1)) for index in range(wanted)}
)
@staticmethod
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb", buffering=8 * 1024 * 1024) as handle:
while chunk := handle.read(8 * 1024 * 1024):
digest.update(chunk)
return digest.hexdigest()
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Fail-closed verifier for LocateAnything-Data staging."
)
default_root = Path(__file__).resolve().parent.parent
parser.add_argument(
"root",
nargs="?",
type=Path,
default=default_root,
help=f"release staging root (default: {default_root})",
)
parser.add_argument(
"--mode",
choices=("unit", "final"),
default="unit",
help="unit samples payload rows; final scans and joins all rows",
)
parser.add_argument(
"--receipt",
type=Path,
help="receipt path (default: sibling of release root)",
)
parser.add_argument(
"--sample-records",
type=int,
default=7,
help="deterministic rows sampled per view/part in unit mode",
)
parser.add_argument(
"--hash-mode",
choices=("auto", "sample", "all", "none"),
default="auto",
help="manifest content verification; auto=sample for unit, all for final",
)
parser.add_argument(
"--hash-jobs",
type=int,
default=min(8, max(1, os.cpu_count() or 1)),
help="parallel manifest hashing workers",
)
parser.add_argument(
"--temp-dir",
type=Path,
help="node-local directory for bounded final-mode SQLite joins",
)
parser.add_argument(
"--max-errors",
type=int,
default=200,
help="maximum detailed errors retained in the receipt",
)
return parser.parse_args(argv)
def main(argv: Sequence[str] | None = None) -> int:
args = parse_args(argv)
root = args.root.resolve()
receipt = (
args.receipt
if args.receipt is not None
else root.parent / f"{root.name}.verify-receipt.json"
)
hash_mode = args.hash_mode
if hash_mode == "auto":
hash_mode = "all" if args.mode == "final" else "sample"
if args.temp_dir is not None:
args.temp_dir.mkdir(parents=True, exist_ok=True)
verifier = Verification(
root=root,
mode=args.mode,
receipt_path=receipt,
sample_records=args.sample_records,
hash_mode=hash_mode,
hash_jobs=args.hash_jobs,
temp_dir=args.temp_dir,
max_errors=args.max_errors,
)
try:
passed = verifier.run()
except BaseException as exc: # even KeyboardInterrupt produces a failed receipt
verifier.error("verifier_aborted", f"{type(exc).__name__}: {exc}")
passed = False
receipt_path = verifier.write_receipt()
status = "PASS" if passed and verifier.error_count == 0 else "FAIL"
print(
f"{status}: {verifier.error_count} error(s), "
f"{verifier.warning_count} warning(s); receipt={receipt_path}"
)
return 0 if status == "PASS" else 1
if __name__ == "__main__":
raise SystemExit(main())