"""Open Data Contracts (ODCS v3.1.0) for the relations the public API serves (#270). The public API reads only what ``publish_public_serving`` puts in the ``public`` schema (dbt_project/macros/publish_public_serving.sql). Each served relation whose ``schema.yml`` enforces a dbt contract gets ``dbt_project/contracts/.odcs.yaml``, generated from that ``schema.yml``, so dbt stays the one place the structure is declared: * the model's description, and its grain (its "one row per ..." sentence); * each column's physical type as declared, and its ODCS logical type; * primary keys and foreign keys (dbt constraints and ``relationships`` tests). A foreign key points into its parent's contract with a fully qualified ODCS reference to the column's ``id`` (#276), so it is left out while the parent has no contract holding that column; * ``not_null``, ``unique`` and ``accepted_values`` tests as ODCS library quality rules, and range tests, filtered tests and CHECK constraints as text rules, each with the test's severity (a ``warn`` test never makes a column ``required`` or ``unique``); * columns that ``publish_public_serving`` redacts in ``public`` (``null::text as email``) marked as redacted, and columns its projection leaves out dropped; * whether its materialize mode slims the relation (fewer rows, or fewer columns too). python -m models.odcs --write # regenerate after changing a schema.yml or the served list python -m models.odcs --check # CI: fails on a stale, missing, extra or invalid contract Contracts describe structure only: no row data, hostnames or personal data. They are validated against the official ODCS v3.1.0 JSON Schema at its release tag (the copy Ontos bundles), vendored in dbt_project/contracts/_schema/. The same commands write and check the ODPS data products built from them (``models.odps``). """ from __future__ import annotations import argparse import json import re from functools import lru_cache from pathlib import Path from typing import Any, NamedTuple import yaml from loguru import logger from models import odps REPO_ROOT = Path(__file__).resolve().parents[3] DBT_DIR = REPO_ROOT / "dbt_project" SCHEMA_FILE = DBT_DIR / "contracts" / "_schema" / "odcs-json-schema-v3.1.0.json" API_VERSION = "v3.1.0" CONTRACT_VERSION = "1.0.0" SUFFIX = ".odcs.yaml" HEADER = ( "# Generated by `python -m models.odcs --write` from the dbt schema.yml files (issue #270).\n" "# Do not edit by hand: change the schema.yml, then regenerate.\n" ) RANGE_TESTS = ("accepted_range", "expect_column_values_to_be_between") def served_relations(macro_text: str) -> list[str]: """The relations publish_public_serving publishes into ``public``, in its order.""" found = re.search(r"set\s+served\s*=\s*\[(.*?)\]", macro_text, re.DOTALL) if not found: raise ValueError("publish_public_serving declares no `served` list") return re.findall(r"'([A-Za-z0-9_]+)'", found.group(1)) def _dict_block(macro_text: str, name: str) -> str | None: """The inside of ``{%- set = { ... } -%}`` in the macro, or None when it isn't set.""" found = re.search( rf"set\s+{name}\s*=\s*\{{(.*?)\}}\s*-?%\}}", macro_text, re.DOTALL ) return found.group(1) if found else None def projections(macro_text: str) -> dict[str, dict[str, list[str]]]: """Per relation, the columns its public projection selects and those it redacts to null.""" block = _dict_block(macro_text, "projections") if block is None: return {} result: dict[str, dict[str, list[str]]] = {} for name, literals in re.findall( r"'([A-Za-z0-9_]+)'\s*:\s*((?:'[^']*'\s*)+)", block ): sql = "".join(re.findall(r"'([^']*)'", literals)) select = re.search(r"select\s+(.*?)\s+from\s", sql, re.IGNORECASE | re.DOTALL) if not select: continue columns: list[str] = [] redacted: list[str] = [] for item in (part.strip() for part in select.group(1).split(",")): aliased = re.match(r"(.+?)\s+as\s+([A-Za-z0-9_]+)$", item, re.IGNORECASE) if aliased: expression, column = aliased.group(1).strip(), aliased.group(2) if re.fullmatch(r"null(::[\w ]+)?", expression, re.IGNORECASE): redacted.append(column) else: column = item.split(".")[-1] columns.append(column) result[name] = {"columns": columns, "redacted": redacted} return result def serving_bodies(macro_text: str) -> dict[str, str]: """Relations the macro's materialize mode slims: ``rows`` (same columns) or ``columns`` (fewer too).""" block = _dict_block(macro_text, "neon_bodies") if block is None: return {} parts = re.split(r"^\s*'([A-Za-z0-9_]+)'\s*:", block, flags=re.MULTILINE) return { name: "rows" if re.search(r"\bselect\s+(?:\w+\.)?\*", body, re.IGNORECASE) else "columns" for name, body in zip(parts[1::2], parts[2::2]) } def load_models(models_dir: Path) -> dict[str, dict[str, Any]]: """Every model declared in the dbt schema files, by name.""" models: dict[str, dict[str, Any]] = {} for path in sorted(models_dir.rglob("*.yml")): for model in (yaml.safe_load(path.read_text(encoding="utf-8")) or {}).get( "models" ) or []: if model.get("name") in models: logger.warning( "{} is declared twice; using its first declaration", model["name"] ) continue models[model["name"]] = model return models def logical_type(data_type: str) -> str: """The ODCS logical type of a Postgres data type as dbt declares it.""" t = data_type.strip().lower() if t.endswith("[]"): return "array" if t in ("json", "jsonb"): return "object" if t.startswith(("bigint", "integer", "int", "smallint", "serial", "bigserial")): return "integer" if t.startswith(("numeric", "decimal", "double", "real", "float")): return "number" if t.startswith("bool"): return "boolean" if t == "date": return "date" if t.startswith("timestamp"): return "timestamp" if t.startswith("time"): return "time" return "string" def _clean(text: Any) -> str: return " ".join(str(text).split()) if text else "" def _ref(target: Any) -> str: """``ref('mdm_organization')`` -> ``mdm_organization``.""" found = re.search(r"ref\(\s*['\"]([^'\"]+)['\"]", str(target)) return found.group(1) if found else str(target).strip().strip("'\"").split(".")[-1] def _reference(owner: str, relation: str, column: str) -> str: """ODCS's fully qualified reference to a column, written in the contract of ``owner``. Every contract holds one table, whose ``id`` is the relation's name, and each property's ``id`` is its column's name. Within the same contract the file part is left out; otherwise it is the other contract's file, in the same folder: ``.odcs.yaml#/schema//properties/``. """ path = f"schema/{relation}/properties/{column}" return path if relation == owner else f"{relation}{SUFFIX}#/{path}" def _target(reference: str) -> tuple[str, str]: """The (relation, column) that a reference written by :func:`_reference` points at.""" _, _, path = reference.rpartition("#/") _, relation, _, column = path.split("/") return relation, column def _grain(description: str) -> str | None: """The description's "one row per ..." sentence, which states the relation's grain.""" found = re.search( r"(one row per\b.*?)(? grain.count("("): grain = grain[:-1].rstrip() return grain[0].upper() + grain[1:] + "." def _tests(column: dict[str, Any]) -> list[tuple[str, dict[str, Any]]]: """A column's dbt tests as (name, arguments), for both ``tests`` and ``data_tests``.""" out: list[tuple[str, dict[str, Any]]] = [] for test in (column.get("data_tests") or []) + (column.get("tests") or []): if isinstance(test, str): out.append((test, {})) continue name = next(iter(test)) args = dict(test[name] or {}) args.update(args.pop("arguments", None) or {}) out.append((name, args)) return out def _severity(args: dict[str, Any]) -> str: """ODCS severity of a dbt test: ``warning`` for ``severity: warn``, else ``error`` (dbt's default).""" level = (args.get("config") or {}).get("severity", args.get("severity", "error")) return "warning" if str(level).strip().lower() == "warn" else "error" def _where(args: dict[str, Any]) -> str: """The filter a dbt test runs under (``config: where:``), or empty when it checks every row.""" return _clean((args.get("config") or {}).get("where", args.get("where"))) def _range_text(args: dict[str, Any]) -> str: low, high = args.get("min_value"), args.get("max_value") strict = args.get("inclusive") is False or args.get("strictly") is True if low is not None and high is not None: return f"Values {'strictly between' if strict else 'from'} {low} {'and' if strict else 'to'} {high}" if low is not None: return f"Values {'above' if strict else 'at least'} {low}" return f"Values {'below' if strict else 'at most'} {high}" LIBRARY = { # dbt test -> (ODCS library metric, dimension, sentence for a filtered copy) "not_null": ("nullValues", "completeness", "No null values"), "unique": ("duplicateValues", "uniqueness", "No duplicate values"), "accepted_values": ("invalidValues", "conformity", "Values only from {values}"), } def _rule(name: str, args: dict[str, Any]) -> dict[str, Any] | None: """The ODCS quality rule for one dbt column test, or None when the test has no rule here.""" short = name.split(".")[-1] severity, where = _severity(args), _where(args) if short in LIBRARY and not (short == "accepted_values" and not args.get("values")): metric, dimension, sentence = LIBRARY[short] if not where: rule: dict[str, Any] = {"type": "library", "metric": metric} if short == "accepted_values": rule["arguments"] = {"validValues": list(args["values"])} return rule | {"mustBe": 0, "dimension": dimension, "severity": severity} text = sentence.format(values=list(args.get("values") or [])) elif short in RANGE_TESTS: text, dimension = _range_text(args), "conformity" else: return None if where: text += f" where {where}" return { "type": "text", "description": f"{text} (dbt test {name}).", "dimension": dimension, "severity": severity, } def _property( owner: str, column: dict[str, Any], keys: list[str], foreign: list[tuple[str, str]], redacted: bool, ) -> dict[str, Any]: name = column["name"] data_type = str(column.get("data_type") or "") prop: dict[str, Any] = { "id": name, "name": name, "logicalType": logical_type(data_type), "physicalType": data_type, } description = _clean(column.get("description")) if redacted: description = (description + " " if description else "") + ( "Always null in public: publish_public_serving redacts this column." ) if description: prop["description"] = description constraints = column.get("constraints") or [] kinds = {c.get("type") for c in constraints} tests = _tests(column) # A guarantee needs a Postgres constraint, or a dbt test that fails the build on every row. guaranteed = { n for n, args in tests if _severity(args) == "error" and not _where(args) } if not redacted: # Every primary-key column is not null; only a one-column key makes the column unique. if name in keys or "not_null" in kinds or "not_null" in guaranteed: prop["required"] = True if keys == [name] or "unique" in kinds or "unique" in guaranteed: prop["unique"] = True if name in keys: prop["primaryKey"] = True prop["primaryKeyPosition"] = keys.index(name) + 1 # Relationship targets as (relation, column), each kept once; a target only a warn-level test # asserts is marked so. build_contracts later drops those with no contract to point into. soft: dict[tuple[str, str], bool] = {target: False for target in foreign} for c in constraints: if c.get("type") == "foreign_key" and c.get("to") and c.get("to_columns"): soft[(_ref(c["to"]), c["to_columns"][0])] = False for test_name, args in tests: if test_name == "relationships" and args.get("to") and args.get("field"): target = (_ref(args["to"]), args["field"]) soft[target] = soft.get(target, True) and _severity(args) == "warning" if soft: prop["relationships"] = [ {"type": "foreignKey", "to": _reference(owner, *target)} | ( {"customProperties": [{"property": "dbtTestSeverity", "value": "warn"}]} if is_soft else {} ) for target, is_soft in soft.items() ] quality = ( [] if redacted else [rule for n, args in tests if (rule := _rule(n, args))] ) if not redacted: quality += [ { "type": "text", "description": f"Postgres CHECK constraint: {_clean(c['expression'])}", "dimension": "conformity", "severity": "error", } for c in constraints if c.get("type") == "check" and c.get("expression") ] if quality: prop["quality"] = quality if redacted: prop["customProperties"] = [{"property": "redactedInPublic", "value": True}] return prop def contract_for( model: dict[str, Any], projection: dict[str, list[str]] | None = None, slimmed: str | None = None, ) -> dict[str, Any]: """The ODCS v3.1.0 contract of one served dbt model. ``projection`` is its entry in the macro's ``projections`` (columns kept and redacted); ``slimmed`` is its entry in :func:`serving_bodies` (``rows`` or ``columns``), if any. Its foreign keys point into their parents' contract files; :func:`build_contracts` drops each one whose parent has no contract holding the column. """ name = model["name"] description = _clean(model.get("description")) keys: list[str] = [] foreign: dict[str, list[tuple[str, str]]] = {} composite: list[dict[str, Any]] = [] for c in model.get("constraints") or []: if c.get("type") == "primary_key": keys += list(c.get("columns") or []) elif c.get("type") == "foreign_key": cols, to_cols, target = ( list(c.get("columns") or []), list(c.get("to_columns") or []), _ref(c.get("to")), ) if len(cols) == 1 and len(to_cols) == 1: foreign.setdefault(cols[0], []).append((target, to_cols[0])) elif cols and len(cols) == len(to_cols): composite.append( { "type": "foreignKey", "from": [_reference(name, name, col) for col in cols], "to": [_reference(name, target, col) for col in to_cols], } ) columns = model.get("columns") or [] if not keys: keys = [ c["name"] for c in columns if any(k.get("type") == "primary_key" for k in c.get("constraints") or []) ] redacted = set(projection["redacted"]) if projection else set() if projection: # the view selects these, in this order by_name = {c["name"]: c for c in columns} missing = [c for c in projection["columns"] if c not in by_name] if missing: logger.warning( "{}: the public projection selects columns its schema.yml lacks: {}", name, missing, ) columns = [by_name[c] for c in projection["columns"] if c in by_name] table: dict[str, Any] = { "id": name, "name": name, "physicalName": f"public.{name}", "logicalType": "object", } if description: table["description"] = description grain = _grain(description) if grain: table["dataGranularityDescription"] = grain table["properties"] = [ _property(name, c, keys, foreign.get(c["name"], []), c["name"] in redacted) for c in columns ] if composite: table["relationships"] = composite return { "apiVersion": API_VERSION, "kind": "DataContract", "id": f"open-navigator-public-{name}", "name": name, "version": CONTRACT_VERSION, "status": "active", "dataProduct": "open-navigator-public-api", "description": { "purpose": f"The columns, keys and quality rules the Open Navigator public API relies on in " f"`public.{name}`.", "usage": "Read by the Open Navigator public API from the `public` schema, where the " "publish_public_serving dbt macro publishes it (by default as a view over gold).", "limitations": _limitations(slimmed), }, "tags": ["open-navigator", "public-api"], "schema": [table], } def _limitations(slimmed: str | None) -> str: text = ( "Structure only: no row counts, freshness or service levels. Describes the relation as " "publish_public_serving builds it by default; with the public_serving_launch_scope var on, rows " "may be limited to the launch jurisdictions." ) if slimmed == "rows": text += " Its materialize mode keeps these columns but fewer rows (the Neon serving scope)." elif slimmed == "columns": text += ( " Its materialize mode keeps fewer rows and drops or nulls some of these columns " "(see neon_bodies in publish_public_serving)." ) return text def _enforced(model: dict[str, Any]) -> bool: columns = model.get("columns") or [] contract = (model.get("config") or {}).get("contract") or {} return ( contract.get("enforced") is True and bool(columns) and all(c.get("data_type") for c in columns) ) class Built(NamedTuple): """What :func:`build_contracts` returns. ``contracts``: by relation, in the macro's served order. ``left_out``: the served relations with no enforced dbt contract, so no contract. ``left_out_keys``: the foreign keys left out, each as ``. -> .``. """ contracts: dict[str, dict[str, Any]] left_out: list[str] left_out_keys: list[str] def _drop_unresolved(contracts: dict[str, dict[str, Any]]) -> list[str]: """Remove each foreign key whose target is no property of these contracts; list those removed. A fully qualified reference names a property in the parent's contract, so it resolves only when the parent has a contract holding that column. A parent served without one (#271), one not served at all, or a column its public projection leaves out gives it nothing to point at. Such a key comes back by itself once its parent's contract holds the column. """ held = { name: {p["id"] for p in c["schema"][0]["properties"]} for name, c in contracts.items() } def resolves(reference: str) -> bool: relation, column = _target(reference) return column in held.get(relation, set()) def prune(holder: dict[str, Any], references) -> list[dict[str, Any]]: """Drop the holder's relationships that don't all resolve; return the ones dropped.""" kept: list[dict[str, Any]] = [] dropped: list[dict[str, Any]] = [] for rel in holder.get("relationships", []): (kept if all(map(resolves, references(rel))) else dropped).append(rel) if kept: holder["relationships"] = kept # same key, so the YAML keeps its order else: holder.pop("relationships", None) return dropped def side(references: list[str]) -> str: """One side of a composite key, as ``relation.(a, b)``.""" columns = ", ".join(_target(r)[1] for r in references) return f"{_target(references[0])[0]}.({columns})" left_out: list[str] = [] for name, contract in contracts.items(): table = contract["schema"][0] for prop in table["properties"]: left_out += [ f"{name}.{prop['name']} -> {'.'.join(_target(rel['to']))}" for rel in prune(prop, lambda rel: [rel["to"]]) ] left_out += [ f"{side(rel['from'])} -> {side(rel['to'])}" for rel in prune(table, lambda rel: rel["from"] + rel["to"]) ] return left_out def build_contracts(dbt_dir: Path = DBT_DIR) -> Built: """The contracts of the served relations, the served relations left out (no enforced dbt contract), and the foreign keys left out (no contract holds the column they point at).""" macro = (dbt_dir / "macros" / "publish_public_serving.sql").read_text( encoding="utf-8" ) projected, slimmed = projections(macro), serving_bodies(macro) models = load_models(dbt_dir / "models") contracts: dict[str, dict[str, Any]] = {} left_out: list[str] = [] for name in served_relations(macro): model = models.get(name) if model is None or not _enforced(model): left_out.append(name) continue contracts[name] = contract_for(model, projected.get(name), slimmed.get(name)) return Built(contracts, left_out, _drop_unresolved(contracts)) def render(document: dict[str, Any], header: str = HEADER) -> str: """A contract or product as committed: a header comment, then YAML in a stable order.""" return header + yaml.safe_dump( document, sort_keys=False, allow_unicode=True, width=10_000 ) @lru_cache(maxsize=1) def _schema() -> dict[str, Any]: return json.loads(SCHEMA_FILE.read_text(encoding="utf-8")) def validate( contract: dict[str, Any], schema: dict[str, Any] | None = None ) -> list[str]: """Every way the contract breaks the ODCS v3.1.0 JSON Schema; empty when it is valid.""" from jsonschema import Draft201909Validator validator = Draft201909Validator(schema or _schema()) return sorted( f"{'/'.join(map(str, e.absolute_path)) or ''}: {e.message}" for e in validator.iter_errors(contract) ) def _name(path: Path) -> str: return path.name[: -len(SUFFIX)] def write(dbt_dir: Path = DBT_DIR) -> int: """Regenerate every contract (and remove contracts for relations no longer served).""" contracts, left_out, left_out_keys = build_contracts(dbt_dir) products = odps.products_for(contracts) invalid = { f"{name}{SUFFIX}": f"ODCS {API_VERSION}: {errors[:3]}" for name, c in contracts.items() if (errors := validate(c)) } | { f"{pid}{odps.SUFFIX}": f"ODPS {odps.API_VERSION}: {errors[:3]}" for pid, product in products.items() if (errors := odps.validate(product)) } for name, errors in invalid.items(): logger.error("{}: not valid {}", name, errors) if invalid: return 1 out = dbt_dir / "contracts" out.mkdir(parents=True, exist_ok=True) for name, contract in contracts.items(): (out / f"{name}{SUFFIX}").write_text(render(contract), encoding="utf-8") for path in out.glob(f"*{SUFFIX}"): if _name(path) not in contracts: path.unlink() logger.info( "Removed {}: no longer served with an enforced dbt contract", path.name ) product_dir = out / odps.SUBDIR product_dir.mkdir(exist_ok=True) for pid, product in products.items(): (product_dir / f"{pid}{odps.SUFFIX}").write_text( render(product, odps.HEADER), encoding="utf-8" ) for path in product_dir.glob(f"*{odps.SUFFIX}"): if path.name[: -len(odps.SUFFIX)] not in products: path.unlink() logger.info("Removed {}: no contract names that data product", path.name) logger.success( "Wrote {} ODCS {} contracts and {} ODPS {} data products to {}", len(contracts), API_VERSION, len(products), odps.API_VERSION, out, ) if left_out: logger.warning( "{} served relations have no enforced dbt contract, so no ODCS contract: {}", len(left_out), ", ".join(left_out), ) if left_out_keys: logger.warning( "{} foreign keys point at a column no contract holds, so they are left out: {}", len(left_out_keys), "; ".join(left_out_keys), ) return 0 def check(dbt_dir: Path = DBT_DIR) -> int: """0 when every contract is present, current and valid; 1 (naming each problem) otherwise.""" contracts = build_contracts(dbt_dir).contracts out = dbt_dir / "contracts" problems: list[str] = [] for name, contract in contracts.items(): errors = validate(contract) if errors: problems.append(f"{name}: not valid ODCS {API_VERSION}: {errors[:3]}") path = out / f"{name}{SUFFIX}" if not path.exists(): problems.append(f"{name}: missing {path.name}") elif path.read_text(encoding="utf-8") != render(contract): problems.append( f"{name}: {path.name} is stale (its schema.yml or the served list changed)" ) for path in sorted(out.glob(f"*{SUFFIX}")) if out.exists() else []: if _name(path) not in contracts: problems.append( f"{_name(path)}: extra {path.name} (not served with an enforced dbt contract)" ) problems += _check_products(out, odps.products_for(contracts)) for problem in problems: logger.error(problem) if problems: logger.error("Regenerate with: python -m models.odcs --write") return 1 logger.success( "{} ODCS {} contracts and their ODPS {} data products are current and valid", len(contracts), API_VERSION, odps.API_VERSION, ) return 0 def _check_products(out: Path, products: dict[str, dict[str, Any]]) -> list[str]: """Problems with the ODPS product files: invalid, missing, stale, extra or dangling ports.""" problems: list[str] = [] product_dir = out / odps.SUBDIR for pid, product in products.items(): errors = odps.validate(product) if errors: problems.append(f"{pid}: not valid ODPS {odps.API_VERSION}: {errors[:3]}") path = product_dir / f"{pid}{odps.SUFFIX}" if not path.exists(): problems.append(f"{pid}: missing {odps.SUBDIR}/{path.name}") elif path.read_text(encoding="utf-8") != render(product, odps.HEADER): problems.append( f"{pid}: {odps.SUBDIR}/{path.name} is stale (a contract changed)" ) # Ports must point at contracts that exist on disk, whatever wrote the product file. contract_ids = { (yaml.safe_load(p.read_text(encoding="utf-8")) or {}).get("id") for p in out.glob(f"*{SUFFIX}") } for path in ( sorted(product_dir.glob(f"*{odps.SUFFIX}")) if product_dir.exists() else [] ): if path.name[: -len(odps.SUFFIX)] not in products: problems.append( f"{odps.SUBDIR}/{path.name}: extra (no contract names that data product)" ) product = yaml.safe_load(path.read_text(encoding="utf-8")) or {} problems += [ f"{odps.SUBDIR}/{path.name}: {d}" for d in odps.dangling_ports(product, contract_ids) ] return problems def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="python -m models.odcs", description=__doc__.split("\n\n")[0] ) mode = parser.add_mutually_exclusive_group(required=True) mode.add_argument( "--write", action="store_true", help="regenerate dbt_project/contracts/ and its products/", ) mode.add_argument( "--check", action="store_true", help="fail on a stale, missing, extra or invalid contract or product", ) parser.add_argument( "--dbt-dir", type=Path, default=DBT_DIR, help="the dbt project (default: %(default)s)", ) args = parser.parse_args(argv) return write(args.dbt_dir) if args.write else check(args.dbt_dir) if __name__ == "__main__": raise SystemExit(main())