taco-api-fixtures / verify /_common.py
csaybar's picture
Optimize remote fixture verification
75287e5 verified
Raw History Blame
10.6 kB
from __future__ import annotations
import hashlib
import json
import struct
import zipfile
from collections import Counter
from pathlib import Path
from typing import Any
import numpy as np
import pyarrow as pa
import rumi
import taco
PROTECTED = {"cozip:location", "taco:location"}
def digest_path(path: Path) -> str:
value = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
value.update(chunk)
return value.hexdigest()
def array_digest(value: Any) -> str:
array = np.ascontiguousarray(np.asarray(value))
return hashlib.sha256(array.tobytes(order="C")).hexdigest()
def load_manifest(root: Path) -> dict[str, Any]:
value = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
if value.get("schema_version") != 1:
raise AssertionError("unsupported fixture manifest schema")
if len(value.get("logical_cases", ())) != 10:
raise AssertionError("manifest must contain ten logical cases")
if len(value.get("datasets", ())) != 50:
raise AssertionError("manifest must contain fifty dataset entrypoints")
return value
def case_map(manifest: dict[str, Any]) -> dict[str, dict[str, Any]]:
return {item["id"]: item for item in manifest["logical_cases"]}
def expected_sources(case: dict[str, Any]) -> Counter[str]:
return Counter(asset["source_fixture"] for sample in case["samples"] for asset in sample["assets"])
def point_from_wkb(value: bytes) -> tuple[float, float]:
if len(value) != 21:
raise AssertionError("centroid is not a two-dimensional WKB point")
order, geometry_type, longitude, latitude = struct.unpack("<BIdd", value)
if order != 1 or geometry_type != 1:
raise AssertionError("centroid is not a little-endian WKB point")
if not (-180 <= longitude <= 180 and -90 <= latitude <= 90):
raise AssertionError("centroid is outside longitude/latitude bounds")
return longitude, latitude
def verify_checksums(root: Path) -> None:
checksum_path = root / "checksums.sha256"
expected = {}
for line in checksum_path.read_text(encoding="utf-8").splitlines():
checksum, relative = line.split(" ", 1)
expected[relative] = checksum
actual_files = sorted([path for path in (root / "data").rglob("*") if path.is_file()] + [root / "manifest.json"])
actual_names = {path.relative_to(root).as_posix() for path in actual_files}
if actual_names != set(expected):
missing = sorted(set(expected) - actual_names)
extra = sorted(actual_names - set(expected))
raise AssertionError(f"checksum inventory mismatch; missing={missing}, extra={extra}")
for path in actual_files:
relative = path.relative_to(root).as_posix()
if digest_path(path) != expected[relative]:
raise AssertionError(f"checksum mismatch: {relative}")
def verify_payload_names(path: Path, parts: list[Path], *, null_structure: bool) -> None:
def valid(name: str) -> bool:
relative = name.removeprefix("DATA/")
return relative.isdigit() if null_structure else relative.endswith(".rumi")
if path.is_dir() and path.name != ".tacocat":
names = [item.relative_to(path).as_posix() for item in (path / "DATA").rglob("*") if item.is_file()]
if not names or any(not valid(name) for name in names):
raise AssertionError(f"FOLDER DATA contains a non-Rumi payload: {path}")
archives = [path] if path.suffix == ".zip" else parts
for archive in archives:
with zipfile.ZipFile(archive) as source:
names = [name for name in source.namelist() if name.startswith("DATA/") and not name.endswith("/")]
if not names or any(not valid(name) for name in names):
raise AssertionError(f"ZIP DATA contains a non-Rumi payload: {archive}")
def verify_coordinate_profile(source: str | Path | list[str], case: dict[str, Any]) -> None:
profile = case["coordinate_profile"]
sample = taco.read(source, level="sample")
columns = set(sample.column_names)
if profile in {"none", "folder-stac"}:
if any(name.startswith(("geo:", "stac:", "istac:", "temporal:")) for name in columns):
raise AssertionError(f"{case['id']} unexpectedly stores sample coordinate metadata")
elif profile == "point":
if sample["geo:longitude"].null_count or sample["geo:latitude"].null_count:
raise AssertionError(f"{case['id']} has null point coordinates")
if not all(-180 <= value <= 180 for value in sample["geo:longitude"].to_pylist()):
raise AssertionError(f"{case['id']} has invalid longitude")
if not all(-90 <= value <= 90 for value in sample["geo:latitude"].to_pylist()):
raise AssertionError(f"{case['id']} has invalid latitude")
elif profile == "optional-point":
if sample["geo:longitude"].null_count != 2 or sample["geo:latitude"].null_count != 2:
raise AssertionError(f"{case['id']} does not exercise nullable points")
elif profile in {"stac", "stac-interval", "shared-stac"}:
for value in sample["stac:centroid"].to_pylist():
point_from_wkb(value)
if profile == "stac-interval" and sample["stac:time_end"].null_count:
raise AssertionError(f"{case['id']} has null STAC intervals")
if profile == "shared-stac":
for name in ("stac:crs", "stac:centroid", "stac:geotransform", "stac:time_start"):
if len(set(map(str, sample[name].to_pylist()))) != 1:
raise AssertionError(f"{case['id']} does not share {name}")
elif profile == "istac":
if sample["istac:geometry"].null_count:
raise AssertionError(f"{case['id']} has null ISTAC geometry")
for value in sample["istac:centroid"].to_pylist():
point_from_wkb(value)
elif profile == "temporal-only":
if sample["temporal:time_start"].null_count:
raise AssertionError(f"{case['id']} has null temporal coordinates")
if any(name.startswith(("geo:", "stac:", "istac:")) for name in columns):
raise AssertionError(f"{case['id']} unexpectedly stores spatial coordinates")
else:
raise AssertionError(f"unknown coordinate profile: {profile}")
if profile == "folder-stac":
children = taco.read(source, level="children")
if children["stac:centroid"].null_count:
raise AssertionError(f"{case['id']} has null folder STAC metadata")
for value in children["stac:centroid"].to_pylist():
point_from_wkb(value)
def logical_table(source: str | Path) -> pa.Table:
table = taco.read(source, layout="long")
excluded = {"sample_id", "source_file", "taco:location", "cozip:location"}
table = table.select([name for name in table.column_names if name not in excluded])
order = [(name, "ascending") for name in ("fixture:sample_key", "path") if name in table.column_names]
return table.sort_by(order)
def verify_dataset(
source: str | Path | list[str],
record: dict[str, Any],
case: dict[str, Any],
source_fixtures: dict[str, dict[str, Any]],
*,
check_payload_names: bool = False,
full_api: bool = True,
) -> dict[str, int]:
if isinstance(source, Path):
report = taco.validate(source)
report.raise_for_errors()
if report.warnings:
raise AssertionError(f"validation warnings for {record['id']}: {report.warnings}")
dataset = taco.open_dataset(source)
if dataset.collection.id != case["id"]:
raise AssertionError(f"collection id mismatch for {record['id']}")
if dataset.collection.sources is None and record["container"] == "tacocat" and not isinstance(source, list):
raise AssertionError(f"TACOCAT sources missing for {record['id']}")
long = taco.read(dataset, layout="long")
if long.num_rows != record["assets"]:
raise AssertionError(f"asset count mismatch for {record['id']}: {long.num_rows}")
if "taco:location" not in long.column_names or "cozip:location" in long.column_names:
raise AssertionError(f"generated location columns are wrong for {record['id']}")
remote = (isinstance(source, str) and source.startswith(("http://", "https://"))) or (
isinstance(source, list) and bool(source) and source[0].startswith(("http://", "https://"))
)
if remote and any("/vsicurl/http" not in value for value in long["taco:location"].to_pylist()):
raise AssertionError(f"remote subfile location is wrong for {record['id']}")
if Counter(long["rumi:source_fixture"].to_pylist()) != expected_sources(case):
raise AssertionError(f"Rumi source inventory mismatch for {record['id']}")
for row in long.select(["rumi:source_fixture", "rumi:header", "rumi:array_sha256", "taco:location"]).to_pylist():
fixture = source_fixtures[row["rumi:source_fixture"]]
if row["rumi:array_sha256"] != fixture["array_sha256"]:
raise AssertionError(f"stored array checksum mismatch for {record['id']}")
actual = array_digest(rumi.read(row["taco:location"], row["rumi:header"]))
if actual != fixture["array_sha256"]:
raise AssertionError(f"decoded Rumi mismatch for {record['id']}/{row['rumi:source_fixture']}")
if not full_api:
return {"samples": record["samples"], "assets": long.num_rows}
quiet = taco.read(dataset, layout="long", location=False)
if "taco:location" not in quiet.column_names or any(quiet["taco:location"].to_pylist()):
raise AssertionError(f"location=False failed for {record['id']}")
wide = taco.read(dataset, layout="wide")
if wide.num_rows != record["samples"]:
raise AssertionError(f"wide sample count mismatch for {record['id']}")
for level in dataset.contract.levels:
raw = taco.read(dataset, level=level)
if PROTECTED.intersection(raw.column_names):
raise AssertionError(f"raw level {level} exposes a protected location in {record['id']}")
verify_coordinate_profile(source, case)
if check_payload_names:
local_path = Path(source) if not isinstance(source, list) else None
if local_path is None:
raise AssertionError("payload name checks require a local entrypoint")
parts = [local_path.parents[3] / item for item in record["parts"]]
verify_payload_names(local_path, parts, null_structure=case["structure"] is None)
return {"samples": wide.num_rows, "assets": long.num_rows}