From a9706c4855ff645067ded8c506a032345e2b32f1 Mon Sep 17 00:00:00 2001 From: Kyoung Min Kim Date: Wed, 4 Nov 2026 16:26:14 +0900 Subject: [PATCH 1/4] feat(validation): hand a named vendor's custom_extensions to its own validator custom_extensions payloads stay opaque to validate.py. A converter that wants its own payload checked has had no place to plug in, so each one re-implements the read in its own CLI with its own strictness. Add --vendor NAME. For every custom_extensions entry carrying that vendor_name, at any of the six places the schema allows one, the script decodes data as JSON, reports a payload that is not JSON, and hands the decoded value with its location to the callable the vendor's package registers under the entry point group ossie.vendor_validators, named by the vendor token. Messages come back as [Vendor NAME] : .... Nothing runs without the flag, entries of other vendors are not read, naming a vendor whose validator is not installed is an error before any file runs, and a validator that raises is reported against its vendor instead of ending the file's report. Generated-by: Claude Code --- validation/tests/test_validate.py | 2 +- validation/tests/test_vendor_validators.py | 339 +++++++++++++++++++++ validation/validate.py | 200 +++++++++++- 3 files changed, 531 insertions(+), 10 deletions(-) create mode 100644 validation/tests/test_vendor_validators.py 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..cd15f158 --- /dev/null +++ b/validation/tests/test_vendor_validators.py @@ -0,0 +1,339 @@ +# 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: str) -> 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.2.0.dev0", + "name": "sales", + "custom_extensions": [_ext("ACME", '{"at": "model"}'), _ext("OTHER", "not json")], + "datasets": [ + { + "name": "orders", + "source": "db.orders", + "custom_extensions": [_ext("ACME", '{"at": "dataset"}')], + "fields": [ + {"name": "customer_id", "expression": {"sql": "customer_id"}}, + { + "name": "amount", + "expression": {"sql": "amount"}, + "custom_extensions": [_ext("ACME", '{"at": "field"}')], + }, + ], + "metrics": [ + { + "name": "order_total", + "expression": {"sql": "SUM(amount)"}, + "custom_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"], + "custom_extensions": [_ext("ACME", '{"at": "relationship"}')], + } + ], + "metrics": [ + { + "name": "total", + "expression": {"sql": "SUM(orders.amount)"}, + "custom_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 +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_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_decoded(core_schema: dict, monkeypatch: pytest.MonkeyPatch) -> None: + decoded: list[str] = [] + + def counting_loads(text: str, *args: object, **kwargs: object) -> object: + decoded.append(text) + return json.loads(text, *args, **kwargs) + + # Only the script's own json.loads calls are counted; jsonschema keeps the real module. + stub = types.ModuleType("json_stub") + stub.__dict__.update(json.__dict__) + stub.loads = counting_loads + monkeypatch.setattr(_VALIDATE, "json", stub) + + errors = _VALIDATE.validate_document(_model(), core_schema, vendors={"ACME": lambda payload, site: []}) + + assert errors == [] + assert "not json" not in decoded + assert '{"at": "model"}' in decoded + + +def test_bad_json_is_reported_once_and_not_handed_over(core_schema: dict) -> None: + calls: list[object] = [] + + def check(payload: object, site: object) -> list[str]: + calls.append(site) + return [] + + model = _model() + model["datasets"][0]["custom_extensions"] = [_ext("ACME", "{not json")] + + errors = _VALIDATE.validate_document(model, core_schema, vendors={"ACME": check}) + + assert len(errors) == 1 + assert errors[0].startswith("[Vendor ACME] Dataset 'orders' in model 'sales': data is not valid JSON: Expecting") + assert Site("dataset", "orders") not in calls + assert Site("model", "sales") in calls + + +def test_a_payload_that_is_not_an_object_still_reaches_the_validator(core_schema: dict) -> None: + seen: list[object] = [] + model = _model() + model["custom_extensions"] = [_ext("ACME", "42"), _ext("ACME", "null")] + for dataset in model["datasets"]: + dataset.pop("custom_extensions", None) + for node in dataset["fields"] + dataset.get("metrics", []): + node.pop("custom_extensions", None) + for node in model["relationships"] + model["metrics"]: + node.pop("custom_extensions", None) + + errors = _VALIDATE.validate_document(model, core_schema, vendors={"ACME": lambda p, s: seen.append(p) or []}) + + assert errors == [] + assert seen == [42, None] + + +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_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["custom_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_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..6abdd890 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -54,17 +54,28 @@ expression_language.md compares them. A referenced document is checked against its own schema first. +custom_extensions payloads are opaque unless a vendor is named. With --vendor NAME +the entries of a semantic model carrying that vendor_name go to the vendor's own +validator: the script decodes each data string as JSON, reports the ones that are +not JSON, and hands the decoded value to the callable the vendor's package +registers under the entry point group ossie.vendor_validators with the vendor +token as its name. Entries of other vendors are not read, 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 difflib @@ -77,11 +88,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 +2120,160 @@ 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 custom_extensions entry sits in a semantic model.""" + + kind: Literal["model", "dataset", "field", "metric", "relationship"] + name: str + dataset: str | None = None # the owning dataset of a field or a dataset-scoped metric + + +# A vendor validator receives one decoded custom_extensions payload and the site it +# sits at, and returns the messages to report there. Every message is an error. +VendorValidator = Callable[[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 as e: + # The package is installed but its entry point does not import. 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_custom_extensions(model: dict) -> Iterator[tuple[ExtensionSite, dict]]: + """Yield (site, entry) for every custom_extensions entry in a semantic model. + + The schema places custom_extensions on the model, its datasets, their fields + and dataset-scoped metrics, the model-scoped metrics and the relationships. + """ + + def entries(owner: dict, site: ExtensionSite) -> Iterator[tuple[ExtensionSite, dict]]: + for entry in as_list(owner.get("custom_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}" + + yield from entries(model, ExtensionSite("model", model_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 model_name_of(model: dict) -> str: + name = model.get("name") + return name if isinstance(name, str) else "" + + +def site_label(site: ExtensionSite, model_name: str) -> str: + """The site as the other checks write it: Field 'orders.amount' in model 'sales'.""" + if site.kind == "model": + return f"Model '{site.name}'" + name = f"{site.dataset}.{site.name}" if site.dataset else site.name + return f"{site.kind.capitalize()} '{name}' in model '{model_name}'" + + +def validate_vendor_extensions(model: dict, validators: Mapping[str, VendorValidator]) -> list[str]: + """Hand each named vendor's custom_extensions payloads to that vendor's validator. + + The data string is decoded here, once, so a validator receives the decoded + value and a payload that is not JSON is reported in one place. Entries of + vendors that were not named are not read. A validator that raises 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] = [] + model_name = model_name_of(model) + for site, entry in iter_custom_extensions(model): + 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, model_name)}" + # data that is not a string fails the schema first; a direct call on an unvetted + # document still gets a report instead of a TypeError. + try: + payload = json.loads(entry.get("data")) + except (TypeError, ValueError) as e: + errors.append(f"{prefix}: data is not valid JSON: {str(e).splitlines()[0]}") + 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(payload, site) + messages = [result] if isinstance(result, str) else list(result or []) + except Exception as e: + errors.append(f"{prefix}: validator raised {type(e).__name__}: {e}") + 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 +2325,18 @@ 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 custom_extensions of those vendors are checked and the rest stay opaque. """ errors = [] errors.extend(validate_schema(data, schema)) @@ -2189,6 +2360,8 @@ def clean() -> bool: errors.extend(validate_metric_scoping(data)) errors.extend(validate_sql(data)) errors.extend(validate_metric_agreement(data)) + if vendors: + errors.extend(validate_vendor_extensions(data, vendors)) if clean() and isinstance(data, dict) and "ontology" in data: errors.extend(validate_ontology(data)) if clean() and isinstance(data, dict) and "concept_mappings" in data: @@ -2197,7 +2370,7 @@ def clean() -> bool: 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 +2390,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 +2434,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 +2443,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 +2470,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: From 83d395f3829fb11118e72f2d905801586732b127 Mon Sep 17 00:00:00 2001 From: Kyoung Min Kim Date: Wed, 4 Nov 2026 16:40:28 +0900 Subject: [PATCH 2/4] docs(extensions): describe how a vendor registers a payload validator The registry names the tokens; say what --vendor does with them and that the package has to be on the uv run path. Generated-by: Claude Code --- extensions/vendors.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/extensions/vendors.md b/extensions/vendors.md index 58a3971b..4404ca43 100644 --- a/extensions/vendors.md +++ b/extensions/vendors.md @@ -44,6 +44,29 @@ 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` leaves `data` opaque unless a vendor is named. With +`--vendor THOUGHTSPOT` it decodes the `data` of every `THOUGHTSPOT` entry in a +semantic model as JSON, reports the ones that are not JSON, and hands each +decoded payload 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 the decoded JSON value, and `site` has `kind` (one of `model`, +`dataset`, `field`, `metric`, `relationship`), `name`, 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 is reported the same way, with the traceback on stderr. Vendor +checks run on a document that passed the schema and the other checks, and +entries of other vendors are not read. 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 | From be80cab9f27baa284be4cf9aa9666b9e0bdb546a Mon Sep 17 00:00:00 2001 From: Kyoung Min Kim Date: Thu, 5 Nov 2026 08:59:52 +0900 Subject: [PATCH 3/4] fix(validation): hand a validator only a clean document, and catch sys.exit() Two gaps between extensions/vendors.md and the hook, the same hole in the loader, and one gap in the tests. validate_document ran the vendor checks whenever a vendor was named: clean() was true on entering the block, but nothing checked it again after the semantic checks, so a validator could be handed a model with duplicate dataset names or dangling references it was told it would never see. The vendor checks now wait for those checks the way the ontology and mapping checks do; a warning from them does not withhold the document. SystemExit is not an Exception, so a validator that calls sys.exit(), easy to do when it reuses a converter's CLI code, passed both the hook's handler and the catch-all in validate_file and ended the run at that file: with sys.exit() or sys.exit(0) the process exited 0 and an earlier failed file read as a pass, with any other code it exited with that code. Either way the remaining files were never checked. The same CLI module can exit while it is imported, and entry_point.load() had the same hole. Both handlers now catch SystemExit with the exceptions and report it against the vendor; a bare sys.exit() reads "validator raised SystemExit" with no empty detail after it. test_vendor_validators.py only skipped without yaml or jsonschema, but without sqlglot validate_sql adds its warning to every result and the exact assertions failed; CI passed because sqlglot is installed there. Nothing in the file exercises SQL, so an autouse fixture patches validate_sql out and the tests run everywhere. Four tests pin the above: an error from the other checks withholds the document and a warning does not, a validator that exits is reported like one that raises, and an entry point that exits on import is an error before any file runs. vendors.md says "raises, or exits" for the validator. --- extensions/vendors.md | 6 +- validation/tests/test_vendor_validators.py | 68 ++++++++++++++++++++++ validation/validate.py | 27 +++++---- 3 files changed, 88 insertions(+), 13 deletions(-) diff --git a/extensions/vendors.md b/extensions/vendors.md index 4404ca43..d747f473 100644 --- a/extensions/vendors.md +++ b/extensions/vendors.md @@ -58,9 +58,9 @@ 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 is reported the same way, with the traceback on stderr. Vendor -checks run on a document that passed the schema and the other checks, and -entries of other vendors are not read. The package has to be installed where +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, +and entries of other vendors are not read. The package has to be installed where the script runs; for a uv run that is: ```sh diff --git a/validation/tests/test_vendor_validators.py b/validation/tests/test_vendor_validators.py index cd15f158..3350d441 100644 --- a/validation/tests/test_vendor_validators.py +++ b/validation/tests/test_vendor_validators.py @@ -108,6 +108,13 @@ def _model() -> dict: ] +@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" @@ -143,6 +150,30 @@ 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]] = [] @@ -225,6 +256,25 @@ def check(payload: object, site: object) -> list[str]: 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 @@ -318,6 +368,24 @@ def test_entry_point_that_does_not_import_is_an_error( ) +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: diff --git a/validation/validate.py b/validation/validate.py index 6abdd890..d0baa95c 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -2169,9 +2169,10 @@ def load_vendor_validators(names: list[str]) -> dict[str, VendorValidator] | Non entry_point = candidates[0] try: validator = entry_point.load() - except Exception as e: - # The package is installed but its entry point does not import. Name both - # so the vendor can fix the registration, and keep the traceback on stderr. + 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}" @@ -2241,9 +2242,9 @@ def validate_vendor_extensions(model: dict, validators: Mapping[str, VendorValid The data string is decoded here, once, so a validator receives the decoded value and a payload that is not JSON is reported in one place. Entries of - vendors that were not named are not read. A validator that raises is reported - against its vendor instead of ending the file's report, with the traceback on - stderr like a built-in check that raises. + vendors that were not named are not read. 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] = [] model_name = model_name_of(model) @@ -2265,8 +2266,11 @@ def validate_vendor_extensions(model: dict, validators: Mapping[str, VendorValid try: result = validator(payload, site) messages = [result] if isinstance(result, str) else list(result or []) - except Exception as e: - errors.append(f"{prefix}: validator raised {type(e).__name__}: {e}") + 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) @@ -2336,7 +2340,8 @@ def validate_document( 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. vendors maps a vendor token to its validator; - the custom_extensions of those vendors are checked and the rest stay opaque. + the custom_extensions of those vendors are checked, once the other checks + have passed, and the rest stay opaque. """ errors = [] errors.extend(validate_schema(data, schema)) @@ -2360,7 +2365,9 @@ def clean() -> bool: errors.extend(validate_metric_scoping(data)) errors.extend(validate_sql(data)) errors.extend(validate_metric_agreement(data)) - if vendors: + # A validator is promised a document the checks above accepted; a warning + # from them does not withhold it. + if vendors and clean(): errors.extend(validate_vendor_extensions(data, vendors)) if clean() and isinstance(data, dict) and "ontology" in data: errors.extend(validate_ontology(data)) From 21ab77ef1721bd478dfbe679364692b2d911c787 Mon Sep 17 00:00:00 2001 From: Kyoung Min Kim Date: Wed, 11 Nov 2026 18:46:34 +0900 Subject: [PATCH 4/4] fix(validation): hand over the data object of nonportable_extensions The extension field is now nonportable_extensions and its data is an object, where the hook read custom_extensions and decoded a JSON string. On a merge with main the hook found no entries, and the vendor tests failed at the schema with the old version and the old field name. The hook reads nonportable_extensions and hands a validator a copy of the data object. The decode step and its "data is not valid JSON" report are gone: the schema requires an object, the JSON-value check on data rejects what JSON cannot represent, and a validator still only sees a document those checks accepted. A repeated key under data never gets that far, since the loader rejects it for the whole document. Decoding used to give every call a fresh value; the copy keeps that, so a validator that changes its payload cannot change what the next site sees when two entries share one object through a YAML alias. A mapping document carries nonportable_extensions at its top level, and --vendor on one used to pass without a word. Its entries now go to the validator too, at a site of kind "mapping", after the mapping cross-checks. Only the entries of the file being validated are handed over, not those of the documents a mapping references, and an ontology document has none. The tests move to 0.3.0.dev0 and object payloads. The decode tests give way to these: a value JSON cannot represent is reported by the schema check and withholds the document, data that is not an object is reported on a direct call, a payload shared through an alias is copied for each site, a mapping document's entries reach the validator, an error from the mapping cross-checks withholds them, and an ontology document yields no entries. Generated-by: Claude Code --- extensions/vendors.md | 34 ++--- validation/tests/test_vendor_validators.py | 139 ++++++++++++++------- validation/validate.py | 109 +++++++++------- 3 files changed, 173 insertions(+), 109 deletions(-) diff --git a/extensions/vendors.md b/extensions/vendors.md index d747f473..a33528bc 100644 --- a/extensions/vendors.md +++ b/extensions/vendors.md @@ -46,22 +46,24 @@ Quoted and unquoted values under `data` are shown in ## Validating a vendor's payload -`validation/validate.py` leaves `data` opaque unless a vendor is named. With -`--vendor THOUGHTSPOT` it decodes the `data` of every `THOUGHTSPOT` entry in a -semantic model as JSON, reports the ones that are not JSON, and hands each -decoded payload 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 the decoded JSON value, and `site` has `kind` (one of `model`, -`dataset`, `field`, `metric`, `relationship`), `name`, 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, -and entries of other vendors are not read. The package has to be installed where -the script runs; for a uv run that is: +`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 diff --git a/validation/tests/test_vendor_validators.py b/validation/tests/test_vendor_validators.py index 3350d441..efdef7ea 100644 --- a/validation/tests/test_vendor_validators.py +++ b/validation/tests/test_vendor_validators.py @@ -36,34 +36,34 @@ Site = _VALIDATE.ExtensionSite -def _ext(vendor: str, data: str) -> dict: +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.2.0.dev0", + "version": "0.3.0.dev0", "name": "sales", - "custom_extensions": [_ext("ACME", '{"at": "model"}'), _ext("OTHER", "not json")], + "nonportable_extensions": [_ext("ACME", {"at": "model"}), _ext("OTHER", {"at": "other"})], "datasets": [ { "name": "orders", "source": "db.orders", - "custom_extensions": [_ext("ACME", '{"at": "dataset"}')], + "nonportable_extensions": [_ext("ACME", {"at": "dataset"})], "fields": [ {"name": "customer_id", "expression": {"sql": "customer_id"}}, { "name": "amount", "expression": {"sql": "amount"}, - "custom_extensions": [_ext("ACME", '{"at": "field"}')], + "nonportable_extensions": [_ext("ACME", {"at": "field"})], }, ], "metrics": [ { "name": "order_total", "expression": {"sql": "SUM(amount)"}, - "custom_extensions": [_ext("ACME", '{"at": "dataset metric"}')], + "nonportable_extensions": [_ext("ACME", {"at": "dataset metric"})], } ], }, @@ -80,14 +80,14 @@ def _model() -> dict: "to": "customers", "from_columns": ["customer_id"], "to_columns": ["id"], - "custom_extensions": [_ext("ACME", '{"at": "relationship"}')], + "nonportable_extensions": [_ext("ACME", {"at": "relationship"})], } ], "metrics": [ { "name": "total", "expression": {"sql": "SUM(orders.amount)"}, - "custom_extensions": [_ext("ACME", '{"at": "metric"}')], + "nonportable_extensions": [_ext("ACME", {"at": "metric"})], } ], } @@ -187,59 +187,108 @@ def check(payload: object, site: object) -> list[str]: assert seen == [({"at": tag}, site) for site, _, tag in _EXPECTED] -def test_unnamed_vendors_are_not_decoded(core_schema: dict, monkeypatch: pytest.MonkeyPatch) -> None: - decoded: list[str] = [] - - def counting_loads(text: str, *args: object, **kwargs: object) -> object: - decoded.append(text) - return json.loads(text, *args, **kwargs) - - # Only the script's own json.loads calls are counted; jsonschema keeps the real module. - stub = types.ModuleType("json_stub") - stub.__dict__.update(json.__dict__) - stub.loads = counting_loads - monkeypatch.setattr(_VALIDATE, "json", stub) +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 payload, site: []}) + errors = _VALIDATE.validate_document(_model(), core_schema, vendors={"ACME": lambda p, s: seen.append(p) or []}) assert errors == [] - assert "not json" not in decoded - assert '{"at": "model"}' in decoded + assert {"at": "other"} not in seen + assert {"at": "model"} in seen -def test_bad_json_is_reported_once_and_not_handed_over(core_schema: dict) -> None: +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 check(payload: object, site: object) -> list[str]: - calls.append(site) - return [] +def test_data_that_is_not_an_object_is_reported_on_a_direct_call() -> None: + calls: list[object] = [] model = _model() - model["datasets"][0]["custom_extensions"] = [_ext("ACME", "{not json")] + model["nonportable_extensions"] = [_ext("ACME", '{"at": "model"}')] - errors = _VALIDATE.validate_document(model, core_schema, vendors={"ACME": check}) + errors = _VALIDATE.validate_vendor_extensions(model, {"ACME": lambda p, s: calls.append(s) or []}) - assert len(errors) == 1 - assert errors[0].startswith("[Vendor ACME] Dataset 'orders' in model 'sales': data is not valid JSON: Expecting") - assert Site("dataset", "orders") not in calls - assert Site("model", "sales") in calls + 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_that_is_not_an_object_still_reaches_the_validator(core_schema: dict) -> None: - seen: list[object] = [] +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["custom_extensions"] = [_ext("ACME", "42"), _ext("ACME", "null")] - for dataset in model["datasets"]: - dataset.pop("custom_extensions", None) - for node in dataset["fields"] + dataset.get("metrics", []): - node.pop("custom_extensions", None) - for node in model["relationships"] + model["metrics"]: - node.pop("custom_extensions", None) + model["nonportable_extensions"] = [_ext("ACME", shared)] + model["datasets"][0]["nonportable_extensions"] = [_ext("ACME", shared)] + + seen: list[dict] = [] - errors = _VALIDATE.validate_document(model, core_schema, vendors={"ACME": lambda p, s: seen.append(p) or []}) + 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 == [42, None] + 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( @@ -301,7 +350,7 @@ def test_cli_runs_a_repeated_vendor_name_once( ) -> None: _register(monkeypatch, ACME=lambda payload, site: ["acme says no"], OTHER=lambda payload, site: ["never"]) model = _model() - model["custom_extensions"] = [_ext("ACME", "{}"), _ext("OTHER", "{}")] + model["nonportable_extensions"] = [_ext("ACME", {}), _ext("OTHER", {})] code, output = _run_main( monkeypatch, capsys, "--vendor", "ACME", "--vendor", "OTHER", "--vendor", "ACME", str(_write(tmp_path, model)) diff --git a/validation/validate.py b/validation/validate.py index d0baa95c..6b7436d6 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -54,13 +54,14 @@ expression_language.md compares them. A referenced document is checked against its own schema first. -custom_extensions payloads are opaque unless a vendor is named. With --vendor NAME -the entries of a semantic model carrying that vendor_name go to the vendor's own -validator: the script decodes each data string as JSON, reports the ones that are -not JSON, and hands the decoded value to the callable the vendor's package -registers under the entry point group ossie.vendor_validators with the vendor -token as its name. Entries of other vendors are not read, and naming a vendor -whose validator is not installed is an error. +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 ] [--vendor ]... [--] [ ...] @@ -78,6 +79,7 @@ uv run --with . """ +import copy import difflib import importlib.util import itertools @@ -2124,16 +2126,17 @@ def check_link_mapping(node: object, concept: str, path: str, level: int) -> Non class ExtensionSite(NamedTuple): - """Where a custom_extensions entry sits in a semantic model.""" + """Where a nonportable_extensions entry sits in a semantic model or a mapping document.""" - kind: Literal["model", "dataset", "field", "metric", "relationship"] + 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 one decoded custom_extensions payload and the site it -# sits at, and returns the messages to report there. Every message is an error. -VendorValidator = Callable[[object, ExtensionSite], Iterable[str] | None] +# 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: @@ -2188,15 +2191,17 @@ def load_vendor_validators(names: list[str]) -> dict[str, VendorValidator] | Non return None if failed else validators -def iter_custom_extensions(model: dict) -> Iterator[tuple[ExtensionSite, dict]]: - """Yield (site, entry) for every custom_extensions entry in a semantic model. +def iter_nonportable_extensions(document: dict) -> Iterator[tuple[ExtensionSite, dict]]: + """Yield (site, entry) for every nonportable_extensions entry in a document. - The schema places custom_extensions on the model, its datasets, their fields - and dataset-scoped metrics, the model-scoped metrics and the relationships. + 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("custom_extensions")): + for entry in as_list(owner.get("nonportable_extensions")): if isinstance(entry, dict): yield site, entry @@ -2204,7 +2209,13 @@ def name_of(node: dict, index: int) -> str: name = node.get("name") return name if isinstance(name, str) else f"#{index}" - yield from entries(model, ExtensionSite("model", model_name_of(model))) + 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 @@ -2224,47 +2235,49 @@ def name_of(node: dict, index: int) -> str: yield from entries(relationship, ExtensionSite("relationship", name_of(relationship, i))) -def model_name_of(model: dict) -> str: - name = model.get("name") +def document_name_of(document: dict) -> str: + name = document.get("name") return name if isinstance(name, str) else "" -def site_label(site: ExtensionSite, model_name: str) -> str: - """The site as the other checks write it: Field 'orders.amount' in model 'sales'.""" - if site.kind == "model": - return f"Model '{site.name}'" +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 '{model_name}'" + return f"{site.kind.capitalize()} '{name}' in model '{document_name}'" -def validate_vendor_extensions(model: dict, validators: Mapping[str, VendorValidator]) -> list[str]: - """Hand each named vendor's custom_extensions payloads to that vendor's validator. +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. - The data string is decoded here, once, so a validator receives the decoded - value and a payload that is not JSON is reported in one place. Entries of - vendors that were not named are not read. 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. + 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] = [] - model_name = model_name_of(model) - for site, entry in iter_custom_extensions(model): + 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, model_name)}" - # data that is not a string fails the schema first; a direct call on an unvetted - # document still gets a report instead of a TypeError. - try: - payload = json.loads(entry.get("data")) - except (TypeError, ValueError) as e: - errors.append(f"{prefix}: data is not valid JSON: {str(e).splitlines()[0]}") + 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(payload, site) + 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 @@ -2340,8 +2353,8 @@ def validate_document( 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. vendors maps a vendor token to its validator; - the custom_extensions of those vendors are checked, once the other checks - have passed, and the rest stay opaque. + 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)) @@ -2365,14 +2378,14 @@ def clean() -> bool: errors.extend(validate_metric_scoping(data)) errors.extend(validate_sql(data)) errors.extend(validate_metric_agreement(data)) - # A validator is promised a document the checks above accepted; a warning - # from them does not withhold it. - if vendors and clean(): - errors.extend(validate_vendor_extensions(data, vendors)) if clean() and isinstance(data, dict) and "ontology" in data: 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