diff --git a/extensions/vendors.md b/extensions/vendors.md index 58a3971b..a33528bc 100644 --- a/extensions/vendors.md +++ b/extensions/vendors.md @@ -44,6 +44,31 @@ payload. Behavior defined only in `data` is non-portable. Quoted and unquoted values under `data` are shown in [`nonportable_extensions.md`](nonportable_extensions.md). +## Validating a vendor's payload + +`validation/validate.py` does not interpret `data` unless a vendor is named. With +`--vendor THOUGHTSPOT` it hands the `data` object of every `THOUGHTSPOT` entry in +a semantic model or a mapping document to the validator the vendor's own package +registers under the entry point group `ossie.vendor_validators`, with the token +from the table below as the entry point name. The validator is a callable +`check(payload, site)`: `payload` is a copy of the `data` object, and `site` has +`kind` (one of `model`, `dataset`, `field`, `metric`, `relationship`, `mapping`), +`name` (for `model` and `mapping`, the name of the document), and `dataset` (the +owning dataset of a field or a dataset-scoped metric, otherwise `None`). It +returns the messages to report, a single string for one message, or `None` for +none; the script prefixes each with the vendor and the site (`[Vendor +THOUGHTSPOT] Field 'orders.amount' in model 'sales': ...`) and counts it as an +error. A validator that raises, or exits, is reported the same way, with the +traceback on stderr. Vendor checks run on a document that passed the schema and +the other checks. Only the entries of the file being validated are handed over, +not those of a document it references, and entries of other vendors are not +handed over at all. The package has to be installed where the script runs; for a +uv run that is: + +```sh +uv run --with validation/validate.py --vendor THOUGHTSPOT model.yaml +``` + ## Known vendors | Vendor | Description | diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 76edb140..0a718ab6 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -1862,7 +1862,7 @@ def test_cli_reports_a_check_that_raises_and_goes_on(tmp_path, monkeypatch, caps good = _write_document(tmp_path, "good.json", _document([_CUSTOMERS], [])) bad = _write_document(tmp_path, "bad.json", _document([_ORDERS], [])) - def explode(data, schema, base=None): + def explode(data, schema, base=None, vendors=None): if "orders" in json.dumps(data): raise KeyError("dialect") return [] diff --git a/validation/tests/test_vendor_validators.py b/validation/tests/test_vendor_validators.py new file mode 100644 index 00000000..efdef7ea --- /dev/null +++ b/validation/tests/test_vendor_validators.py @@ -0,0 +1,456 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +import json +import sys +import types +from importlib.metadata import EntryPoint +from importlib.util import module_from_spec, spec_from_file_location +from pathlib import Path + +import pytest + +yaml = pytest.importorskip("yaml") +pytest.importorskip("jsonschema") + +_VALIDATE_PATH = Path(__file__).parents[1] / "validate.py" +_SPEC = spec_from_file_location("ossie_validate_vendor", _VALIDATE_PATH) +assert _SPEC is not None and _SPEC.loader is not None +_VALIDATE = module_from_spec(_SPEC) +_SPEC.loader.exec_module(_VALIDATE) + +_GROUP = _VALIDATE.VENDOR_VALIDATOR_GROUP +Site = _VALIDATE.ExtensionSite + + +def _ext(vendor: str, data: object) -> dict: + return {"vendor_name": vendor, "data": data} + + +def _model() -> dict: + """A valid model with an ACME extension at each place the schema allows one.""" + return { + "version": "0.3.0.dev0", + "name": "sales", + "nonportable_extensions": [_ext("ACME", {"at": "model"}), _ext("OTHER", {"at": "other"})], + "datasets": [ + { + "name": "orders", + "source": "db.orders", + "nonportable_extensions": [_ext("ACME", {"at": "dataset"})], + "fields": [ + {"name": "customer_id", "expression": {"sql": "customer_id"}}, + { + "name": "amount", + "expression": {"sql": "amount"}, + "nonportable_extensions": [_ext("ACME", {"at": "field"})], + }, + ], + "metrics": [ + { + "name": "order_total", + "expression": {"sql": "SUM(amount)"}, + "nonportable_extensions": [_ext("ACME", {"at": "dataset metric"})], + } + ], + }, + { + "name": "customers", + "source": "db.customers", + "fields": [{"name": "id", "expression": {"sql": "id"}}], + }, + ], + "relationships": [ + { + "name": "orders_to_customers", + "from": "orders", + "to": "customers", + "from_columns": ["customer_id"], + "to_columns": ["id"], + "nonportable_extensions": [_ext("ACME", {"at": "relationship"})], + } + ], + "metrics": [ + { + "name": "total", + "expression": {"sql": "SUM(orders.amount)"}, + "nonportable_extensions": [_ext("ACME", {"at": "metric"})], + } + ], + } + + +# (site handed to the validator, label the script prints, "at" tag of the payload) per site in _model() +_EXPECTED = [ + (Site("model", "sales"), "Model 'sales'", "model"), + (Site("dataset", "orders"), "Dataset 'orders' in model 'sales'", "dataset"), + (Site("field", "amount", "orders"), "Field 'orders.amount' in model 'sales'", "field"), + (Site("metric", "order_total", "orders"), "Metric 'orders.order_total' in model 'sales'", "dataset metric"), + (Site("metric", "total"), "Metric 'total' in model 'sales'", "metric"), + ( + Site("relationship", "orders_to_customers"), + "Relationship 'orders_to_customers' in model 'sales'", + "relationship", + ), +] + + +@pytest.fixture(autouse=True) +def _no_sql_check(monkeypatch: pytest.MonkeyPatch) -> None: + # Nothing here is about SQL; without sqlglot the SQL check would add its + # warning to every result and the exact assertions below would fail. + monkeypatch.setattr(_VALIDATE, "validate_sql", lambda data: []) + + +@pytest.fixture +def core_schema() -> dict: + schema_path = Path(__file__).parents[2] / "core-spec" / "ossie-schema.json" + return json.loads(schema_path.read_text()) + + +def _register(monkeypatch: pytest.MonkeyPatch, **validators: object) -> None: + """Make one entry point per vendor visible under the vendor validator group.""" + points = [] + for name, attr in validators.items(): + module_name = f"{name.lower()}_validator" + module = types.ModuleType(module_name) + module.check = attr + monkeypatch.setitem(sys.modules, module_name, module) + points.append(EntryPoint(name=name, value=f"{module_name}:check", group=_GROUP)) + monkeypatch.setattr(_VALIDATE, "entry_points", lambda group: points if group == _GROUP else []) + + +def _write(tmp_path: Path, model: dict) -> Path: + path = tmp_path / "model.yaml" + path.write_text(yaml.safe_dump(model), encoding="utf-8") + return path + + +def _run_main(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], *argv: str) -> tuple[int, str]: + monkeypatch.setattr(sys, "argv", ["validate.py", *argv]) + with pytest.raises(SystemExit) as raised: + _VALIDATE.main() + return raised.value.code, capsys.readouterr().out + + +def test_payloads_stay_opaque_without_a_vendor(core_schema: dict) -> None: + assert _VALIDATE.validate_document(_model(), core_schema) == [] + + +def test_vendor_checks_wait_for_the_other_checks(core_schema: dict) -> None: + calls: list[object] = [] + model = _model() + model["datasets"][1]["name"] = "orders" + + errors = _VALIDATE.validate_document(model, core_schema, vendors={"ACME": lambda p, s: calls.append(s) or []}) + + assert any(e.startswith("[Unique]") for e in errors) + assert not [e for e in errors if e.startswith("[Vendor")] + assert calls == [] + + +def test_a_warning_from_the_other_checks_does_not_withhold_the_document( + core_schema: dict, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(_VALIDATE, "validate_sql", lambda data: [_VALIDATE.ValidationWarning("[SQL] Warning: probe")]) + calls: list[object] = [] + + errors = _VALIDATE.validate_document(_model(), core_schema, vendors={"ACME": lambda p, s: calls.append(s) or []}) + + assert errors == ["[SQL] Warning: probe"] + assert calls == [site for site, _, _ in _EXPECTED] + + +def test_every_site_is_handed_to_the_validator(core_schema: dict) -> None: + seen: list[tuple[object, object]] = [] + + def check(payload: object, site: object) -> list[str]: + seen.append((payload, site)) + return [f"saw {payload['at']}"] + + errors = _VALIDATE.validate_document(_model(), core_schema, vendors={"ACME": check}) + + assert errors == [f"[Vendor ACME] {label}: saw {tag}" for _, label, tag in _EXPECTED] + assert seen == [({"at": tag}, site) for site, _, tag in _EXPECTED] + + +def test_unnamed_vendors_are_not_handed_over(core_schema: dict) -> None: + seen: list[object] = [] + + errors = _VALIDATE.validate_document(_model(), core_schema, vendors={"ACME": lambda p, s: seen.append(p) or []}) + + assert errors == [] + assert {"at": "other"} not in seen + assert {"at": "model"} in seen + + +def test_a_payload_json_cannot_represent_is_not_handed_over(core_schema: dict) -> None: + calls: list[object] = [] + model = _model() + model["datasets"][0]["nonportable_extensions"] = [_ext("ACME", {"ratio": float("nan")})] + + errors = _VALIDATE.validate_document(model, core_schema, vendors={"ACME": lambda p, s: calls.append(s) or []}) + + assert len(errors) == 1 + assert errors[0].startswith("[Schema] datasets -> 0 -> nonportable_extensions -> 0 -> data -> ratio") + assert calls == [] + + +def test_data_that_is_not_an_object_is_reported_on_a_direct_call() -> None: + calls: list[object] = [] + model = _model() + model["nonportable_extensions"] = [_ext("ACME", '{"at": "model"}')] + + errors = _VALIDATE.validate_vendor_extensions(model, {"ACME": lambda p, s: calls.append(s) or []}) + + assert errors == ["[Vendor ACME] Model 'sales': data is not an object"] + assert Site("model", "sales") not in calls + assert Site("dataset", "orders") in calls + + +def test_a_payload_shared_through_an_alias_is_copied_for_each_site(core_schema: dict) -> None: + shared = {"kind": "x", "opts": {"a": 1}} + model = _model() + model["nonportable_extensions"] = [_ext("ACME", shared)] + model["datasets"][0]["nonportable_extensions"] = [_ext("ACME", shared)] + + seen: list[dict] = [] + + def check(payload: dict, site: object) -> list[str]: + if "opts" in payload: + seen.append(dict(payload["opts"])) + payload["opts"].clear() + return [] + + errors = _VALIDATE.validate_document(model, core_schema, vendors={"ACME": check}) + + assert errors == [] + assert seen == [{"a": 1}, {"a": 1}] + assert shared == {"kind": "x", "opts": {"a": 1}} + + +def test_an_ontology_document_has_no_entries_to_hand_over() -> None: + ontology = {"name": "sales", "ontology": [], "nonportable_extensions": [_ext("ACME", {})]} + + assert list(_VALIDATE.iter_nonportable_extensions(ontology)) == [] + + +def _mapping() -> dict: + return { + "version": "0.3.0.dev0", + "name": "sales_mapping", + "ontology_ref": {"name": "sales", "iri": "./sales.ontology.yaml"}, + "semantic_model_ref": {"name": "sales", "iri": "./sales.semantic_model.yaml"}, + "concept_mappings": [{"concept": "Order", "object_mappings": [{"expression": "orders.order_id"}]}], + "nonportable_extensions": [_ext("ACME", {"at": "mapping"}), _ext("OTHER", {"at": "other"})], + } + + +@pytest.fixture +def mapping_schema() -> dict: + schema_path = Path(__file__).parents[2] / "ontology" / "mapping.json" + return json.loads(schema_path.read_text()) + + +def test_a_mapping_error_withholds_the_mapping_document(mapping_schema: dict, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(_VALIDATE, "validate_mapping", lambda data, base: ["[Reference] probe"]) + calls: list[object] = [] + + errors = _VALIDATE.validate_document(_mapping(), mapping_schema, vendors={"ACME": lambda p, s: calls.append(s)}) + + assert errors == ["[Reference] probe"] + assert calls == [] + + +def test_a_mapping_document_hands_over_its_entries(mapping_schema: dict, monkeypatch: pytest.MonkeyPatch) -> None: + # The cross-checks against the two referenced documents are not the subject here. + monkeypatch.setattr(_VALIDATE, "validate_mapping", lambda data, base: []) + mapping = _mapping() + seen: list[tuple[object, object]] = [] + + def check(payload: object, site: object) -> list[str]: + seen.append((payload, site)) + return ["rejected"] + + errors = _VALIDATE.validate_document(mapping, mapping_schema, vendors={"ACME": check}) + + assert errors == ["[Vendor ACME] Mapping 'sales_mapping': rejected"] + assert seen == [({"at": "mapping"}, Site("mapping", "sales_mapping"))] + + +def test_a_raising_validator_is_reported_against_its_vendor( + core_schema: dict, capsys: pytest.CaptureFixture[str] +) -> None: + def check(payload: object, site: object) -> list[str]: + if site.kind == "model": + raise KeyError("_v") + return [] + + errors = _VALIDATE.validate_document(_model(), core_schema, vendors={"ACME": check}) + + assert errors == ["[Vendor ACME] Model 'sales': validator raised KeyError: '_v'"] + assert "KeyError: '_v'" in capsys.readouterr().err + + +def test_a_validator_that_exits_is_reported_like_one_that_raises( + core_schema: dict, capsys: pytest.CaptureFixture[str] +) -> None: + def check(payload: object, site: object) -> list[str]: + if site.kind == "model": + sys.exit(0) + if site.kind == "dataset": + sys.exit() + return [] + + errors = _VALIDATE.validate_document(_model(), core_schema, vendors={"ACME": check}) + + assert errors == [ + "[Vendor ACME] Model 'sales': validator raised SystemExit: 0", + "[Vendor ACME] Dataset 'orders' in model 'sales': validator raised SystemExit", + ] + assert "SystemExit: 0" in capsys.readouterr().err + + +def test_a_single_string_is_one_message_and_none_is_none(core_schema: dict) -> None: + def check(payload: object, site: object) -> object: + return "one finding" if site.kind == "model" else None + + errors = _VALIDATE.validate_document(_model(), core_schema, vendors={"ACME": check}) + + assert errors == ["[Vendor ACME] Model 'sales': one finding"] + + +def test_cli_runs_the_registered_validator( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _register(monkeypatch, ACME=lambda payload, site: [f"{payload['at']} rejected"]) + + code, output = _run_main(monkeypatch, capsys, "--vendor", "ACME", str(_write(tmp_path, _model()))) + + assert code == 1 + assert "Validation FAILED with 6 error(s)" in output + assert "[Vendor ACME] Field 'orders.amount' in model 'sales': field rejected" in output + + +def test_cli_runs_a_repeated_vendor_name_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _register(monkeypatch, ACME=lambda payload, site: ["acme says no"], OTHER=lambda payload, site: ["never"]) + model = _model() + model["nonportable_extensions"] = [_ext("ACME", {}), _ext("OTHER", {})] + + code, output = _run_main( + monkeypatch, capsys, "--vendor", "ACME", "--vendor", "OTHER", "--vendor", "ACME", str(_write(tmp_path, model)) + ) + + assert code == 1 + assert output.count("[Vendor ACME] Model 'sales': acme says no") == 1 + assert output.count("[Vendor OTHER] Model 'sales': never") == 1 + + +def test_cli_passes_without_the_flag_even_when_a_validator_would_reject( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _register(monkeypatch, ACME=lambda payload, site: ["rejected"]) + + code, output = _run_main(monkeypatch, capsys, str(_write(tmp_path, _model()))) + + assert code == 0 + assert "Validation PASSED" in output + + +def test_missing_validator_is_an_error_before_any_file_runs( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setattr(_VALIDATE, "entry_points", lambda group: []) + + code, output = _run_main( + monkeypatch, capsys, "--vendor", "THOUGHTSPOT", "--vendor", "THOUGHTSPOT", str(_write(tmp_path, _model())) + ) + + assert code == 1 + assert output.count("Error: No validator is installed for vendor 'THOUGHTSPOT'") == 1 + assert "uv run --with validation/validate.py --vendor THOUGHTSPOT " in output + assert "Validation" not in output + + +def test_two_registrations_for_one_vendor_are_an_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + points = [ + EntryPoint(name="ACME", value="acme_one:check", group=_GROUP), + EntryPoint(name="ACME", value="acme_two:check", group=_GROUP), + ] + monkeypatch.setattr(_VALIDATE, "entry_points", lambda group: points) + + code, output = _run_main(monkeypatch, capsys, "--vendor", "ACME", str(_write(tmp_path, _model()))) + + assert code == 1 + assert "Error: More than one validator is installed for vendor 'ACME': acme_one:check, acme_two:check" in output + + +def test_entry_point_that_does_not_import_is_an_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + entry_point = EntryPoint(name="ACME", value="acme_validator_missing:check", group=_GROUP) + monkeypatch.setattr(_VALIDATE, "entry_points", lambda group: [entry_point]) + + code, output = _run_main(monkeypatch, capsys, "--vendor", "ACME", str(_write(tmp_path, _model()))) + + assert code == 1 + assert ( + "Error: Could not load the validator for vendor 'ACME' from acme_validator_missing:check: " + "ModuleNotFoundError:" in output + ) + + +def test_entry_point_that_exits_on_import_is_an_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + (tmp_path / "acme_exits_on_import.py").write_text("import sys\nsys.exit(2)\n", encoding="utf-8") + monkeypatch.syspath_prepend(tmp_path) + entry_point = EntryPoint(name="ACME", value="acme_exits_on_import:check", group=_GROUP) + monkeypatch.setattr(_VALIDATE, "entry_points", lambda group: [entry_point]) + + code, output = _run_main(monkeypatch, capsys, "--vendor", "ACME", str(_write(tmp_path, _model()))) + + assert code == 1 + assert ( + "Error: Could not load the validator for vendor 'ACME' from acme_exits_on_import:check: " + "SystemExit: 2" in output + ) + assert "Validation" not in output + + +def test_entry_point_that_is_not_callable_is_an_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _register(monkeypatch, ACME="not a function") + + code, output = _run_main(monkeypatch, capsys, "--vendor", "ACME", str(_write(tmp_path, _model()))) + + assert code == 1 + assert "Error: The validator for vendor 'ACME' (acme_validator:check) is not callable" in output + + +@pytest.mark.parametrize("argv", [["model.yaml", "--vendor"], ["--vendor", "--schema", "x.json"], ["--vendor", ""]]) +def test_vendor_flag_needs_a_name( + argv: list[str], monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + code, output = _run_main(monkeypatch, capsys, *argv) + + assert code == 1 + assert output.strip() == _VALIDATE.USAGE diff --git a/validation/validate.py b/validation/validate.py index 330e7155..6b7436d6 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -54,19 +54,32 @@ expression_language.md compares them. A referenced document is checked against its own schema first. +nonportable_extensions payloads are not interpreted unless a vendor is named. +With --vendor NAME the entries of a semantic model or a mapping document carrying +that vendor_name go to the vendor's own validator: the script hands a copy of +each data object to the callable the vendor's package registers under the entry +point group ossie.vendor_validators with the vendor token as its name. Only the +entries of the file being validated are handed over, not those of a document it +references. Entries of other vendors are not handed to anyone, and naming a +vendor whose validator is not installed is an error. + Usage: - python validation/validate.py [--schema ] [--] [ ...] + python validation/validate.py [--schema ] [--vendor ]... [--] [ ...] python validation/validate.py --schema ontology/ontology.json python validation/validate.py examples/tpcds_semantic_model.yaml + uv run --with validation/validate.py --vendor THOUGHTSPOT Every file is validated and reported, including one whose checks fail unexpectedly; the exit status is non-zero if any of them failed. Put -- before a file name that starts with a dash. The schema defaults to core-spec/ossie-schema.json in this repository's layout. When the script is vendored elsewhere, install the Python SDK (pip install /path/to/ossie/python) for its shared YAML loader and point -OSSIE_SCHEMA or --schema at a copy of the schema. +OSSIE_SCHEMA or --schema at a copy of the schema. A vendor validator has to be +installed in the environment the script runs in; for a uv run that is +uv run --with . """ +import copy import difflib import importlib.util import itertools @@ -77,11 +90,12 @@ import sys import traceback from collections import Counter -from collections.abc import Iterator +from collections.abc import Callable, Iterable, Iterator, Mapping from dataclasses import dataclass from datetime import date, datetime, time from decimal import Decimal, InvalidOperation from functools import lru_cache +from importlib.metadata import EntryPoint, entry_points from pathlib import Path from typing import Literal, NamedTuple from urllib.parse import unquote, urlsplit @@ -2108,7 +2122,175 @@ def check_link_mapping(node: object, concept: str, path: str, level: int) -> Non return errors -USAGE = "Usage: python validation/validate.py [--schema ] [--] [ ...]" +VENDOR_VALIDATOR_GROUP = "ossie.vendor_validators" + + +class ExtensionSite(NamedTuple): + """Where a nonportable_extensions entry sits in a semantic model or a mapping document.""" + + kind: Literal["model", "dataset", "field", "metric", "relationship", "mapping"] + name: str + dataset: str | None = None # the owning dataset of a field or a dataset-scoped metric + + +# A vendor validator receives a copy of the data object of one nonportable_extensions +# entry and the site it sits at, and returns the messages to report there. Every +# message is an error. +VendorValidator = Callable[[dict[str, object], ExtensionSite], Iterable[str] | None] + + +def load_vendor_validators(names: list[str]) -> dict[str, VendorValidator] | None: + """Resolve each vendor token to its registered validator, or report and return None. + + A validator is registered under the entry point group ossie.vendor_validators + with the vendor token as its name. The names are matched exactly, like the + tokens in extensions/vendors.md. + """ + if not names: + return {} + names = list(dict.fromkeys(names)) + registered: dict[str, list[EntryPoint]] = {} + for entry_point in entry_points(group=VENDOR_VALIDATOR_GROUP): + registered.setdefault(entry_point.name, []).append(entry_point) + validators: dict[str, VendorValidator] = {} + failed = False + for name in names: + candidates = registered.get(name, []) + if not candidates: + print(f"Error: No validator is installed for vendor '{name}' (entry point group {VENDOR_VALIDATOR_GROUP}).") + print( + "Install the vendor's package in the environment this script runs in, for a uv run: " + f"uv run --with validation/validate.py --vendor {name} " + ) + failed = True + continue + if len(candidates) > 1: + where = ", ".join(sorted(ep.value for ep in candidates)) + print(f"Error: More than one validator is installed for vendor '{name}': {where}") + failed = True + continue + entry_point = candidates[0] + try: + validator = entry_point.load() + except (Exception, SystemExit) as e: + # The package is installed but its entry point does not import, or exits on + # import as a CLI module parsing sys.argv does. Name both so the vendor can + # fix the registration, and keep the traceback on stderr. + print( + f"Error: Could not load the validator for vendor '{name}' from " + f"{entry_point.value}: {type(e).__name__}: {e}" + ) + traceback.print_exc() + failed = True + continue + if not callable(validator): + print(f"Error: The validator for vendor '{name}' ({entry_point.value}) is not callable") + failed = True + continue + validators[name] = validator + return None if failed else validators + + +def iter_nonportable_extensions(document: dict) -> Iterator[tuple[ExtensionSite, dict]]: + """Yield (site, entry) for every nonportable_extensions entry in a document. + + The schema places nonportable_extensions on a semantic model, its datasets, + their fields and dataset-scoped metrics, the model-scoped metrics and the + relationships. A mapping document carries them at its top level only, and an + ontology document has none. + """ + + def entries(owner: dict, site: ExtensionSite) -> Iterator[tuple[ExtensionSite, dict]]: + for entry in as_list(owner.get("nonportable_extensions")): + if isinstance(entry, dict): + yield site, entry + + def name_of(node: dict, index: int) -> str: + name = node.get("name") + return name if isinstance(name, str) else f"#{index}" + + if "concept_mappings" in document: + yield from entries(document, ExtensionSite("mapping", document_name_of(document))) + return + if "datasets" not in document: + return + model = document + yield from entries(model, ExtensionSite("model", document_name_of(model))) + for i, dataset in enumerate(as_list(model.get("datasets"))): + if not isinstance(dataset, dict): + continue + dataset_name = name_of(dataset, i) + yield from entries(dataset, ExtensionSite("dataset", dataset_name)) + for j, field in enumerate(as_list(dataset.get("fields"))): + if isinstance(field, dict): + yield from entries(field, ExtensionSite("field", name_of(field, j), dataset_name)) + for j, metric in enumerate(as_list(dataset.get("metrics"))): + if isinstance(metric, dict): + yield from entries(metric, ExtensionSite("metric", name_of(metric, j), dataset_name)) + for i, metric in enumerate(as_list(model.get("metrics"))): + if isinstance(metric, dict): + yield from entries(metric, ExtensionSite("metric", name_of(metric, i))) + for i, relationship in enumerate(as_list(model.get("relationships"))): + if isinstance(relationship, dict): + yield from entries(relationship, ExtensionSite("relationship", name_of(relationship, i))) + + +def document_name_of(document: dict) -> str: + name = document.get("name") + return name if isinstance(name, str) else "" + + +def site_label(site: ExtensionSite, document_name: str) -> str: + """Name the site the way the model checks do: Field 'orders.amount' in model 'sales'. + + A model or a mapping document is named by itself: Mapping 'sales_mapping'. + """ + if site.kind in ("model", "mapping"): + return f"{site.kind.capitalize()} '{site.name}'" + name = f"{site.dataset}.{site.name}" if site.dataset else site.name + return f"{site.kind.capitalize()} '{name}' in model '{document_name}'" + + +def validate_vendor_extensions(document: dict, validators: Mapping[str, VendorValidator]) -> list[str]: + """Hand each named vendor's nonportable_extensions payloads to that vendor's validator. + + A validator receives its own copy of the data object, so what it does to one + payload cannot reach another entry that shares it through a YAML alias. Entries + of vendors that were not named are not handed over. A validator that raises, or + exits, is reported against its vendor instead of ending the file's report, + with the traceback on stderr like a built-in check that raises. + """ + errors: list[str] = [] + document_name = document_name_of(document) + for site, entry in iter_nonportable_extensions(document): + vendor = entry.get("vendor_name") + validator = validators.get(vendor) if isinstance(vendor, str) else None + if validator is None: + continue + prefix = f"[Vendor {vendor}] {site_label(site, document_name)}" + # data that is not an object fails the schema first; a direct call on an unvetted + # document still gets a report, and the validator still gets an object. + payload = entry.get("data") + if not isinstance(payload, dict): + errors.append(f"{prefix}: data is not an object") + continue + # A single string is one message and None is none, so a validator that returns + # its one finding or falls off the end is read as it was written. + try: + result = validator(copy.deepcopy(payload), site) + messages = [result] if isinstance(result, str) else list(result or []) + except (Exception, SystemExit) as e: + # A validator built on a converter's CLI code can call sys.exit(); that must + # not end the run or pass the file. + detail = f": {e}" if str(e) else "" + errors.append(f"{prefix}: validator raised {type(e).__name__}{detail}") + traceback.print_exc() + continue + errors.extend(f"{prefix}: {message}" for message in messages) + return errors + + +USAGE = "Usage: python validation/validate.py [--schema ] [--vendor ]... [--] [ ...]" def read_text_or_report(path: Path, description: str) -> str | None: @@ -2160,12 +2342,19 @@ def load_schema_or_report(schema_path: Path) -> dict | None: return schema -def validate_document(data, schema: dict, base: Path | None = None) -> list[str]: +def validate_document( + data, + schema: dict, + base: Path | None = None, + vendors: Mapping[str, VendorValidator] | None = None, +) -> list[str]: """Run every check on a parsed document and return the diagnostics. base is the directory the document was read from. A mapping document follows its relative references from there, and without it those checks - are skipped with a warning. + are skipped with a warning. vendors maps a vendor token to its validator; + the nonportable_extensions of those vendors are handed to it, once the other + checks have passed, and the rest are left alone. """ errors = [] errors.extend(validate_schema(data, schema)) @@ -2193,11 +2382,15 @@ def clean() -> bool: errors.extend(validate_ontology(data)) if clean() and isinstance(data, dict) and "concept_mappings" in data: errors.extend(validate_mapping(data, base)) + # A validator is promised a document the checks above accepted; a warning + # from them does not withhold it. + if vendors and clean() and isinstance(data, dict): + errors.extend(validate_vendor_extensions(data, vendors)) return errors -def validate_file(yaml_path: Path, schema: dict) -> bool: +def validate_file(yaml_path: Path, schema: dict, vendors: Mapping[str, VendorValidator] | None = None) -> bool: """Validate one document, print its report and return True if it passed.""" if not yaml_path.exists(): print(f"Error: File not found: {yaml_path}") @@ -2217,7 +2410,7 @@ def validate_file(yaml_path: Path, schema: dict) -> bool: return False try: - errors = validate_document(data, schema, yaml_path.parent) + errors = validate_document(data, schema, yaml_path.parent, vendors) except Exception as e: # A check that raises on this document is a bug in the validator, not in the # model. Report it like any other failure so the remaining files still run, @@ -2261,6 +2454,7 @@ def main(): paths: list[Path] = [] schema_arg: str | None = None + vendor_names: list[str] = [] args = sys.argv[1:] while args: arg = args.pop(0) @@ -2269,6 +2463,11 @@ def main(): print(USAGE) sys.exit(1) schema_arg = args.pop(0) + elif arg == "--vendor": + if not args or not args[0] or args[0].startswith("-"): + print(USAGE) + sys.exit(1) + vendor_names.append(args.pop(0)) elif arg == "--": paths.extend(Path(rest) for rest in args) break @@ -2291,12 +2490,15 @@ def main(): schema = load_schema_or_report(schema_path) if schema is None: sys.exit(1) + vendors = load_vendor_validators(vendor_names) + if vendors is None: + sys.exit(1) failed = 0 for yaml_path in paths: if len(paths) > 1: print(f"== {yaml_path}") - if not validate_file(yaml_path, schema): + if not validate_file(yaml_path, schema, vendors): failed += 1 if len(paths) > 1: