From a327204b3020336901674fc94932d3f7185e67b2 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Thu, 26 Nov 2026 14:35:09 +0000 Subject: [PATCH 01/21] feat(schema): accept infrahub_version and list the fields a schema export keeps [IFC-3669] Regenerated with uv run invoke backend.generate: InfrahubSchemaWrite gains the optional infrahub_version field, and contract.py gains KEEP_IN_EXPORT_FIELDS. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/schema/generated/contract.py | 6 ++++++ infrahub_sdk/schema/generated/write.py | 1 + 2 files changed, 7 insertions(+) diff --git a/infrahub_sdk/schema/generated/contract.py b/infrahub_sdk/schema/generated/contract.py index 0d9facdb3..45e0994ee 100644 --- a/infrahub_sdk/schema/generated/contract.py +++ b/infrahub_sdk/schema/generated/contract.py @@ -34,3 +34,9 @@ "TextAttributeParametersWrite": frozenset({"id", "state"}), "TextAttributeWrite": frozenset({"inherited"}), } + +# Optional fields a schema export keeps when set, keyed the same way: schema processing does +# not derive them, so a schema file without them fails to load. +KEEP_IN_EXPORT_FIELDS: dict[str, frozenset[str]] = { + "NodeSchemaWrite": frozenset({"inherit_from"}), +} diff --git a/infrahub_sdk/schema/generated/write.py b/infrahub_sdk/schema/generated/write.py index e741aa667..80b14e333 100644 --- a/infrahub_sdk/schema/generated/write.py +++ b/infrahub_sdk/schema/generated/write.py @@ -607,6 +607,7 @@ class SchemaExtensionWrite(BaseModel): class InfrahubSchemaWrite(BaseModel): model_config = ConfigDict(extra="ignore", use_enum_values=True) version: str + infrahub_version: str | None = None nodes: list[NodeSchemaWrite] = Field(default_factory=list) generics: list[GenericSchemaWrite] = Field(default_factory=list) extensions: SchemaExtensionWrite | None = None From 2631a682331e2d86b9df87487e5f660a330d2c7b Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Thu, 26 Nov 2026 14:35:09 +0000 Subject: [PATCH 02/21] test(schema): check that validate_schema accepts infrahub_version [IFC-3669] Co-Authored-By: Claude Opus 5.5 --- tests/unit/sdk/test_schema.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/unit/sdk/test_schema.py b/tests/unit/sdk/test_schema.py index c10a139fd..e3bf464fc 100644 --- a/tests/unit/sdk/test_schema.py +++ b/tests/unit/sdk/test_schema.py @@ -13,7 +13,14 @@ from infrahub_sdk.ctl.schema import display_schema_load_errors, valid_error_path from infrahub_sdk.exceptions import SchemaNotFoundError, ValidationError from infrahub_sdk.protocols import BuiltinIPAddress, BuiltinIPAddressSync, BuiltinTag, BuiltinTagSync -from infrahub_sdk.schema import BranchSchema, InfrahubSchema, InfrahubSchemaBase, InfrahubSchemaSync, NodeSchemaAPI +from infrahub_sdk.schema import ( + BranchSchema, + InfrahubSchema, + InfrahubSchemaBase, + InfrahubSchemaSync, + NodeSchemaAPI, + validate_schema, +) from infrahub_sdk.schema.repository import ( InfrahubCheckDefinitionConfig, InfrahubJinja2TransformConfig, @@ -567,3 +574,17 @@ async def test_schema_load_surfaces_api_error_on_422(client: InfrahubClient, htt assert response.errors assert response.errors["errors"][0]["message"] == api_error_message assert not response.schema_updated + + +def test_validate_schema_accepts_infrahub_version() -> None: + schema = { + "version": "1.0", + "infrahub_version": "1.0.0", + "nodes": [{"name": "Device", "namespace": "Infra", "attributes": [{"name": "hostname", "kind": "Text"}]}], + } + + result = validate_schema(schema=schema) + + assert result.valid is True + assert result.errors == [] + assert result.warnings == [] From c405d508ad00266a927b38f8213269a2e58dae77 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Thu, 26 Nov 2026 15:58:35 +0000 Subject: [PATCH 03/21] feat(schema): keep the fields a schema load requires in schema exports [IFC-3669] Regenerated from the Infrahub schema definitions, which now mark choices, read_only and unique on attributes, and cardinality, identifier and optional on relationships. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/schema/generated/contract.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/infrahub_sdk/schema/generated/contract.py b/infrahub_sdk/schema/generated/contract.py index 45e0994ee..ce1aab57c 100644 --- a/infrahub_sdk/schema/generated/contract.py +++ b/infrahub_sdk/schema/generated/contract.py @@ -38,5 +38,12 @@ # Optional fields a schema export keeps when set, keyed the same way: schema processing does # not derive them, so a schema file without them fails to load. KEEP_IN_EXPORT_FIELDS: dict[str, frozenset[str]] = { + "AttributeSchemaBaseWrite": frozenset({"choices", "read_only", "unique"}), + "GenericAttributeWrite": frozenset({"choices", "read_only", "unique"}), + "ListAttributeWrite": frozenset({"choices", "read_only", "unique"}), "NodeSchemaWrite": frozenset({"inherit_from"}), + "NumberAttributeWrite": frozenset({"choices", "read_only", "unique"}), + "NumberPoolAttributeWrite": frozenset({"choices", "read_only", "unique"}), + "RelationshipSchemaWrite": frozenset({"cardinality", "identifier", "optional"}), + "TextAttributeWrite": frozenset({"choices", "read_only", "unique"}), } From 3229eced4d2f4e727d7ef83efe89ce49feaf318b Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Thu, 26 Nov 2026 16:43:16 +0000 Subject: [PATCH 04/21] feat(schema): export the schema through the server export endpoint [IFC-3669] infrahubctl schema export and InfrahubSchema.export now call GET /api/schema/export and return its document as a SchemaExportDocument. The CLI gains --mode and --single-file, splits the document by namespace with split_by_namespace, and writes only the keys the server returned. A server without the endpoint gives an error that names the first release with it; any other error response is reported as the server returned it. The client-side export rules and their models are removed. Co-Authored-By: Claude Opus 5.5 --- docs/docs/infrahubctl/infrahubctl-schema.mdx | 2 + infrahub_sdk/ctl/schema.py | 60 ++- infrahub_sdk/schema/__init__.py | 144 ++++---- infrahub_sdk/schema/export.py | 140 ++----- tests/unit/ctl/schema/test_schema.py | 187 +++++++++- tests/unit/sdk/test_schema_export.py | 369 +++++++------------ 6 files changed, 465 insertions(+), 437 deletions(-) diff --git a/docs/docs/infrahubctl/infrahubctl-schema.mdx b/docs/docs/infrahubctl/infrahubctl-schema.mdx index ec9f24fe3..1ffd7afd0 100644 --- a/docs/docs/infrahubctl/infrahubctl-schema.mdx +++ b/docs/docs/infrahubctl/infrahubctl-schema.mdx @@ -81,6 +81,8 @@ $ infrahubctl schema export [OPTIONS] * `--directory PATH`: Directory path to store schema files [default: (dynamic)] * `--branch TEXT`: Branch from which to export the schema * `--namespaces TEXT`: Namespace(s) to export (default: all user-defined) +* `--mode [BRIEF|FULL]`: BRIEF leaves out the values Infrahub derives when the schema is loaded; FULL writes every value [default: BRIEF] +* `--single-file`: Write all namespaces to one file, schema.yml * `--debug / --no-debug`: [default: no-debug] * `--config-file TEXT`: [env var: INFRAHUBCTL_CONFIG; default: infrahubctl.toml] * `--help`: Show this message and exit. diff --git a/infrahub_sdk/ctl/schema.py b/infrahub_sdk/ctl/schema.py index 46b7f2072..82f5aa863 100644 --- a/infrahub_sdk/ctl/schema.py +++ b/infrahub_sdk/ctl/schema.py @@ -17,8 +17,16 @@ from ..async_typer import AsyncTyper from ..ctl.client import initialize_client from ..ctl.utils import catch_exception, init_logging +from ..exceptions import ApiError, VersionNotSupportedError from ..queries import SCHEMA_HASH_SYNC_STATUS -from ..schema import NodeSchemaAPI, SchemaWarning, validate_schema +from ..schema import ( + NodeSchemaAPI, + SchemaExportDocument, + SchemaExportMode, + SchemaWarning, + split_by_namespace, + validate_schema, +) from ..yaml import SchemaFile from .parameters import CONFIG_PARAM from .schema_format import ( @@ -32,6 +40,8 @@ SchemaContainer = Literal["nodes", "generics", "relationships"] +_EXPORT_LEADING_KEYS = ("version", "infrahub_version", "generics", "nodes") + app = AsyncTyper() console = Console() @@ -297,6 +307,11 @@ async def export( directory: Path = typer.Option(_default_export_directory, help="Directory path to store schema files"), branch: str = typer.Option(None, help="Branch from which to export the schema"), namespaces: list[str] = typer.Option([], help="Namespace(s) to export (default: all user-defined)"), + mode: SchemaExportMode = typer.Option( + SchemaExportMode.BRIEF, + help="BRIEF leaves out the values Infrahub derives when the schema is loaded; FULL writes every value", + ), + single_file: bool = typer.Option(False, "--single-file", help="Write all namespaces to one file, schema.yml"), debug: bool = False, _: str = CONFIG_PARAM, ) -> None: @@ -304,34 +319,41 @@ async def export( init_logging(debug=debug) client = initialize_client() - user_schemas = await client.schema.export( - branch=branch, - namespaces=namespaces or None, - ) + try: + document = await client.schema.export(branch=branch, namespaces=namespaces or None, mode=mode) + except (VersionNotSupportedError, ApiError) as exc: + console.print(f"[red]Error: {escape(str(exc))}") + raise typer.Exit(code=1) from exc - if not user_schemas.namespaces: + if not document.nodes and not document.generics: console.print("[yellow]No user-defined schema found to export.") return directory.mkdir(parents=True, exist_ok=True) - for ns, data in sorted(user_schemas.namespaces.items()): - payload: dict[str, Any] = {"version": "1.0"} - if data.generics: - payload["generics"] = data.generics - if data.nodes: - payload["nodes"] = data.nodes - - output_file = directory / f"{ns.lower()}.yml" - output_file.write_text( - yaml.dump(payload, default_flow_style=False, sort_keys=False, allow_unicode=True), - encoding="utf-8", - ) - console.print(f"[green] Exported namespace '{ns}' to {output_file}") + if single_file: + output_file = directory / "schema.yml" + _write_schema_file(document=document, output_file=output_file) + console.print(f"[green] Exported schema to {output_file}") + else: + for ns, namespace_document in sorted(split_by_namespace(document).items()): + output_file = directory / f"{ns.lower()}.yml" + _write_schema_file(document=namespace_document, output_file=output_file) + console.print(f"[green] Exported namespace '{ns}' to {output_file}") console.print(f"[green] Schema exported to {directory}") +def _write_schema_file(document: SchemaExportDocument, output_file: Path) -> None: + # Only the fields the server returned are written, so a value it left out is not replaced by its default. + data = document.model_dump(mode="json", exclude_unset=True) + leading = {key: data.pop(key) for key in _EXPORT_LEADING_KEYS if key in data} + output_file.write_text( + yaml.dump({**leading, **data}, default_flow_style=False, sort_keys=False, allow_unicode=True), + encoding="utf-8", + ) + + @app.command(name="list") @catch_exception(console=console) async def schema_list( diff --git a/infrahub_sdk/schema/__init__.py b/infrahub_sdk/schema/__init__.py index fb2d5cddf..c815bb672 100644 --- a/infrahub_sdk/schema/__init__.py +++ b/infrahub_sdk/schema/__init__.py @@ -14,16 +14,18 @@ from pydantic import BaseModel, Field from ..exceptions import ( + ApiError, BranchNotFoundError, InvalidResponseError, JsonDecodeError, SchemaNotFoundError, ValidationError, + VersionNotSupportedError, ) from ..graphql import Mutation from ..protocols_base import CoreNodeBase from ..queries import SCHEMA_HASH_SYNC_STATUS -from .export import RESTRICTED_NAMESPACES, NamespaceExport, SchemaExport, schema_to_export_dict +from .export import SchemaExportDocument, SchemaExportMode, split_by_namespace from .generated.read import InfrahubSchemaRead from .generated.write import InfrahubSchemaWrite from .main import ( @@ -66,7 +68,6 @@ "GenericSchemaAPI", "InfrahubSchemaRead", "InfrahubSchemaWrite", - "NamespaceExport", "NodeSchema", "NodeSchemaAPI", "ProfileSchemaAPI", @@ -74,17 +75,24 @@ "RelationshipKind", "RelationshipSchema", "RelationshipSchemaAPI", - "SchemaExport", + "SchemaExportDocument", + "SchemaExportMode", "SchemaRoot", "SchemaRootAPI", "SchemaValidationErrorDetail", "SchemaValidationResult", "SchemaValidationWarningDetail", "TemplateSchemaAPI", - "schema_to_export_dict", + "split_by_namespace", "validate_schema", ] +SCHEMA_EXPORT_MIN_INFRAHUB_VERSION = "1.13.0" +"""First Infrahub release that serves the schema export endpoint.""" + +# An older server routes the export URL as a request for a schema kind named "export". +_SCHEMA_EXPORT_MISSING_MESSAGE = "Unable to find the schema export in the database." + class DropdownMutationOptionalArgs(TypedDict): color: str | None @@ -137,47 +145,51 @@ def __init__(self, client: InfrahubClient | InfrahubClientSync) -> None: self.client = client self.cache = {} - @staticmethod - def _build_export_schemas( - schema_nodes: MutableMapping[str, MainSchemaTypesAPI], - namespaces: list[str] | None = None, - ) -> SchemaExport: - """Organize fetched schemas into a per-namespace export structure. + def _export_url(self, branch: str, namespaces: list[str] | None, mode: SchemaExportMode) -> str: + url_parts = [("branch", branch)] + if namespaces: + url_parts.extend([("namespaces", ns) for ns in namespaces]) + url_parts.append(("mode", SchemaExportMode(mode).value)) + return f"{self.client.address}/api/schema/export?{urlencode(url_parts)}" - Filters out system types (Profile/Template) and restricted namespaces - (see :data:`RESTRICTED_NAMESPACES`), and optionally limits to specific - namespaces. If the caller requests restricted namespaces they are - silently excluded and a :func:`warnings.warn` is emitted. + @staticmethod + def _parse_export_response(response: httpx.Response) -> SchemaExportDocument: + """Read the schema export endpoint's response. - Returns: - A :class:`SchemaExport` containing user-defined schemas by namespace. + Raises: + VersionNotSupportedError: When the server is older than the first release with the endpoint. + ApiError: When the server returns any other error, with the messages the server returned. + JsonDecodeError: When the server returns a body that is not JSON. """ - if namespaces: - restricted = set(namespaces) & set(RESTRICTED_NAMESPACES) - if restricted: - warnings.warn( - f"Restricted namespace(s) {sorted(restricted)} requested but will be excluded from export", - stacklevel=3, - ) + if response.status_code == httpx.codes.OK: + try: + return SchemaExportDocument.model_validate(response.json()) + except json.decoder.JSONDecodeError as exc: + raise JsonDecodeError( + message=f"Invalid schema export response received from the server at {response.url}: {response.text} [{response.status_code}]", + content=response.text, + url=str(response.url), + ) from exc + + try: + body = response.json() + except json.decoder.JSONDecodeError: + body = None + errors = body.get("errors") if isinstance(body, dict) else None + error_list = [error for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [] + messages = [error["message"] for error in error_list if isinstance(error.get("message"), str)] + + if response.status_code == httpx.codes.UNPROCESSABLE_ENTITY and _SCHEMA_EXPORT_MISSING_MESSAGE in messages: + raise VersionNotSupportedError( + feature="The schema export", required_version=SCHEMA_EXPORT_MIN_INFRAHUB_VERSION + ) - ns_map: dict[str, NamespaceExport] = {} - for schema in schema_nodes.values(): - if isinstance(schema, (ProfileSchemaAPI, TemplateSchemaAPI)): - continue - if schema.namespace in RESTRICTED_NAMESPACES: - continue - if namespaces and schema.namespace not in namespaces: - continue - ns = schema.namespace - if ns not in ns_map: - ns_map[ns] = NamespaceExport() - schema_dict = schema_to_export_dict(schema) - if isinstance(schema, GenericSchemaAPI): - ns_map[ns].generics.append(schema_dict) - else: - ns_map[ns].nodes.append(schema_dict) - return SchemaExport(namespaces=ns_map) + details = " | ".join(messages) if messages else response.text + api_error = ApiError(message=f"HTTP {response.status_code}: {details}") + api_error.http_status = response.status_code + api_error.errors = error_list + raise api_error def validate(self, data: dict[str, Any]) -> SchemaValidationResult: """Validate a schema payload against the generated write contract. @@ -579,28 +591,26 @@ async def export( self, branch: str | None = None, namespaces: list[str] | None = None, - ) -> SchemaExport: - """Export user-defined schemas organized by namespace. - - Fetches schemas from the server, filters out system types and - restricted namespaces (see :data:`RESTRICTED_NAMESPACES`), and returns - a :class:`SchemaExport` object with per-namespace data. Restricted - namespaces such as ``Core`` and ``Builtin`` are always excluded even if - explicitly listed in *namespaces*; a warning is emitted when this - happens. + mode: SchemaExportMode = SchemaExportMode.BRIEF, + ) -> SchemaExportDocument: + """Export the user-defined schema of a branch as one schema file, built by the server. Args: branch: Branch to export from. Defaults to default_branch. - namespaces: Optional list of namespaces to include. If empty/None, - all user-defined namespaces are exported. + namespaces: Namespaces to export. If empty or None, the server exports all user-defined namespaces. + mode: BRIEF leaves out the values Infrahub derives when the file is loaded; FULL writes every value. Returns: - A :class:`SchemaExport` containing user-defined schemas by namespace. + The server's document, holding only the fields the server returned. + + Raises: + VersionNotSupportedError: When the server is older than the first release with the export endpoint. + ApiError: When the server returns any other error, with the messages the server returned. """ branch = branch or self.client.default_branch - schema_nodes = await self.fetch(branch=branch, namespaces=namespaces, populate_cache=False) - return self._build_export_schemas(schema_nodes=schema_nodes, namespaces=namespaces) + response = await self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) + return self._parse_export_response(response=response) async def get_graphql_schema(self, branch: str | None = None) -> str: """Get the GraphQL schema as a string. @@ -857,28 +867,26 @@ def export( self, branch: str | None = None, namespaces: list[str] | None = None, - ) -> SchemaExport: - """Export user-defined schemas organized by namespace. - - Fetches schemas from the server, filters out system types and - restricted namespaces (see :data:`RESTRICTED_NAMESPACES`), and returns - a :class:`SchemaExport` object with per-namespace data. Restricted - namespaces such as ``Core`` and ``Builtin`` are always excluded even if - explicitly listed in *namespaces*; a warning is emitted when this - happens. + mode: SchemaExportMode = SchemaExportMode.BRIEF, + ) -> SchemaExportDocument: + """Export the user-defined schema of a branch as one schema file, built by the server. Args: branch: Branch to export from. Defaults to default_branch. - namespaces: Optional list of namespaces to include. If empty/None, - all user-defined namespaces are exported. + namespaces: Namespaces to export. If empty or None, the server exports all user-defined namespaces. + mode: BRIEF leaves out the values Infrahub derives when the file is loaded; FULL writes every value. Returns: - A :class:`SchemaExport` containing user-defined schemas by namespace. + The server's document, holding only the fields the server returned. + + Raises: + VersionNotSupportedError: When the server is older than the first release with the export endpoint. + ApiError: When the server returns any other error, with the messages the server returned. """ branch = branch or self.client.default_branch - schema_nodes = self.fetch(branch=branch, namespaces=namespaces, populate_cache=False) - return self._build_export_schemas(schema_nodes=schema_nodes, namespaces=namespaces) + response = self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) + return self._parse_export_response(response=response) def get_graphql_schema(self, branch: str | None = None) -> str: """Get the GraphQL schema as a string. diff --git a/infrahub_sdk/schema/export.py b/infrahub_sdk/schema/export.py index 378f0386d..8aefcc455 100644 --- a/infrahub_sdk/schema/export.py +++ b/infrahub_sdk/schema/export.py @@ -1,121 +1,45 @@ from __future__ import annotations -from typing import Any +from enum import Enum -from pydantic import BaseModel, Field +from .generated.write import GenericSchemaWrite, InfrahubSchemaWrite, NodeSchemaWrite -from .main import GenericSchemaAPI, NodeSchemaAPI +class SchemaExportMode(str, Enum): + BRIEF = "BRIEF" + """Leaves out the values that Infrahub derives again when the export is loaded.""" -class NamespaceExport(BaseModel): - """Export data for a single namespace.""" + FULL = "FULL" + """Writes every value of the user-defined nodes and generics that a schema file can carry.""" - nodes: list[dict[str, Any]] = Field(default_factory=list) - generics: list[dict[str, Any]] = Field(default_factory=list) +class SchemaExportDocument(InfrahubSchemaWrite): + """Schema file returned by the schema export endpoint, valid as a schema load payload.""" -class SchemaExport(BaseModel): - """Result of a schema export, organized by namespace.""" + infrahub_version: str - namespaces: dict[str, NamespaceExport] = Field(default_factory=dict) - def to_dict(self) -> dict[str, dict[str, list[dict[str, Any]]]]: - """Convert to plain dict for YAML serialization.""" - return {ns: data.model_dump(exclude_defaults=True) for ns, data in self.namespaces.items()} +def split_by_namespace(document: SchemaExportDocument) -> dict[str, SchemaExportDocument]: + """Split an exported schema into one document per namespace, keeping the order of the input. + A document only sets `generics` or `nodes` when its namespace has some, so a dump with + `exclude_unset=True` leaves out an empty list. + """ + generics: dict[str, list[GenericSchemaWrite]] = {} + nodes: dict[str, list[NodeSchemaWrite]] = {} + for generic in document.generics: + generics.setdefault(generic.namespace, []).append(generic) + for node in document.nodes: + nodes.setdefault(node.namespace, []).append(node) -# Namespaces reserved by the Infrahub server — mirrored from -# backend/infrahub/core/constants/__init__.py in the opsmill/infrahub repo. -RESTRICTED_NAMESPACES: list[str] = [ - "Account", - "Branch", - "Builtin", - "Core", - "Deprecated", - "Diff", - "Infrahub", - "Internal", - "Lineage", - "Schema", - "Profile", - "Template", -] - -_SCHEMA_EXPORT_EXCLUDE: set[str] = {"hash", "hierarchy", "used_by", "id", "state"} -# branch is inherited from the node and need not be repeated on each field -_FIELD_EXPORT_EXCLUDE: set[str] = {"inherited", "allow_override", "hierarchical", "id", "state", "branch"} - -# Attribute field values that match schema loading defaults — omitted for cleaner output -_ATTR_EXPORT_DEFAULTS: dict[str, Any] = { - "read_only": False, - "optional": False, - "ordered": True, -} - -# Relationship field values that match schema loading defaults — omitted for cleaner output -_REL_EXPORT_DEFAULTS: dict[str, Any] = { - "direction": "bidirectional", - "on_delete": "no-action", - "cardinality": "many", - "optional": True, - "min_count": 0, - "max_count": 0, - "read_only": False, -} - -# Relationship kinds that Infrahub generates automatically — never user-defined -_AUTO_GENERATED_REL_KINDS: frozenset[str] = frozenset({"Group", "Profile", "Hierarchy"}) - - -def schema_to_export_dict(schema: NodeSchemaAPI | GenericSchemaAPI) -> dict[str, Any]: - """Convert an API schema object to an export-ready dict (omits API-internal fields).""" - data = schema.model_dump(exclude=_SCHEMA_EXPORT_EXCLUDE, exclude_none=True) - - # Pop attrs/rels so they can be re-inserted last for better readability - data.pop("attributes", None) - data.pop("relationships", None) - - # Generics with Hierarchy relationships were defined with `hierarchical: true`. - # Restore that flag and drop the auto-generated rels so the schema round-trips cleanly. - if isinstance(schema, GenericSchemaAPI) and any( - rel.kind == "Hierarchy" for rel in schema.relationships if not rel.inherited - ): - data["hierarchical"] = True - - # Strip uniqueness_constraints that are auto-generated from `unique: true` attributes - # (single-field entries of the form ["__value"]). User-defined multi-field - # constraints are preserved. - unique_attr_suffixes = {f"{attr.name}__value" for attr in schema.attributes if attr.unique} - user_constraints = [ - c - for c in (data.pop("uniqueness_constraints", None) or []) - if not (len(c) == 1 and c[0] in unique_attr_suffixes) - ] - if user_constraints: - data["uniqueness_constraints"] = user_constraints - - attributes = [ - { - k: v - for k, v in attr.model_dump(exclude=_FIELD_EXPORT_EXCLUDE, exclude_none=True).items() - if k not in _ATTR_EXPORT_DEFAULTS or v != _ATTR_EXPORT_DEFAULTS[k] - } - for attr in schema.attributes - if not attr.inherited - ] - if attributes: - data["attributes"] = attributes - - relationships = [ - { - k: v - for k, v in rel.model_dump(exclude=_FIELD_EXPORT_EXCLUDE, exclude_none=True).items() - if k not in _REL_EXPORT_DEFAULTS or v != _REL_EXPORT_DEFAULTS[k] - } - for rel in schema.relationships - if not rel.inherited and rel.kind not in _AUTO_GENERATED_REL_KINDS - ] - if relationships: - data["relationships"] = relationships - - return data + documents: dict[str, SchemaExportDocument] = {} + for namespace in [*generics, *nodes]: + if namespace in documents: + continue + namespace_document = SchemaExportDocument(version=document.version, infrahub_version=document.infrahub_version) + if namespace in generics: + namespace_document.generics = generics[namespace] + if namespace in nodes: + namespace_document.nodes = nodes[namespace] + documents[namespace] = namespace_document + return documents diff --git a/tests/unit/ctl/schema/test_schema.py b/tests/unit/ctl/schema/test_schema.py index 771625d30..e33f21771 100644 --- a/tests/unit/ctl/schema/test_schema.py +++ b/tests/unit/ctl/schema/test_schema.py @@ -2,12 +2,22 @@ from __future__ import annotations +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any from unittest.mock import AsyncMock, MagicMock, patch +import pytest +import yaml from typer.testing import CliRunner from infrahub_sdk.ctl.cli_commands import app -from infrahub_sdk.schema import NodeSchemaAPI +from infrahub_sdk.schema import SCHEMA_EXPORT_MIN_INFRAHUB_VERSION, NodeSchemaAPI +from tests.helpers.cli import remove_ansi_color + +if TYPE_CHECKING: + from pathlib import Path + + from pytest_httpx import HTTPXMock runner = CliRunner() @@ -325,3 +335,178 @@ def test_schema_show_attribute_with_default_value() -> None: assert result.exit_code == 0, result.stdout assert "1000" in result.stdout + + +# --------------------------------------------------------------------------- +# schema export tests +# --------------------------------------------------------------------------- + +EXPORT_URL = "http://mock/api/schema/export?branch=main&mode=BRIEF" + +EXPORT_RESPONSE: dict[str, Any] = { + "version": "1.0", + "infrahub_version": "1.13.0", + "generics": [ + { + "name": "Interface", + "namespace": "Network", + "attributes": [{"name": "name", "kind": "Text"}], + }, + ], + "nodes": [ + { + "name": "Device", + "namespace": "Network", + "inherit_from": [], + "attributes": [{"name": "name", "kind": "Text", "unique": True}], + "relationships": [{"name": "site", "peer": "LocationSite", "cardinality": "one", "optional": False}], + }, + {"name": "Site", "namespace": "Location", "attributes": [{"name": "name", "kind": "Text"}]}, + ], +} + + +def _read_yaml(path: Path) -> dict[str, Any]: + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def test_schema_export_writes_one_file_per_namespace(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path)]) + + assert result.exit_code == 0, result.stdout + assert sorted(path.name for path in tmp_path.iterdir()) == ["location.yml", "network.yml"] + + network = _read_yaml(tmp_path / "network.yml") + assert list(network) == ["version", "infrahub_version", "generics", "nodes"] + assert network == { + "version": "1.0", + "infrahub_version": "1.13.0", + "generics": EXPORT_RESPONSE["generics"], + "nodes": [EXPORT_RESPONSE["nodes"][0]], + } + assert _read_yaml(tmp_path / "location.yml") == { + "version": "1.0", + "infrahub_version": "1.13.0", + "nodes": [EXPORT_RESPONSE["nodes"][1]], + } + + +def test_schema_export_single_file_writes_the_endpoint_document(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path), "--single-file"]) + + assert result.exit_code == 0, result.stdout + assert [path.name for path in tmp_path.iterdir()] == ["schema.yml"] + schema = _read_yaml(tmp_path / "schema.yml") + assert list(schema) == ["version", "infrahub_version", "generics", "nodes"] + assert schema == EXPORT_RESPONSE + + +def test_schema_export_writes_no_default_for_a_field_the_response_left_out( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path), "--single-file"]) + + assert result.exit_code == 0, result.stdout + site = _read_yaml(tmp_path / "schema.yml")["nodes"][1] + # These fields have defaults in the schema model, so they would appear if the CLI wrote every field. + for field in ("label", "branch", "state", "generate_profile", "relationships", "inherit_from"): + assert field not in site + assert site["attributes"] == [{"name": "name", "kind": "Text"}] + + +def test_schema_export_sends_mode_and_namespaces(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=main&namespaces=Network&namespaces=Location&mode=FULL", + json=EXPORT_RESPONSE, + ) + + result = runner.invoke( + app, + [ + "schema", + "export", + "--directory", + str(tmp_path), + "--mode", + "FULL", + "--namespaces", + "Network", + "--namespaces", + "Location", + ], + ) + + assert result.exit_code == 0, result.stdout + assert len(httpx_mock.get_requests()) == 1 + + +def test_schema_export_empty_document(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response( + method="GET", + url=EXPORT_URL, + json={"version": "1.0", "infrahub_version": "1.13.0", "generics": [], "nodes": []}, + ) + directory = tmp_path / "export" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory)]) + + assert result.exit_code == 0, result.stdout + assert "No user-defined schema found to export." in result.stdout + assert not directory.exists() + + +@dataclass +class ExportErrorCase: + name: str + status_code: int + message: str + expected_output: str + + +EXPORT_ERROR_CASES = [ + ExportErrorCase( + name="older-server", + status_code=422, + message="Unable to find the schema export in the database.", + expected_output=f"Infrahub {SCHEMA_EXPORT_MIN_INFRAHUB_VERSION} or later", + ), + ExportErrorCase( + name="422-other-message", + status_code=422, + message="Unable to find the schema NetworkDevice in the database.", + expected_output="HTTP 422: Unable to find the schema NetworkDevice in the database.", + ), + ExportErrorCase( + name="500", + status_code=500, + message="Internal server error", + expected_output="HTTP 500: Internal server error", + ), +] + + +@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in EXPORT_ERROR_CASES]) +def test_schema_export_error_response(httpx_mock: HTTPXMock, tmp_path: Path, case: ExportErrorCase) -> None: + httpx_mock.add_response( + method="GET", + url=EXPORT_URL, + status_code=case.status_code, + json={"data": None, "errors": [{"message": case.message, "extensions": {"code": case.status_code}}]}, + ) + directory = tmp_path / "export" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory)]) + + assert result.exit_code == 1 + output = remove_ansi_color(result.stdout.replace("\n", "")) + assert case.expected_output in output + if case.name != "older-server": + assert SCHEMA_EXPORT_MIN_INFRAHUB_VERSION not in output + assert not directory.exists() diff --git a/tests/unit/sdk/test_schema_export.py b/tests/unit/sdk/test_schema_export.py index e579168c6..40ff74272 100644 --- a/tests/unit/sdk/test_schema_export.py +++ b/tests/unit/sdk/test_schema_export.py @@ -1,19 +1,18 @@ from __future__ import annotations -import warnings +import re +from dataclasses import dataclass from typing import TYPE_CHECKING, Any import pytest +from infrahub_sdk.exceptions import ApiError, VersionNotSupportedError from infrahub_sdk.schema import ( - GenericSchemaAPI, - InfrahubSchemaBase, - NodeSchemaAPI, - ProfileSchemaAPI, - SchemaExport, - TemplateSchemaAPI, + SCHEMA_EXPORT_MIN_INFRAHUB_VERSION, + SchemaExportDocument, + SchemaExportMode, + split_by_namespace, ) -from infrahub_sdk.schema.export import schema_to_export_dict if TYPE_CHECKING: from pytest_httpx import HTTPXMock @@ -22,268 +21,156 @@ client_types = ["standard", "sync"] -# --------------------------------------------------------------------------- -# Minimal schema API response builders (reused from ctl tests) -# --------------------------------------------------------------------------- - -_BASE_NODE: dict[str, Any] = { - "id": None, - "state": "present", - "hash": None, - "hierarchy": None, - "label": None, - "description": None, - "include_in_menu": None, - "menu_placement": None, - "display_label": None, - "display_labels": None, - "human_friendly_id": None, - "icon": None, - "uniqueness_constraints": None, - "documentation": None, - "order_by": None, - "inherit_from": [], - "branch": "aware", - "default_filter": None, - "generate_profile": True, - "generate_template": False, - "parent": None, - "children": None, - "attributes": [], - "relationships": [], +EXPORT_RESPONSE: dict[str, Any] = { + "version": "1.0", + "infrahub_version": "1.13.0", + "generics": [ + { + "name": "Interface", + "namespace": "Network", + "human_friendly_id": ["device__name__value", "name__value"], + "attributes": [{"name": "name", "kind": "Text"}], + "relationships": [ + { + "name": "device", + "peer": "NetworkDevice", + "cardinality": "one", + "optional": False, + "kind": "Attribute", + } + ], + }, + ], + "nodes": [ + { + "name": "Device", + "namespace": "Network", + "attributes": [{"name": "name", "kind": "Text", "unique": True}], + }, + {"name": "Site", "namespace": "Location", "attributes": [{"name": "name", "kind": "Text"}]}, + { + "name": "PhysicalInterface", + "namespace": "Network", + "inherit_from": ["NetworkInterface"], + "attributes": [{"name": "speed", "kind": "Number"}], + }, + ], } -_BASE_GENERIC: dict[str, Any] = { - "id": None, - "state": "present", - "hash": None, - "used_by": [], - "label": None, - "description": None, - "include_in_menu": None, - "menu_placement": None, - "display_label": None, - "display_labels": None, - "human_friendly_id": None, - "icon": None, - "uniqueness_constraints": None, - "documentation": None, - "order_by": None, - "attributes": [], - "relationships": [], +OLDER_SERVER_RESPONSE: dict[str, Any] = { + "data": None, + "errors": [{"message": "Unable to find the schema export in the database.", "extensions": {"code": 422}}], } -def _make_node_schema(namespace: str, name: str) -> NodeSchemaAPI: - return NodeSchemaAPI(**{**_BASE_NODE, "namespace": namespace, "name": name}) +async def _export( + clients: BothClients, + client_type: str, + branch: str, + namespaces: list[str] | None = None, + mode: SchemaExportMode = SchemaExportMode.BRIEF, +) -> SchemaExportDocument: + if client_type == "standard": + return await clients.standard.schema.export(branch=branch, namespaces=namespaces, mode=mode) + return clients.sync.schema.export(branch=branch, namespaces=namespaces, mode=mode) -def _make_generic_schema(namespace: str, name: str) -> GenericSchemaAPI: - return GenericSchemaAPI(**{**_BASE_GENERIC, "namespace": namespace, "name": name}) +@pytest.mark.parametrize("client_type", client_types) +async def test_export_returns_the_endpoint_document( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", url="http://mock/api/schema/export?branch=main&mode=BRIEF", json=EXPORT_RESPONSE + ) + document = await _export(clients, client_type, branch="main") -def _make_profile_schema(namespace: str, name: str) -> ProfileSchemaAPI: - return ProfileSchemaAPI( - **{ - **_BASE_NODE, - "namespace": namespace, - "name": name, - } - ) + assert isinstance(document, SchemaExportDocument) + assert document.model_dump(mode="json", exclude_unset=True) == EXPORT_RESPONSE -def _make_template_schema(namespace: str, name: str) -> TemplateSchemaAPI: - return TemplateSchemaAPI( - **{ - **_BASE_NODE, - "namespace": namespace, - "name": name, - } +@pytest.mark.parametrize("client_type", client_types) +async def test_export_sends_branch_namespaces_and_mode( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=feature&namespaces=Network&namespaces=Location&mode=FULL", + json=EXPORT_RESPONSE, ) - -# --------------------------------------------------------------------------- -# _build_export_schemas tests -# --------------------------------------------------------------------------- - - -class TestBuildExportSchemas: - def test_separates_nodes_and_generics(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - "InfraInterface": _make_generic_schema("Infra", "Interface"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - assert isinstance(result, SchemaExport) - assert "Infra" in result.namespaces - assert len(result.namespaces["Infra"].nodes) == 1 - assert len(result.namespaces["Infra"].generics) == 1 - assert result.namespaces["Infra"].nodes[0]["name"] == "Device" - assert result.namespaces["Infra"].generics[0]["name"] == "Interface" - - def test_groups_by_namespace(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - "DcimRack": _make_node_schema("Dcim", "Rack"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - assert set(result.namespaces.keys()) == {"Infra", "Dcim"} - - def test_filters_profiles_and_templates(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - "ProfileInfraDevice": _make_profile_schema("Profile", "InfraDevice"), - "TemplateInfraDevice": _make_template_schema("Template", "InfraDevice"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - assert "Infra" in result.namespaces - assert "Profile" not in result.namespaces - assert "Template" not in result.namespaces - - def test_filters_restricted_namespaces(self) -> None: - schema_nodes = { - "CoreRepository": _make_node_schema("Core", "Repository"), - "BuiltinTag": _make_node_schema("Builtin", "Tag"), - "InfraDevice": _make_node_schema("Infra", "Device"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - assert "Core" not in result.namespaces - assert "Builtin" not in result.namespaces - assert "Infra" in result.namespaces - - def test_namespace_filter(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - "DcimRack": _make_node_schema("Dcim", "Rack"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes, namespaces=["Infra"]) - assert "Infra" in result.namespaces - assert "Dcim" not in result.namespaces - - def test_empty_when_no_user_schemas(self) -> None: - schema_nodes = { - "CoreRepository": _make_node_schema("Core", "Repository"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - assert result.namespaces == {} - - def test_warns_on_restricted_namespaces(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - } - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always") - result = InfrahubSchemaBase._build_export_schemas(schema_nodes, namespaces=["Infra", "Core"]) - assert len(w) == 1 - assert "Core" in str(w[0].message) - assert "Infra" in result.namespaces - - def test_to_dict(self) -> None: - schema_nodes = { - "InfraDevice": _make_node_schema("Infra", "Device"), - "InfraInterface": _make_generic_schema("Infra", "Interface"), - } - result = InfrahubSchemaBase._build_export_schemas(schema_nodes) - as_dict = result.to_dict() - assert isinstance(as_dict, dict) - assert "Infra" in as_dict - assert isinstance(as_dict["Infra"], dict) - assert len(as_dict["Infra"]["nodes"]) == 1 - assert len(as_dict["Infra"]["generics"]) == 1 - - -def test_export_preserves_non_default_ordered_flag() -> None: - """`ordered: false` survives the fetch -> export round-trip; the default `true` is omitted.""" - node = NodeSchemaAPI( - **{ - **_BASE_NODE, - "namespace": "Infra", - "name": "Device", - "attributes": [ - {"name": "tags_unordered", "kind": "List", "ordered": False}, - {"name": "tags_ordered", "kind": "List"}, - ], - } + document = await _export( + clients, client_type, branch="feature", namespaces=["Network", "Location"], mode=SchemaExportMode.FULL ) - exported = schema_to_export_dict(node) - attrs = {attr["name"]: attr for attr in exported["attributes"]} - assert attrs["tags_unordered"]["ordered"] is False - assert "ordered" not in attrs["tags_ordered"] - - -# --------------------------------------------------------------------------- -# Integration tests for export() method on client.schema -# --------------------------------------------------------------------------- - - -def _schema_response( - nodes: list[dict] | None = None, - generics: list[dict] | None = None, - profiles: list[dict] | None = None, - templates: list[dict] | None = None, -) -> dict: - return { - "main": "aabbccdd", - "nodes": nodes or [], - "generics": generics or [], - "profiles": profiles or [], - "templates": templates or [], - } + + assert document.infrahub_version == "1.13.0" -def _make_node_dict(namespace: str, name: str) -> dict[str, Any]: - return {**_BASE_NODE, "namespace": namespace, "name": name} +def test_split_by_namespace_keeps_versions_and_input_order() -> None: + document = SchemaExportDocument.model_validate(EXPORT_RESPONSE) + documents = split_by_namespace(document) -def _make_generic_dict(namespace: str, name: str) -> dict[str, Any]: - return {**_BASE_GENERIC, "namespace": namespace, "name": name} + assert list(documents) == ["Network", "Location"] + for namespace_document in documents.values(): + assert isinstance(namespace_document, SchemaExportDocument) + assert namespace_document.version == "1.0" + assert namespace_document.infrahub_version == "1.13.0" + assert [generic.name for generic in documents["Network"].generics] == ["Interface"] + assert [node.name for node in documents["Network"].nodes] == ["Device", "PhysicalInterface"] + assert [node.name for node in documents["Location"].nodes] == ["Site"] + assert documents["Location"].model_dump(mode="json", exclude_unset=True) == { + "version": "1.0", + "infrahub_version": "1.13.0", + "nodes": [EXPORT_RESPONSE["nodes"][1]], + } @pytest.mark.parametrize("client_type", client_types) -async def test_export_returns_user_schemas(httpx_mock: HTTPXMock, clients: BothClients, client_type: str) -> None: - response = _schema_response( - nodes=[_make_node_dict("Infra", "Device"), _make_node_dict("Dcim", "Rack")], - generics=[_make_generic_dict("Infra", "GenericInterface")], +async def test_export_names_the_release_on_an_older_server( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=main&mode=BRIEF", + status_code=422, + json=OLDER_SERVER_RESPONSE, ) - httpx_mock.add_response(method="GET", url="http://mock/api/schema?branch=main", json=response) - - if client_type == "standard": - result = await clients.standard.schema.export(branch="main") - else: - result = clients.sync.schema.export(branch="main") - assert isinstance(result, SchemaExport) - assert "Infra" in result.namespaces - assert "Dcim" in result.namespaces - assert len(result.namespaces["Infra"].nodes) == 1 - assert len(result.namespaces["Infra"].generics) == 1 - assert len(result.namespaces["Dcim"].nodes) == 1 + with pytest.raises(VersionNotSupportedError, match=re.escape(f"Infrahub {SCHEMA_EXPORT_MIN_INFRAHUB_VERSION}")): + await _export(clients, client_type, branch="main") -@pytest.mark.parametrize("client_type", client_types) -async def test_export_with_namespace_filter(httpx_mock: HTTPXMock, clients: BothClients, client_type: str) -> None: - response = _schema_response( - nodes=[_make_node_dict("Infra", "Device")], - ) - httpx_mock.add_response(method="GET", url="http://mock/api/schema?branch=main&namespaces=Infra", json=response) +@dataclass +class ErrorResponseCase: + name: str + status_code: int + message: str - if client_type == "standard": - result = await clients.standard.schema.export(branch="main", namespaces=["Infra"]) - else: - result = clients.sync.schema.export(branch="main", namespaces=["Infra"]) - assert "Infra" in result.namespaces - assert "Dcim" not in result.namespaces +ERROR_RESPONSE_CASES = [ + ErrorResponseCase( + name="422-other-message", status_code=422, message="Unable to find the schema NetworkDevice in the database." + ), + ErrorResponseCase(name="500", status_code=500, message="Internal server error"), +] @pytest.mark.parametrize("client_type", client_types) -async def test_export_empty_when_only_restricted(httpx_mock: HTTPXMock, clients: BothClients, client_type: str) -> None: - response = _schema_response(nodes=[_make_node_dict("Core", "Repository")]) - httpx_mock.add_response(method="GET", url="http://mock/api/schema?branch=main", json=response) +@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in ERROR_RESPONSE_CASES]) +async def test_export_reports_other_errors_as_returned( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str, case: ErrorResponseCase +) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=main&mode=BRIEF", + status_code=case.status_code, + json={"data": None, "errors": [{"message": case.message, "extensions": {"code": case.status_code}}]}, + ) - if client_type == "standard": - result = await clients.standard.schema.export(branch="main") - else: - result = clients.sync.schema.export(branch="main") + with pytest.raises(ApiError, match=re.escape(f"HTTP {case.status_code}: {case.message}")) as exc_info: + await _export(clients, client_type, branch="main") - assert result.namespaces == {} + assert not isinstance(exc_info.value, VersionNotSupportedError) + assert SCHEMA_EXPORT_MIN_INFRAHUB_VERSION not in str(exc_info.value) + assert exc_info.value.http_status == case.status_code From 513bd03386da4b70e7a98961cc810854357675a3 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Thu, 26 Nov 2026 16:43:16 +0000 Subject: [PATCH 05/21] docs(changelog): describe the schema export through the server endpoint [IFC-3669] Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-client-rules.removed.md | 1 + changelog/+schema-export-document.changed.md | 1 + changelog/+schema-export-endpoint.changed.md | 11 +++++++++++ changelog/+schema-export-options.added.md | 1 + 4 files changed, 14 insertions(+) create mode 100644 changelog/+schema-export-client-rules.removed.md create mode 100644 changelog/+schema-export-document.changed.md create mode 100644 changelog/+schema-export-endpoint.changed.md create mode 100644 changelog/+schema-export-options.added.md diff --git a/changelog/+schema-export-client-rules.removed.md b/changelog/+schema-export-client-rules.removed.md new file mode 100644 index 000000000..89654d222 --- /dev/null +++ b/changelog/+schema-export-client-rules.removed.md @@ -0,0 +1 @@ +Removed `schema_to_export_dict`, `RESTRICTED_NAMESPACES`, `NamespaceExport` and `SchemaExport` from `infrahub_sdk.schema`, because Infrahub now builds the schema export. Use `SchemaExportDocument` and `split_by_namespace` instead. diff --git a/changelog/+schema-export-document.changed.md b/changelog/+schema-export-document.changed.md new file mode 100644 index 000000000..0e0793b3f --- /dev/null +++ b/changelog/+schema-export-document.changed.md @@ -0,0 +1 @@ +`InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits a `SchemaExportDocument` into one document per namespace. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md new file mode 100644 index 000000000..c97b84da1 --- /dev/null +++ b/changelog/+schema-export-endpoint.changed.md @@ -0,0 +1,11 @@ +`infrahubctl schema export` now asks Infrahub to build the export, so it needs an Infrahub server with the schema export endpoint (Infrahub 1.13.0 or later). With the default `BRIEF` mode, the files it writes differ from the files earlier versions wrote: + +- `branch` on an attribute or relationship is written when it differs from the value Infrahub derives from the node or the peer. +- Values that Infrahub derives when it loads the schema, such as a `label` taken from the name, are left out. +- When an attribute has `unique: true`, the `human_friendly_id` and `uniqueness_constraints` that Infrahub derives from it are left out, and `unique` is written. +- The relationship `identifier`, `cardinality` and `optional`, and the attribute `read_only` and `choices`, are written when they differ from their default value. +- `IpamNamespace` is no longer written. +- The `object_template` relationship that Infrahub generates is no longer written. +- `regex` is written under `parameters`. `min_length` and `max_length` are written under `parameters` for every attribute kind except `List`, which keeps them at the top level. +- NumberPool `start_range` and `end_range` are written as one entry of `ranges`. +- Each file has an `infrahub_version` field with the version of the Infrahub server that built it. diff --git a/changelog/+schema-export-options.added.md b/changelog/+schema-export-options.added.md new file mode 100644 index 000000000..bd870f4d1 --- /dev/null +++ b/changelog/+schema-export-options.added.md @@ -0,0 +1 @@ +Added the `--mode` option to `infrahubctl schema export`: `BRIEF`, the default, leaves out the values Infrahub derives when it loads the schema, and `FULL` writes every value. Added the `--single-file` option, which writes all namespaces to one file, `schema.yml`. From e9b8eed4573c7a37dbd15204dcbed5fb8e1f84ef Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Thu, 26 Nov 2026 17:03:43 +0000 Subject: [PATCH 06/21] fix(schema): recognize the error an older server sends for the schema export [IFC-3669] An Infrahub server without the export endpoint answers with "Unable to find the schema 'export' in the registry", so the SDK now matches that message and names the first release with the endpoint. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/schema/__init__.py | 2 +- tests/unit/ctl/schema/test_schema.py | 8 ++++---- tests/unit/sdk/test_schema_export.py | 7 +++++-- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/infrahub_sdk/schema/__init__.py b/infrahub_sdk/schema/__init__.py index c815bb672..9885e969e 100644 --- a/infrahub_sdk/schema/__init__.py +++ b/infrahub_sdk/schema/__init__.py @@ -91,7 +91,7 @@ """First Infrahub release that serves the schema export endpoint.""" # An older server routes the export URL as a request for a schema kind named "export". -_SCHEMA_EXPORT_MISSING_MESSAGE = "Unable to find the schema export in the database." +_SCHEMA_EXPORT_MISSING_MESSAGE = "Unable to find the schema 'export' in the registry" class DropdownMutationOptionalArgs(TypedDict): diff --git a/tests/unit/ctl/schema/test_schema.py b/tests/unit/ctl/schema/test_schema.py index e33f21771..8c86a2306 100644 --- a/tests/unit/ctl/schema/test_schema.py +++ b/tests/unit/ctl/schema/test_schema.py @@ -474,14 +474,14 @@ class ExportErrorCase: ExportErrorCase( name="older-server", status_code=422, - message="Unable to find the schema export in the database.", + message="Unable to find the schema 'export' in the registry", expected_output=f"Infrahub {SCHEMA_EXPORT_MIN_INFRAHUB_VERSION} or later", ), ExportErrorCase( - name="422-other-message", + name="422-other-kind", status_code=422, - message="Unable to find the schema NetworkDevice in the database.", - expected_output="HTTP 422: Unable to find the schema NetworkDevice in the database.", + message="Unable to find the schema 'NetworkDevice' in the registry", + expected_output="HTTP 422: Unable to find the schema 'NetworkDevice' in the registry", ), ExportErrorCase( name="500", diff --git a/tests/unit/sdk/test_schema_export.py b/tests/unit/sdk/test_schema_export.py index 40ff74272..2ce3283e4 100644 --- a/tests/unit/sdk/test_schema_export.py +++ b/tests/unit/sdk/test_schema_export.py @@ -59,7 +59,7 @@ OLDER_SERVER_RESPONSE: dict[str, Any] = { "data": None, - "errors": [{"message": "Unable to find the schema export in the database.", "extensions": {"code": 422}}], + "errors": [{"message": "Unable to find the schema 'export' in the registry", "extensions": {"code": 422}}], } @@ -150,7 +150,10 @@ class ErrorResponseCase: ERROR_RESPONSE_CASES = [ ErrorResponseCase( - name="422-other-message", status_code=422, message="Unable to find the schema NetworkDevice in the database." + name="422-other-kind", status_code=422, message="Unable to find the schema 'NetworkDevice' in the registry" + ), + ErrorResponseCase( + name="422-other-message", status_code=422, message="Unable to find the schema export in the database." ), ErrorResponseCase(name="500", status_code=500, message="Internal server error"), ] From e59fd9c8de5a5fcfda3fa92dc546280b2b024d37 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Thu, 26 Nov 2026 17:29:20 +0000 Subject: [PATCH 07/21] docs(schema): correct the parameters changelog entry and the keep_in_export comment [IFC-3669] State which attribute kinds write regex, min_length and max_length under parameters, and regenerate the KEEP_IN_EXPORT_FIELDS comment. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-endpoint.changed.md | 2 +- infrahub_sdk/schema/generated/contract.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md index c97b84da1..5d2ebde7c 100644 --- a/changelog/+schema-export-endpoint.changed.md +++ b/changelog/+schema-export-endpoint.changed.md @@ -6,6 +6,6 @@ - The relationship `identifier`, `cardinality` and `optional`, and the attribute `read_only` and `choices`, are written when they differ from their default value. - `IpamNamespace` is no longer written. - The `object_template` relationship that Infrahub generates is no longer written. -- `regex` is written under `parameters`. `min_length` and `max_length` are written under `parameters` for every attribute kind except `List`, which keeps them at the top level. +- On a `Text` or `TextArea` attribute, `regex`, `min_length` and `max_length` are written under `parameters`. On a `List` attribute, `regex` is written under `parameters`, and `min_length` and `max_length` stay at the top level. On an attribute of any other kind, these settings stay at the top level. - NumberPool `start_range` and `end_range` are written as one entry of `ranges`. - Each file has an `infrahub_version` field with the version of the Infrahub server that built it. diff --git a/infrahub_sdk/schema/generated/contract.py b/infrahub_sdk/schema/generated/contract.py index ce1aab57c..b1e527d5b 100644 --- a/infrahub_sdk/schema/generated/contract.py +++ b/infrahub_sdk/schema/generated/contract.py @@ -35,8 +35,8 @@ "TextAttributeWrite": frozenset({"inherited"}), } -# Optional fields a schema export keeps when set, keyed the same way: schema processing does -# not derive them, so a schema file without them fails to load. +# Optional fields a schema export keeps unless they hold their default, keyed the same way: a +# shortened export without them fails validation, so the export writes every value. KEEP_IN_EXPORT_FIELDS: dict[str, frozenset[str]] = { "AttributeSchemaBaseWrite": frozenset({"choices", "read_only", "unique"}), "GenericAttributeWrite": frozenset({"choices", "read_only", "unique"}), From a5c8240471d889dee189859f54722825f988149e Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Fri, 27 Nov 2026 09:23:38 +0000 Subject: [PATCH 08/21] feat(schema): report each namespace the schema export cannot select [IFC-3669] The server answers a namespace that does not exist on the branch, or a restricted one, with a 404 whose errors name the namespace in extensions.namespace. The SDK raises SchemaNamespaceNotFoundError for that response, and URLNotFoundError for a 404 that names no namespace, such as Infrahub's answer to an unknown URL. infrahubctl schema export prints one error line per namespace and exits with code 1. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-document.changed.md | 2 +- changelog/+schema-export-endpoint.changed.md | 2 + infrahub_sdk/ctl/schema.py | 8 +- infrahub_sdk/exceptions/__init__.py | 2 + infrahub_sdk/exceptions/base.py | 10 +++ infrahub_sdk/schema/__init__.py | 27 +++++++ .../error_catalogue/public_names.json | 1 + tests/unit/ctl/schema/test_schema.py | 60 +++++++++++++++ tests/unit/sdk/test_schema_export.py | 73 ++++++++++++++++++- 9 files changed, 181 insertions(+), 4 deletions(-) diff --git a/changelog/+schema-export-document.changed.md b/changelog/+schema-export-document.changed.md index 0e0793b3f..c6ff4a388 100644 --- a/changelog/+schema-export-document.changed.md +++ b/changelog/+schema-export-document.changed.md @@ -1 +1 @@ -`InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits a `SchemaExportDocument` into one document per namespace. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. +`InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits a `SchemaExportDocument` into one document per namespace. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. When `namespaces` names a namespace that does not exist on the branch, or a namespace reserved for Infrahub such as `Core`, they raise the new `SchemaNamespaceNotFoundError`, with one message for each such namespace. diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md index 5d2ebde7c..bbcd85c64 100644 --- a/changelog/+schema-export-endpoint.changed.md +++ b/changelog/+schema-export-endpoint.changed.md @@ -9,3 +9,5 @@ - On a `Text` or `TextArea` attribute, `regex`, `min_length` and `max_length` are written under `parameters`. On a `List` attribute, `regex` is written under `parameters`, and `min_length` and `max_length` stay at the top level. On an attribute of any other kind, these settings stay at the top level. - NumberPool `start_range` and `end_range` are written as one entry of `ranges`. - Each file has an `infrahub_version` field with the version of the Infrahub server that built it. + +`--namespaces` with a namespace that does not exist on the branch, or with a namespace reserved for Infrahub such as `Core`, now prints an error for each such namespace and exits with code 1. diff --git a/infrahub_sdk/ctl/schema.py b/infrahub_sdk/ctl/schema.py index 82f5aa863..0665c993e 100644 --- a/infrahub_sdk/ctl/schema.py +++ b/infrahub_sdk/ctl/schema.py @@ -17,7 +17,7 @@ from ..async_typer import AsyncTyper from ..ctl.client import initialize_client from ..ctl.utils import catch_exception, init_logging -from ..exceptions import ApiError, VersionNotSupportedError +from ..exceptions import ApiError, SchemaNamespaceNotFoundError, URLNotFoundError, VersionNotSupportedError from ..queries import SCHEMA_HASH_SYNC_STATUS from ..schema import ( NodeSchemaAPI, @@ -321,7 +321,11 @@ async def export( client = initialize_client() try: document = await client.schema.export(branch=branch, namespaces=namespaces or None, mode=mode) - except (VersionNotSupportedError, ApiError) as exc: + except SchemaNamespaceNotFoundError as exc: + for message in exc.messages: + console.print(f"[red]Error: {escape(message)}") + raise typer.Exit(code=1) from exc + except (VersionNotSupportedError, URLNotFoundError, ApiError) as exc: console.print(f"[red]Error: {escape(str(exc))}") raise typer.Exit(code=1) from exc diff --git a/infrahub_sdk/exceptions/__init__.py b/infrahub_sdk/exceptions/__init__.py index 3e84e8254..ab9ecbe76 100644 --- a/infrahub_sdk/exceptions/__init__.py +++ b/infrahub_sdk/exceptions/__init__.py @@ -44,6 +44,7 @@ RateLimitError, RepositoryFileNotFoundError, ResourceNotDefinedError, + SchemaNamespaceNotFoundError, SchemaNotFoundError, ServerNotReachableError, ServerNotResponsiveError, @@ -106,6 +107,7 @@ "RateLimitError", "RepositoryFileNotFoundError", "ResourceNotDefinedError", + "SchemaNamespaceNotFoundError", "SchemaNotFoundError", "ServerNotReachableError", "ServerNotResponsiveError", diff --git a/infrahub_sdk/exceptions/base.py b/infrahub_sdk/exceptions/base.py index 656cd069e..f67badad4 100644 --- a/infrahub_sdk/exceptions/base.py +++ b/infrahub_sdk/exceptions/base.py @@ -37,6 +37,7 @@ "RateLimitError", "RepositoryFileNotFoundError", "ResourceNotDefinedError", + "SchemaNamespaceNotFoundError", "SchemaNotFoundError", "ServerNotReachableError", "ServerNotResponsiveError", @@ -206,6 +207,15 @@ def __reduce__(self) -> tuple[type[TrackingGroupCleanupError], tuple[dict[str, s return (self.__class__, (self.failures,)) +class SchemaNamespaceNotFoundError(ApiError): + """Raised when a schema export names a namespace that does not exist on the branch or cannot be exported.""" + + def __init__(self, namespaces: list[str], messages: list[str]) -> None: + self.namespaces = namespaces + self.messages = messages + super().__init__("; ".join(messages)) + + class VersionNotSupportedError(Error): """Raised when a feature is used against an Infrahub server version that does not support it.""" diff --git a/infrahub_sdk/schema/__init__.py b/infrahub_sdk/schema/__init__.py index 9885e969e..20b12b8c4 100644 --- a/infrahub_sdk/schema/__init__.py +++ b/infrahub_sdk/schema/__init__.py @@ -18,7 +18,9 @@ BranchNotFoundError, InvalidResponseError, JsonDecodeError, + SchemaNamespaceNotFoundError, SchemaNotFoundError, + URLNotFoundError, ValidationError, VersionNotSupportedError, ) @@ -94,6 +96,13 @@ _SCHEMA_EXPORT_MISSING_MESSAGE = "Unable to find the schema 'export' in the registry" +def _error_namespace(error: dict[str, Any]) -> str | None: + """Return the namespace a schema export error names in its extensions, if any.""" + extensions = error.get("extensions") + namespace = extensions.get("namespace") if isinstance(extensions, dict) else None + return namespace if isinstance(namespace, str) else None + + class DropdownMutationOptionalArgs(TypedDict): color: str | None description: str | None @@ -158,6 +167,9 @@ def _parse_export_response(response: httpx.Response) -> SchemaExportDocument: Raises: VersionNotSupportedError: When the server is older than the first release with the endpoint. + SchemaNamespaceNotFoundError: When a requested namespace does not exist on the branch or cannot be + exported, with one message per namespace. + URLNotFoundError: When the server returns a 404 that does not name a namespace. ApiError: When the server returns any other error, with the messages the server returned. JsonDecodeError: When the server returns a body that is not JSON. @@ -185,6 +197,17 @@ def _parse_export_response(response: httpx.Response) -> SchemaExportDocument: feature="The schema export", required_version=SCHEMA_EXPORT_MIN_INFRAHUB_VERSION ) + if response.status_code == httpx.codes.NOT_FOUND: + namespaces = [_error_namespace(error) for error in error_list] + if not error_list or None in namespaces: + raise URLNotFoundError(url=str(response.url)) + namespace_error = SchemaNamespaceNotFoundError( + namespaces=[namespace for namespace in namespaces if namespace is not None], messages=messages + ) + namespace_error.http_status = response.status_code + namespace_error.errors = error_list + raise namespace_error + details = " | ".join(messages) if messages else response.text api_error = ApiError(message=f"HTTP {response.status_code}: {details}") api_error.http_status = response.status_code @@ -605,6 +628,8 @@ async def export( Raises: VersionNotSupportedError: When the server is older than the first release with the export endpoint. + SchemaNamespaceNotFoundError: When a namespace does not exist on the branch or cannot be exported. + URLNotFoundError: When the server returns a 404 that does not name a namespace. ApiError: When the server returns any other error, with the messages the server returned. """ @@ -881,6 +906,8 @@ def export( Raises: VersionNotSupportedError: When the server is older than the first release with the export endpoint. + SchemaNamespaceNotFoundError: When a namespace does not exist on the branch or cannot be exported. + URLNotFoundError: When the server returns a 404 that does not name a namespace. ApiError: When the server returns any other error, with the messages the server returned. """ diff --git a/tests/fixtures/error_catalogue/public_names.json b/tests/fixtures/error_catalogue/public_names.json index ac5a2d102..47f5f32d5 100644 --- a/tests/fixtures/error_catalogue/public_names.json +++ b/tests/fixtures/error_catalogue/public_names.json @@ -34,6 +34,7 @@ "RateLimitError", "RepositoryFileNotFoundError", "ResourceNotDefinedError", + "SchemaNamespaceNotFoundError", "SchemaNotFoundError", "ServerNotReachableError", "ServerNotResponsiveError", diff --git a/tests/unit/ctl/schema/test_schema.py b/tests/unit/ctl/schema/test_schema.py index 8c86a2306..29ad68eb8 100644 --- a/tests/unit/ctl/schema/test_schema.py +++ b/tests/unit/ctl/schema/test_schema.py @@ -510,3 +510,63 @@ def test_schema_export_error_response(httpx_mock: HTTPXMock, tmp_path: Path, cas if case.name != "older-server": assert SCHEMA_EXPORT_MIN_INFRAHUB_VERSION not in output assert not directory.exists() + + +NAMESPACE_EXPORT_URL = "http://mock/api/schema/export?branch=main&namespaces=Locaton&namespaces=Core&mode=BRIEF" + + +def test_schema_export_prints_each_namespace_the_server_cannot_export(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response( + method="GET", + url=NAMESPACE_EXPORT_URL, + status_code=404, + json={ + "data": None, + "errors": [ + { + "message": "The namespace 'Locaton' does not exist on the branch 'main'", + "extensions": {"namespace": "Locaton", "code": 404}, + }, + { + "message": "The namespace 'Core' is reserved for Infrahub and cannot be exported", + "extensions": {"namespace": "Core", "code": 404}, + }, + ], + }, + ) + directory = tmp_path / "export" + + result = runner.invoke( + app, + ["schema", "export", "--directory", str(directory), "--namespaces", "Locaton", "--namespaces", "Core"], + ) + + assert result.exit_code == 1 + assert remove_ansi_color(result.stdout).splitlines() == [ + "Error: The namespace 'Locaton' does not exist on the branch 'main'", + "Error: The namespace 'Core' is reserved for Infrahub and cannot be exported", + ] + assert not directory.exists() + + +def test_schema_export_reports_a_404_that_names_no_namespace_as_an_unknown_url( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response( + method="GET", + url=EXPORT_URL, + status_code=404, + json={ + "data": None, + "errors": [ + {"message": "The requested endpoint /api/schema/export does not exist", "extensions": {"code": 404}} + ], + }, + ) + directory = tmp_path / "export" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory)]) + + assert result.exit_code == 1 + assert remove_ansi_color(result.stdout.replace("\n", "")) == f"Error: `{EXPORT_URL}` not found." + assert not directory.exists() diff --git a/tests/unit/sdk/test_schema_export.py b/tests/unit/sdk/test_schema_export.py index 2ce3283e4..c85d59b49 100644 --- a/tests/unit/sdk/test_schema_export.py +++ b/tests/unit/sdk/test_schema_export.py @@ -6,7 +6,12 @@ import pytest -from infrahub_sdk.exceptions import ApiError, VersionNotSupportedError +from infrahub_sdk.exceptions import ( + ApiError, + SchemaNamespaceNotFoundError, + URLNotFoundError, + VersionNotSupportedError, +) from infrahub_sdk.schema import ( SCHEMA_EXPORT_MIN_INFRAHUB_VERSION, SchemaExportDocument, @@ -177,3 +182,69 @@ async def test_export_reports_other_errors_as_returned( assert not isinstance(exc_info.value, VersionNotSupportedError) assert SCHEMA_EXPORT_MIN_INFRAHUB_VERSION not in str(exc_info.value) assert exc_info.value.http_status == case.status_code + + +NAMESPACE_EXPORT_URL = "http://mock/api/schema/export?branch=main&namespaces=Locaton&namespaces=Core&mode=BRIEF" +LOCATON_ERROR = { + "message": "The namespace 'Locaton' does not exist on the branch 'main'", + "extensions": {"namespace": "Locaton", "code": 404}, +} +CORE_ERROR = { + "message": "The namespace 'Core' is reserved for Infrahub and cannot be exported", + "extensions": {"namespace": "Core", "code": 404}, +} +UNKNOWN_ENDPOINT_ERROR = { + "message": "The requested endpoint /api/schema/export does not exist", + "extensions": {"code": 404}, +} + + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_names_each_namespace_the_server_cannot_export( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", + url=NAMESPACE_EXPORT_URL, + status_code=404, + json={"data": None, "errors": [LOCATON_ERROR, CORE_ERROR]}, + ) + + with pytest.raises( + SchemaNamespaceNotFoundError, + match=( + r"^The namespace 'Locaton' does not exist on the branch 'main'; " + r"The namespace 'Core' is reserved for Infrahub and cannot be exported$" + ), + ) as exc_info: + await _export(clients, client_type, branch="main", namespaces=["Locaton", "Core"]) + + assert exc_info.value.namespaces == ["Locaton", "Core"] + assert exc_info.value.messages == [LOCATON_ERROR["message"], CORE_ERROR["message"]] + assert exc_info.value.http_status == 404 + + +@dataclass +class NotFoundCase: + name: str + body: dict[str, Any] + + +NOT_FOUND_CASES = [ + NotFoundCase(name="fastapi-default", body={"detail": "Not Found"}), + NotFoundCase(name="infrahub-unknown-endpoint", body={"data": None, "errors": [UNKNOWN_ENDPOINT_ERROR]}), + NotFoundCase( + name="one-error-without-namespace", body={"data": None, "errors": [LOCATON_ERROR, UNKNOWN_ENDPOINT_ERROR]} + ), +] + + +@pytest.mark.parametrize("client_type", client_types) +@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in NOT_FOUND_CASES]) +async def test_export_reports_a_404_that_names_no_namespace_as_an_unknown_url( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str, case: NotFoundCase +) -> None: + httpx_mock.add_response(method="GET", url=NAMESPACE_EXPORT_URL, status_code=404, json=case.body) + + with pytest.raises(URLNotFoundError, match=f"^`{re.escape(NAMESPACE_EXPORT_URL)}` not found.$"): + await _export(clients, client_type, branch="main", namespaces=["Locaton", "Core"]) From 90f49d420d0082b581bb1cf01748c932c5ef2475 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Fri, 27 Nov 2026 09:42:49 +0000 Subject: [PATCH 09/21] fix(schema): report schema export errors with the SDK's own exceptions [IFC-3669] - An unknown branch raises BranchNotFoundError again, as the export did before it used the server endpoint. - A document with a value this SDK version cannot read raises InvalidResponseError instead of a pydantic ValidationError, and infrahubctl prints it, and a JsonDecodeError, without a traceback. - SchemaNamespaceNotFoundError and VersionNotSupportedError survive pickle and copy. - A namespace error without a text message is named in a fallback message, so the CLI never prints an empty error. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-document.changed.md | 2 +- infrahub_sdk/ctl/schema.py | 17 +++- infrahub_sdk/exceptions/base.py | 6 ++ infrahub_sdk/schema/__init__.py | 40 +++++++-- tests/unit/sdk/test_schema_export.py | 85 ++++++++++++++++++++ 5 files changed, 139 insertions(+), 11 deletions(-) diff --git a/changelog/+schema-export-document.changed.md b/changelog/+schema-export-document.changed.md index c6ff4a388..241c97a28 100644 --- a/changelog/+schema-export-document.changed.md +++ b/changelog/+schema-export-document.changed.md @@ -1 +1 @@ -`InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits a `SchemaExportDocument` into one document per namespace. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. When `namespaces` names a namespace that does not exist on the branch, or a namespace reserved for Infrahub such as `Core`, they raise the new `SchemaNamespaceNotFoundError`, with one message for each such namespace. +`InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits a `SchemaExportDocument` into one document per namespace. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. When `namespaces` names a namespace that does not exist on the branch, or a namespace reserved for Infrahub such as `Core`, they raise the new `SchemaNamespaceNotFoundError`, with one message for each such namespace. When the document holds a value this SDK version cannot read, such as an attribute kind added in a later Infrahub release, they raise `InvalidResponseError`. diff --git a/infrahub_sdk/ctl/schema.py b/infrahub_sdk/ctl/schema.py index 0665c993e..9b4765497 100644 --- a/infrahub_sdk/ctl/schema.py +++ b/infrahub_sdk/ctl/schema.py @@ -17,7 +17,14 @@ from ..async_typer import AsyncTyper from ..ctl.client import initialize_client from ..ctl.utils import catch_exception, init_logging -from ..exceptions import ApiError, SchemaNamespaceNotFoundError, URLNotFoundError, VersionNotSupportedError +from ..exceptions import ( + ApiError, + InvalidResponseError, + JsonDecodeError, + SchemaNamespaceNotFoundError, + URLNotFoundError, + VersionNotSupportedError, +) from ..queries import SCHEMA_HASH_SYNC_STATUS from ..schema import ( NodeSchemaAPI, @@ -325,7 +332,13 @@ async def export( for message in exc.messages: console.print(f"[red]Error: {escape(message)}") raise typer.Exit(code=1) from exc - except (VersionNotSupportedError, URLNotFoundError, ApiError) as exc: + except ( + VersionNotSupportedError, + URLNotFoundError, + JsonDecodeError, + InvalidResponseError, + ApiError, + ) as exc: console.print(f"[red]Error: {escape(str(exc))}") raise typer.Exit(code=1) from exc diff --git a/infrahub_sdk/exceptions/base.py b/infrahub_sdk/exceptions/base.py index f67badad4..bf3082bc8 100644 --- a/infrahub_sdk/exceptions/base.py +++ b/infrahub_sdk/exceptions/base.py @@ -215,6 +215,9 @@ def __init__(self, namespaces: list[str], messages: list[str]) -> None: self.messages = messages super().__init__("; ".join(messages)) + def __reduce__(self) -> tuple[Any, ...]: + return (_rebuild_error, (type(self), self.args, self.__dict__)) + class VersionNotSupportedError(Error): """Raised when a feature is used against an Infrahub server version that does not support it.""" @@ -225,6 +228,9 @@ def __init__(self, feature: str, required_version: str) -> None: self.message = f"{feature} requires Infrahub {required_version} or later." super().__init__(self.message) + def __reduce__(self) -> tuple[Any, ...]: + return (_rebuild_error, (type(self), self.args, self.__dict__)) + class BranchNotFoundPayload(Protocol): """The fields a server-reported BRANCH_NOT_FOUND carries.""" diff --git a/infrahub_sdk/schema/__init__.py b/infrahub_sdk/schema/__init__.py index 20b12b8c4..921f77e31 100644 --- a/infrahub_sdk/schema/__init__.py +++ b/infrahub_sdk/schema/__init__.py @@ -12,6 +12,7 @@ import httpx from pydantic import BaseModel, Field +from pydantic import ValidationError as PydanticValidationError from ..exceptions import ( ApiError, @@ -162,16 +163,18 @@ def _export_url(self, branch: str, namespaces: list[str] | None, mode: SchemaExp return f"{self.client.address}/api/schema/export?{urlencode(url_parts)}" @staticmethod - def _parse_export_response(response: httpx.Response) -> SchemaExportDocument: + def _parse_export_response(response: httpx.Response, branch: str) -> SchemaExportDocument: """Read the schema export endpoint's response. Raises: + BranchNotFoundError: When the branch does not exist on the server. VersionNotSupportedError: When the server is older than the first release with the endpoint. SchemaNamespaceNotFoundError: When a requested namespace does not exist on the branch or cannot be exported, with one message per namespace. URLNotFoundError: When the server returns a 404 that does not name a namespace. ApiError: When the server returns any other error, with the messages the server returned. JsonDecodeError: When the server returns a body that is not JSON. + InvalidResponseError: When the document holds a value this SDK version cannot read. """ if response.status_code == httpx.codes.OK: @@ -183,6 +186,16 @@ def _parse_export_response(response: httpx.Response) -> SchemaExportDocument: content=response.text, url=str(response.url), ) from exc + except PydanticValidationError as exc: + raise InvalidResponseError( + f"The schema export from {response.url} holds a value this version of the SDK cannot read; " + f"use an SDK version that matches the Infrahub server. {exc}" + ) from exc + + if response.status_code == httpx.codes.BAD_REQUEST: + raise BranchNotFoundError( + identifier=branch, message=f"The requested branch was not found on the server [{branch}]" + ) try: body = response.json() @@ -198,12 +211,17 @@ def _parse_export_response(response: httpx.Response) -> SchemaExportDocument: ) if response.status_code == httpx.codes.NOT_FOUND: - namespaces = [_error_namespace(error) for error in error_list] - if not error_list or None in namespaces: + named_errors = [(error, _error_namespace(error)) for error in error_list] + if not named_errors or any(namespace is None for _, namespace in named_errors): raise URLNotFoundError(url=str(response.url)) - namespace_error = SchemaNamespaceNotFoundError( - namespaces=[namespace for namespace in namespaces if namespace is not None], messages=messages - ) + namespaces = [namespace for _, namespace in named_errors if namespace is not None] + namespace_messages = [ + message + if isinstance(message := error.get("message"), str) + else f"The namespace '{namespace}' cannot be exported" + for error, namespace in named_errors + ] + namespace_error = SchemaNamespaceNotFoundError(namespaces=namespaces, messages=namespace_messages) namespace_error.http_status = response.status_code namespace_error.errors = error_list raise namespace_error @@ -627,15 +645,18 @@ async def export( The server's document, holding only the fields the server returned. Raises: + BranchNotFoundError: When the branch does not exist on the server. VersionNotSupportedError: When the server is older than the first release with the export endpoint. SchemaNamespaceNotFoundError: When a namespace does not exist on the branch or cannot be exported. URLNotFoundError: When the server returns a 404 that does not name a namespace. ApiError: When the server returns any other error, with the messages the server returned. + JsonDecodeError: When the server returns a body that is not JSON. + InvalidResponseError: When the document holds a value this SDK version cannot read. """ branch = branch or self.client.default_branch response = await self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) - return self._parse_export_response(response=response) + return self._parse_export_response(response=response, branch=branch) async def get_graphql_schema(self, branch: str | None = None) -> str: """Get the GraphQL schema as a string. @@ -905,15 +926,18 @@ def export( The server's document, holding only the fields the server returned. Raises: + BranchNotFoundError: When the branch does not exist on the server. VersionNotSupportedError: When the server is older than the first release with the export endpoint. SchemaNamespaceNotFoundError: When a namespace does not exist on the branch or cannot be exported. URLNotFoundError: When the server returns a 404 that does not name a namespace. ApiError: When the server returns any other error, with the messages the server returned. + JsonDecodeError: When the server returns a body that is not JSON. + InvalidResponseError: When the document holds a value this SDK version cannot read. """ branch = branch or self.client.default_branch response = self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) - return self._parse_export_response(response=response) + return self._parse_export_response(response=response, branch=branch) def get_graphql_schema(self, branch: str | None = None) -> str: """Get the GraphQL schema as a string. diff --git a/tests/unit/sdk/test_schema_export.py b/tests/unit/sdk/test_schema_export.py index c85d59b49..54132d3b5 100644 --- a/tests/unit/sdk/test_schema_export.py +++ b/tests/unit/sdk/test_schema_export.py @@ -1,5 +1,7 @@ from __future__ import annotations +import copy +import pickle # noqa: S403 - round-tripping our own exception, no untrusted data involved import re from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -8,6 +10,8 @@ from infrahub_sdk.exceptions import ( ApiError, + BranchNotFoundError, + InvalidResponseError, SchemaNamespaceNotFoundError, URLNotFoundError, VersionNotSupportedError, @@ -20,6 +24,8 @@ ) if TYPE_CHECKING: + from collections.abc import Callable + from pytest_httpx import HTTPXMock from tests.unit.sdk.conftest import BothClients @@ -248,3 +254,82 @@ async def test_export_reports_a_404_that_names_no_namespace_as_an_unknown_url( with pytest.raises(URLNotFoundError, match=f"^`{re.escape(NAMESPACE_EXPORT_URL)}` not found.$"): await _export(clients, client_type, branch="main", namespaces=["Locaton", "Core"]) + + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_names_a_namespace_whose_error_has_no_message( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", + url=NAMESPACE_EXPORT_URL, + status_code=404, + json={"data": None, "errors": [{"message": None, "extensions": {"namespace": "Locaton", "code": 404}}]}, + ) + + with pytest.raises(SchemaNamespaceNotFoundError, match=r"^The namespace 'Locaton' cannot be exported$"): + await _export(clients, client_type, branch="main", namespaces=["Locaton", "Core"]) + + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_of_an_unknown_branch_raises_branch_not_found( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=nope&mode=BRIEF", + status_code=400, + json={"data": None, "errors": [{"message": "Branch: nope not found.", "extensions": {"code": 400}}]}, + ) + + with pytest.raises(BranchNotFoundError, match=r"^The requested branch was not found on the server \[nope\]$"): + await _export(clients, client_type, branch="nope") + + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_with_a_value_the_sdk_cannot_read_raises_invalid_response( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + response = { + **EXPORT_RESPONSE, + "generics": [], + "nodes": [{"name": "Device", "namespace": "Network", "attributes": [{"name": "size", "kind": "Decimal"}]}], + } + httpx_mock.add_response(method="GET", url="http://mock/api/schema/export?branch=main&mode=BRIEF", json=response) + + with pytest.raises( + InvalidResponseError, + match=r"^The schema export from http://mock/api/schema/export\?branch=main&mode=BRIEF holds a value this " + r"version of the SDK cannot read; use an SDK version that matches the Infrahub server\. ", + ): + await _export(clients, client_type, branch="main") + + +SERIALISATION_ROUND_TRIPS = { + "pickle": lambda exc: pickle.loads(pickle.dumps(exc)), # noqa: S301 + "deepcopy": copy.deepcopy, + "copy": copy.copy, +} + + +@pytest.mark.parametrize("round_trip", [pytest.param(fn, id=name) for name, fn in SERIALISATION_ROUND_TRIPS.items()]) +def test_export_errors_survive_serialisation(round_trip: Callable[[Exception], Exception]) -> None: + namespace_error = SchemaNamespaceNotFoundError(namespaces=["Locaton"], messages=[LOCATON_ERROR["message"]]) + namespace_error.http_status = 404 + version_error = VersionNotSupportedError(feature="The schema export", required_version="1.13.0") + + restored_namespace_error = round_trip(namespace_error) + restored_version_error = round_trip(version_error) + + assert isinstance(restored_namespace_error, SchemaNamespaceNotFoundError) + assert ( + restored_namespace_error.namespaces, + restored_namespace_error.messages, + restored_namespace_error.http_status, + str(restored_namespace_error), + ) == (["Locaton"], [LOCATON_ERROR["message"]], 404, LOCATON_ERROR["message"]) + assert isinstance(restored_version_error, VersionNotSupportedError) + assert (restored_version_error.required_version, str(restored_version_error)) == ( + "1.13.0", + "The schema export requires Infrahub 1.13.0 or later.", + ) From 58ced06aa31dba388b3eff0a57007948e4a7c8e8 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Fri, 27 Nov 2026 11:03:15 +0000 Subject: [PATCH 10/21] fix(schema): report a rejected login and print bracketed paths in the schema export [IFC-3669] - A 401 or 403 from the export endpoint raises AuthenticationError, as the GraphQL paths do, and infrahubctl prints it as an authentication failure. - infrahubctl escapes the directory, file and namespace names it prints, so a name with square brackets no longer fails a finished export. - The command help mentions the --single-file layout. Co-Authored-By: Claude Opus 5.5 --- docs/docs/infrahubctl/infrahubctl-schema.mdx | 2 +- infrahub_sdk/ctl/schema.py | 11 +++++---- infrahub_sdk/schema/__init__.py | 7 +++++- tests/unit/ctl/schema/test_schema.py | 25 ++++++++++++++++++++ tests/unit/sdk/test_schema_export.py | 17 +++++++++++++ 5 files changed, 56 insertions(+), 6 deletions(-) diff --git a/docs/docs/infrahubctl/infrahubctl-schema.mdx b/docs/docs/infrahubctl/infrahubctl-schema.mdx index 1ffd7afd0..7d7c4295e 100644 --- a/docs/docs/infrahubctl/infrahubctl-schema.mdx +++ b/docs/docs/infrahubctl/infrahubctl-schema.mdx @@ -68,7 +68,7 @@ $ infrahubctl schema check [OPTIONS] SCHEMAS... ## `infrahubctl schema export` -Export the schema from Infrahub as YAML files, one per namespace. +Export the schema from Infrahub as YAML files: one per namespace, or one file with --single-file. **Usage**: diff --git a/infrahub_sdk/ctl/schema.py b/infrahub_sdk/ctl/schema.py index 9b4765497..7332b554d 100644 --- a/infrahub_sdk/ctl/schema.py +++ b/infrahub_sdk/ctl/schema.py @@ -19,6 +19,7 @@ from ..ctl.utils import catch_exception, init_logging from ..exceptions import ( ApiError, + AuthenticationError, InvalidResponseError, JsonDecodeError, SchemaNamespaceNotFoundError, @@ -322,7 +323,7 @@ async def export( debug: bool = False, _: str = CONFIG_PARAM, ) -> None: - """Export the schema from Infrahub as YAML files, one per namespace.""" + """Export the schema from Infrahub as YAML files: one per namespace, or one file with --single-file.""" init_logging(debug=debug) client = initialize_client() @@ -339,6 +340,8 @@ async def export( InvalidResponseError, ApiError, ) as exc: + if isinstance(exc, AuthenticationError): + raise console.print(f"[red]Error: {escape(str(exc))}") raise typer.Exit(code=1) from exc @@ -351,14 +354,14 @@ async def export( if single_file: output_file = directory / "schema.yml" _write_schema_file(document=document, output_file=output_file) - console.print(f"[green] Exported schema to {output_file}") + console.print(f"[green] Exported schema to {escape(str(output_file))}") else: for ns, namespace_document in sorted(split_by_namespace(document).items()): output_file = directory / f"{ns.lower()}.yml" _write_schema_file(document=namespace_document, output_file=output_file) - console.print(f"[green] Exported namespace '{ns}' to {output_file}") + console.print(f"[green] Exported namespace '{escape(ns)}' to {escape(str(output_file))}") - console.print(f"[green] Schema exported to {directory}") + console.print(f"[green] Schema exported to {escape(str(directory))}") def _write_schema_file(document: SchemaExportDocument, output_file: Path) -> None: diff --git a/infrahub_sdk/schema/__init__.py b/infrahub_sdk/schema/__init__.py index 921f77e31..6a0733ca8 100644 --- a/infrahub_sdk/schema/__init__.py +++ b/infrahub_sdk/schema/__init__.py @@ -24,6 +24,7 @@ URLNotFoundError, ValidationError, VersionNotSupportedError, + authentication_error_from_response, ) from ..graphql import Mutation from ..protocols_base import CoreNodeBase @@ -167,6 +168,7 @@ def _parse_export_response(response: httpx.Response, branch: str) -> SchemaExpor """Read the schema export endpoint's response. Raises: + AuthenticationError: When the server rejects the credentials (401) or the permissions (403). BranchNotFoundError: When the branch does not exist on the server. VersionNotSupportedError: When the server is older than the first release with the endpoint. SchemaNamespaceNotFoundError: When a requested namespace does not exist on the branch or cannot be @@ -176,7 +178,7 @@ def _parse_export_response(response: httpx.Response, branch: str) -> SchemaExpor JsonDecodeError: When the server returns a body that is not JSON. InvalidResponseError: When the document holds a value this SDK version cannot read. - """ + """ # noqa: DOC501 # raises via a factory, whose name ruff reads as the exception's if response.status_code == httpx.codes.OK: try: return SchemaExportDocument.model_validate(response.json()) @@ -192,6 +194,9 @@ def _parse_export_response(response: httpx.Response, branch: str) -> SchemaExpor f"use an SDK version that matches the Infrahub server. {exc}" ) from exc + if response.status_code in {httpx.codes.UNAUTHORIZED, httpx.codes.FORBIDDEN}: + raise authentication_error_from_response(response=response) + if response.status_code == httpx.codes.BAD_REQUEST: raise BranchNotFoundError( identifier=branch, message=f"The requested branch was not found on the server [{branch}]" diff --git a/tests/unit/ctl/schema/test_schema.py b/tests/unit/ctl/schema/test_schema.py index 29ad68eb8..21f0bf721 100644 --- a/tests/unit/ctl/schema/test_schema.py +++ b/tests/unit/ctl/schema/test_schema.py @@ -570,3 +570,28 @@ def test_schema_export_reports_a_404_that_names_no_namespace_as_an_unknown_url( assert result.exit_code == 1 assert remove_ansi_color(result.stdout.replace("\n", "")) == f"Error: `{EXPORT_URL}` not found." assert not directory.exists() + + +def test_schema_export_reports_a_401_as_an_authentication_failure(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response( + method="GET", + url=EXPORT_URL, + status_code=401, + json={"data": None, "errors": [{"message": "Authentication is required", "extensions": {"code": 401}}]}, + ) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path / "export")]) + + assert result.exit_code == 1 + assert remove_ansi_color(result.stdout.replace("\n", "")) == "Authentication failure: Authentication is required" + + +def test_schema_export_prints_a_directory_name_with_brackets(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE) + directory = tmp_path / "a[/b]" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory), "--single-file"]) + + assert result.exit_code == 0, result.stdout + assert remove_ansi_color(result.stdout).splitlines()[-1] == f" Schema exported to {directory}" + assert (directory / "schema.yml").exists() diff --git a/tests/unit/sdk/test_schema_export.py b/tests/unit/sdk/test_schema_export.py index 54132d3b5..9b23e001a 100644 --- a/tests/unit/sdk/test_schema_export.py +++ b/tests/unit/sdk/test_schema_export.py @@ -10,6 +10,7 @@ from infrahub_sdk.exceptions import ( ApiError, + AuthenticationError, BranchNotFoundError, InvalidResponseError, SchemaNamespaceNotFoundError, @@ -305,6 +306,22 @@ async def test_export_with_a_value_the_sdk_cannot_read_raises_invalid_response( await _export(clients, client_type, branch="main") +@pytest.mark.parametrize("client_type", client_types) +@pytest.mark.parametrize("status_code", [401, 403]) +async def test_export_rejected_for_the_credentials_raises_authentication_error( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str, status_code: int +) -> None: + httpx_mock.add_response( + method="GET", + url="http://mock/api/schema/export?branch=main&mode=BRIEF", + status_code=status_code, + json={"data": None, "errors": [{"message": "Authentication is required", "extensions": {"code": status_code}}]}, + ) + + with pytest.raises(AuthenticationError, match=r"^Authentication is required$"): + await _export(clients, client_type, branch="main") + + SERIALISATION_ROUND_TRIPS = { "pickle": lambda exc: pickle.loads(pickle.dumps(exc)), # noqa: S301 "deepcopy": copy.deepcopy, From efeebb7118d7230d9bb13d0931f0f8d3490d33d1 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Fri, 27 Nov 2026 15:41:24 +0000 Subject: [PATCH 11/21] fix(schema): write every field the server returns in the schema export files [IFC-3669] infrahubctl schema export wrote its files from the SDK write models, which drop the fields they do not declare. With an SDK older than the server, a field that a later Infrahub release adds was left out of the files with no message, and a load of the files lost it. The CLI now checks the response as before, then writes the JSON body the server returned. split_by_namespace takes and returns dicts and copies every top-level field to each namespace document. InfrahubSchema.export still returns a SchemaExportDocument. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-document.changed.md | 2 +- changelog/+schema-export-endpoint.changed.md | 1 + infrahub_sdk/ctl/schema.py | 12 +++--- infrahub_sdk/schema/__init__.py | 33 ++++++++++++++++ infrahub_sdk/schema/export.py | 39 ++++++++----------- tests/unit/ctl/schema/test_schema.py | 41 ++++++++++++++++++++ tests/unit/sdk/test_schema_export.py | 28 +++++++------ 7 files changed, 116 insertions(+), 40 deletions(-) diff --git a/changelog/+schema-export-document.changed.md b/changelog/+schema-export-document.changed.md index 241c97a28..4545e4a82 100644 --- a/changelog/+schema-export-document.changed.md +++ b/changelog/+schema-export-document.changed.md @@ -1 +1 @@ -`InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits a `SchemaExportDocument` into one document per namespace. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. When `namespaces` names a namespace that does not exist on the branch, or a namespace reserved for Infrahub such as `Core`, they raise the new `SchemaNamespaceNotFoundError`, with one message for each such namespace. When the document holds a value this SDK version cannot read, such as an attribute kind added in a later Infrahub release, they raise `InvalidResponseError`. +`InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits the export as the server returned it, a dict, into one dict per namespace, and copies every field it holds, including fields this SDK version does not know. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. When `namespaces` names a namespace that does not exist on the branch, or a namespace reserved for Infrahub such as `Core`, they raise the new `SchemaNamespaceNotFoundError`, with one message for each such namespace. When the document holds a value this SDK version cannot read, such as an attribute kind added in a later Infrahub release, they raise `InvalidResponseError`. diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md index bbcd85c64..5fc78227a 100644 --- a/changelog/+schema-export-endpoint.changed.md +++ b/changelog/+schema-export-endpoint.changed.md @@ -9,5 +9,6 @@ - On a `Text` or `TextArea` attribute, `regex`, `min_length` and `max_length` are written under `parameters`. On a `List` attribute, `regex` is written under `parameters`, and `min_length` and `max_length` stay at the top level. On an attribute of any other kind, these settings stay at the top level. - NumberPool `start_range` and `end_range` are written as one entry of `ranges`. - Each file has an `infrahub_version` field with the version of the Infrahub server that built it. +- The files hold every field the server returned, including fields that a later Infrahub release adds and this SDK version does not know. `--namespaces` with a namespace that does not exist on the branch, or with a namespace reserved for Infrahub such as `Core`, now prints an error for each such namespace and exits with code 1. diff --git a/infrahub_sdk/ctl/schema.py b/infrahub_sdk/ctl/schema.py index 7332b554d..bead953e0 100644 --- a/infrahub_sdk/ctl/schema.py +++ b/infrahub_sdk/ctl/schema.py @@ -29,12 +29,12 @@ from ..queries import SCHEMA_HASH_SYNC_STATUS from ..schema import ( NodeSchemaAPI, - SchemaExportDocument, SchemaExportMode, SchemaWarning, split_by_namespace, validate_schema, ) +from ..schema.export import EXPORT_ELEMENT_SECTIONS from ..yaml import SchemaFile from .parameters import CONFIG_PARAM from .schema_format import ( @@ -328,7 +328,8 @@ async def export( client = initialize_client() try: - document = await client.schema.export(branch=branch, namespaces=namespaces or None, mode=mode) + # Written as received, so the files keep the fields an older SDK version does not know. + document = await client.schema._export_payload(branch=branch, namespaces=namespaces or None, mode=mode) except SchemaNamespaceNotFoundError as exc: for message in exc.messages: console.print(f"[red]Error: {escape(message)}") @@ -345,7 +346,7 @@ async def export( console.print(f"[red]Error: {escape(str(exc))}") raise typer.Exit(code=1) from exc - if not document.nodes and not document.generics: + if not any(document.get(section) for section in EXPORT_ELEMENT_SECTIONS): console.print("[yellow]No user-defined schema found to export.") return @@ -364,9 +365,8 @@ async def export( console.print(f"[green] Schema exported to {escape(str(directory))}") -def _write_schema_file(document: SchemaExportDocument, output_file: Path) -> None: - # Only the fields the server returned are written, so a value it left out is not replaced by its default. - data = document.model_dump(mode="json", exclude_unset=True) +def _write_schema_file(document: dict[str, Any], output_file: Path) -> None: + data = dict(document) leading = {key: data.pop(key) for key in _EXPORT_LEADING_KEYS if key in data} output_file.write_text( yaml.dump({**leading, **data}, default_flow_style=False, sort_keys=False, allow_unicode=True), diff --git a/infrahub_sdk/schema/__init__.py b/infrahub_sdk/schema/__init__.py index 6a0733ca8..8b9f4979a 100644 --- a/infrahub_sdk/schema/__init__.py +++ b/infrahub_sdk/schema/__init__.py @@ -163,6 +163,17 @@ def _export_url(self, branch: str, namespaces: list[str] | None, mode: SchemaExp url_parts.append(("mode", SchemaExportMode(mode).value)) return f"{self.client.address}/api/schema/export?{urlencode(url_parts)}" + @classmethod + def _export_payload_from_response(cls, response: httpx.Response, branch: str) -> dict[str, Any]: + """Check the schema export endpoint's response, then return its JSON body with every field it holds. + + The write models of this SDK version drop the fields they do not declare, so the checked document cannot be + returned instead. + """ + cls._parse_export_response(response=response, branch=branch) + payload: dict[str, Any] = response.json() + return payload + @staticmethod def _parse_export_response(response: httpx.Response, branch: str) -> SchemaExportDocument: """Read the schema export endpoint's response. @@ -663,6 +674,17 @@ async def export( response = await self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) return self._parse_export_response(response=response, branch=branch) + async def _export_payload( + self, + branch: str | None = None, + namespaces: list[str] | None = None, + mode: SchemaExportMode = SchemaExportMode.BRIEF, + ) -> dict[str, Any]: + """Export the user-defined schema of a branch and return the server's document with every field it holds.""" + branch = branch or self.client.default_branch + response = await self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) + return self._export_payload_from_response(response=response, branch=branch) + async def get_graphql_schema(self, branch: str | None = None) -> str: """Get the GraphQL schema as a string. @@ -944,6 +966,17 @@ def export( response = self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) return self._parse_export_response(response=response, branch=branch) + def _export_payload( + self, + branch: str | None = None, + namespaces: list[str] | None = None, + mode: SchemaExportMode = SchemaExportMode.BRIEF, + ) -> dict[str, Any]: + """Export the user-defined schema of a branch and return the server's document with every field it holds.""" + branch = branch or self.client.default_branch + response = self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) + return self._export_payload_from_response(response=response, branch=branch) + def get_graphql_schema(self, branch: str | None = None) -> str: """Get the GraphQL schema as a string. diff --git a/infrahub_sdk/schema/export.py b/infrahub_sdk/schema/export.py index 8aefcc455..58a6d3f65 100644 --- a/infrahub_sdk/schema/export.py +++ b/infrahub_sdk/schema/export.py @@ -1,8 +1,14 @@ from __future__ import annotations from enum import Enum +from typing import TYPE_CHECKING, Any -from .generated.write import GenericSchemaWrite, InfrahubSchemaWrite, NodeSchemaWrite +from .generated.write import InfrahubSchemaWrite + +if TYPE_CHECKING: + from collections.abc import Mapping + +EXPORT_ELEMENT_SECTIONS = ("generics", "nodes") class SchemaExportMode(str, Enum): @@ -19,27 +25,16 @@ class SchemaExportDocument(InfrahubSchemaWrite): infrahub_version: str -def split_by_namespace(document: SchemaExportDocument) -> dict[str, SchemaExportDocument]: - """Split an exported schema into one document per namespace, keeping the order of the input. +def split_by_namespace(document: Mapping[str, Any]) -> dict[str, dict[str, Any]]: + """Split an exported schema, as the server returned it, into one document per namespace. - A document only sets `generics` or `nodes` when its namespace has some, so a dump with - `exclude_unset=True` leaves out an empty list. + Namespaces keep the order of the input. Each document holds every other top-level field of the input, and holds `generics` or `nodes` only + when its namespace has some. Fields are copied as they are, including fields this SDK version does not know. """ - generics: dict[str, list[GenericSchemaWrite]] = {} - nodes: dict[str, list[NodeSchemaWrite]] = {} - for generic in document.generics: - generics.setdefault(generic.namespace, []).append(generic) - for node in document.nodes: - nodes.setdefault(node.namespace, []).append(node) - - documents: dict[str, SchemaExportDocument] = {} - for namespace in [*generics, *nodes]: - if namespace in documents: - continue - namespace_document = SchemaExportDocument(version=document.version, infrahub_version=document.infrahub_version) - if namespace in generics: - namespace_document.generics = generics[namespace] - if namespace in nodes: - namespace_document.nodes = nodes[namespace] - documents[namespace] = namespace_document + shared = {key: value for key, value in document.items() if key not in EXPORT_ELEMENT_SECTIONS} + documents: dict[str, dict[str, Any]] = {} + for section in EXPORT_ELEMENT_SECTIONS: + for element in document.get(section, []): + namespace_document = documents.setdefault(element["namespace"], dict(shared)) + namespace_document.setdefault(section, []).append(element) return documents diff --git a/tests/unit/ctl/schema/test_schema.py b/tests/unit/ctl/schema/test_schema.py index 21f0bf721..59fa7fe4e 100644 --- a/tests/unit/ctl/schema/test_schema.py +++ b/tests/unit/ctl/schema/test_schema.py @@ -405,6 +405,47 @@ def test_schema_export_single_file_writes_the_endpoint_document(httpx_mock: HTTP assert schema == EXPORT_RESPONSE +UNKNOWN_NODE = { + "name": "Rack", + "namespace": "Location", + "unknown_node_setting": "kept", + "attributes": [{"name": "name", "kind": "Text", "unknown_attribute_setting": True}], + "relationships": [{"name": "site", "peer": "LocationSite", "unknown_relationship_setting": 1}], +} + +EXPORT_RESPONSE_WITH_UNKNOWN_FIELDS: dict[str, Any] = { + **EXPORT_RESPONSE, + "unknown_document_setting": "kept", + "nodes": [*EXPORT_RESPONSE["nodes"], UNKNOWN_NODE], +} + + +def test_schema_export_single_file_keeps_fields_this_sdk_does_not_know(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE_WITH_UNKNOWN_FIELDS) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path), "--single-file"]) + + assert result.exit_code == 0, result.stdout + assert _read_yaml(tmp_path / "schema.yml") == EXPORT_RESPONSE_WITH_UNKNOWN_FIELDS + + +def test_schema_export_per_namespace_keeps_fields_this_sdk_does_not_know(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE_WITH_UNKNOWN_FIELDS) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path)]) + + assert result.exit_code == 0, result.stdout + location = _read_yaml(tmp_path / "location.yml") + assert list(location) == ["version", "infrahub_version", "nodes", "unknown_document_setting"] + assert location == { + "version": "1.0", + "infrahub_version": "1.13.0", + "nodes": [EXPORT_RESPONSE["nodes"][1], UNKNOWN_NODE], + "unknown_document_setting": "kept", + } + assert _read_yaml(tmp_path / "network.yml")["unknown_document_setting"] == "kept" + + def test_schema_export_writes_no_default_for_a_field_the_response_left_out( httpx_mock: HTTPXMock, tmp_path: Path ) -> None: diff --git a/tests/unit/sdk/test_schema_export.py b/tests/unit/sdk/test_schema_export.py index 9b23e001a..9410c1e1d 100644 --- a/tests/unit/sdk/test_schema_export.py +++ b/tests/unit/sdk/test_schema_export.py @@ -119,25 +119,31 @@ async def test_export_sends_branch_namespaces_and_mode( def test_split_by_namespace_keeps_versions_and_input_order() -> None: - document = SchemaExportDocument.model_validate(EXPORT_RESPONSE) - - documents = split_by_namespace(document) + documents = split_by_namespace(EXPORT_RESPONSE) assert list(documents) == ["Network", "Location"] - for namespace_document in documents.values(): - assert isinstance(namespace_document, SchemaExportDocument) - assert namespace_document.version == "1.0" - assert namespace_document.infrahub_version == "1.13.0" - assert [generic.name for generic in documents["Network"].generics] == ["Interface"] - assert [node.name for node in documents["Network"].nodes] == ["Device", "PhysicalInterface"] - assert [node.name for node in documents["Location"].nodes] == ["Site"] - assert documents["Location"].model_dump(mode="json", exclude_unset=True) == { + assert documents["Network"] == { + "version": "1.0", + "infrahub_version": "1.13.0", + "generics": EXPORT_RESPONSE["generics"], + "nodes": [EXPORT_RESPONSE["nodes"][0], EXPORT_RESPONSE["nodes"][2]], + } + assert documents["Location"] == { "version": "1.0", "infrahub_version": "1.13.0", "nodes": [EXPORT_RESPONSE["nodes"][1]], } +def test_split_by_namespace_copies_every_other_top_level_field() -> None: + documents = split_by_namespace({**EXPORT_RESPONSE, "unknown_document_setting": "kept"}) + + assert [namespace_document["unknown_document_setting"] for namespace_document in documents.values()] == [ + "kept", + "kept", + ] + + @pytest.mark.parametrize("client_type", client_types) async def test_export_names_the_release_on_an_older_server( httpx_mock: HTTPXMock, clients: BothClients, client_type: str From 32c3902c915bd01d2cf78547d32df72ce894111f Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Mon, 30 Nov 2026 06:42:11 +0000 Subject: [PATCH 12/21] fix(schema): accept the exported document in split_by_namespace and read the export body once [IFC-3669] split_by_namespace takes the SchemaExportDocument that export returns again, as well as the JSON body as a dict; since the CLI started writing the raw body it raised AttributeError on the document. The export response is parsed once and returns both the raw body and the checked document. The sync _export_payload is now tested, and the generated contract.py docstring describes KEEP_IN_EXPORT_FIELDS. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-document.changed.md | 2 +- infrahub_sdk/schema/__init__.py | 31 +++++++++----------- infrahub_sdk/schema/export.py | 12 +++++--- infrahub_sdk/schema/generated/contract.py | 14 +++++---- tests/unit/sdk/test_schema_export.py | 21 +++++++++++++ 5 files changed, 53 insertions(+), 27 deletions(-) diff --git a/changelog/+schema-export-document.changed.md b/changelog/+schema-export-document.changed.md index 4545e4a82..f2d42d8c4 100644 --- a/changelog/+schema-export-document.changed.md +++ b/changelog/+schema-export-document.changed.md @@ -1 +1 @@ -`InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits the export as the server returned it, a dict, into one dict per namespace, and copies every field it holds, including fields this SDK version does not know. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. When `namespaces` names a namespace that does not exist on the branch, or a namespace reserved for Infrahub such as `Core`, they raise the new `SchemaNamespaceNotFoundError`, with one message for each such namespace. When the document holds a value this SDK version cannot read, such as an attribute kind added in a later Infrahub release, they raise `InvalidResponseError`. +`InfrahubSchema.export` and `InfrahubSchemaSync.export` now return the document that Infrahub builds, as a `SchemaExportDocument`, instead of a `SchemaExport`. They take a `mode` argument, `BRIEF` by default. `split_by_namespace` splits an export, either the `SchemaExportDocument` that `export` returns or the JSON body as a dict, into one dict per namespace. From a dict, it copies every field, including fields this SDK version does not know. Against an Infrahub server without the schema export endpoint, they raise `VersionNotSupportedError` with the first Infrahub release that has it. When `namespaces` names a namespace that does not exist on the branch, or a namespace reserved for Infrahub such as `Core`, they raise the new `SchemaNamespaceNotFoundError`, with one message for each such namespace. When the document holds a value this SDK version cannot read, such as an attribute kind added in a later Infrahub release, they raise `InvalidResponseError`. diff --git a/infrahub_sdk/schema/__init__.py b/infrahub_sdk/schema/__init__.py index 8b9f4979a..95dbc89f5 100644 --- a/infrahub_sdk/schema/__init__.py +++ b/infrahub_sdk/schema/__init__.py @@ -163,21 +163,13 @@ def _export_url(self, branch: str, namespaces: list[str] | None, mode: SchemaExp url_parts.append(("mode", SchemaExportMode(mode).value)) return f"{self.client.address}/api/schema/export?{urlencode(url_parts)}" - @classmethod - def _export_payload_from_response(cls, response: httpx.Response, branch: str) -> dict[str, Any]: - """Check the schema export endpoint's response, then return its JSON body with every field it holds. - - The write models of this SDK version drop the fields they do not declare, so the checked document cannot be - returned instead. - """ - cls._parse_export_response(response=response, branch=branch) - payload: dict[str, Any] = response.json() - return payload - @staticmethod - def _parse_export_response(response: httpx.Response, branch: str) -> SchemaExportDocument: + def _parse_export_response(response: httpx.Response, branch: str) -> tuple[dict[str, Any], SchemaExportDocument]: """Read the schema export endpoint's response. + Returns the JSON body as the server sent it and the document checked against the write models. The write + models of this SDK version drop the fields they do not declare, so only the JSON body holds every field. + Raises: AuthenticationError: When the server rejects the credentials (401) or the permissions (403). BranchNotFoundError: When the branch does not exist on the server. @@ -192,7 +184,8 @@ def _parse_export_response(response: httpx.Response, branch: str) -> SchemaExpor """ # noqa: DOC501 # raises via a factory, whose name ruff reads as the exception's if response.status_code == httpx.codes.OK: try: - return SchemaExportDocument.model_validate(response.json()) + payload = response.json() + return payload, SchemaExportDocument.model_validate(payload) except json.decoder.JSONDecodeError as exc: raise JsonDecodeError( message=f"Invalid schema export response received from the server at {response.url}: {response.text} [{response.status_code}]", @@ -672,7 +665,8 @@ async def export( """ branch = branch or self.client.default_branch response = await self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) - return self._parse_export_response(response=response, branch=branch) + _, document = self._parse_export_response(response=response, branch=branch) + return document async def _export_payload( self, @@ -683,7 +677,8 @@ async def _export_payload( """Export the user-defined schema of a branch and return the server's document with every field it holds.""" branch = branch or self.client.default_branch response = await self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) - return self._export_payload_from_response(response=response, branch=branch) + payload, _ = self._parse_export_response(response=response, branch=branch) + return payload async def get_graphql_schema(self, branch: str | None = None) -> str: """Get the GraphQL schema as a string. @@ -964,7 +959,8 @@ def export( """ branch = branch or self.client.default_branch response = self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) - return self._parse_export_response(response=response, branch=branch) + _, document = self._parse_export_response(response=response, branch=branch) + return document def _export_payload( self, @@ -975,7 +971,8 @@ def _export_payload( """Export the user-defined schema of a branch and return the server's document with every field it holds.""" branch = branch or self.client.default_branch response = self.client._get(url=self._export_url(branch=branch, namespaces=namespaces, mode=mode)) - return self._export_payload_from_response(response=response, branch=branch) + payload, _ = self._parse_export_response(response=response, branch=branch) + return payload def get_graphql_schema(self, branch: str | None = None) -> str: """Get the GraphQL schema as a string. diff --git a/infrahub_sdk/schema/export.py b/infrahub_sdk/schema/export.py index 58a6d3f65..39d6d7147 100644 --- a/infrahub_sdk/schema/export.py +++ b/infrahub_sdk/schema/export.py @@ -25,12 +25,16 @@ class SchemaExportDocument(InfrahubSchemaWrite): infrahub_version: str -def split_by_namespace(document: Mapping[str, Any]) -> dict[str, dict[str, Any]]: - """Split an exported schema, as the server returned it, into one document per namespace. +def split_by_namespace(document: SchemaExportDocument | Mapping[str, Any]) -> dict[str, dict[str, Any]]: + """Split an exported schema into one document per namespace. - Namespaces keep the order of the input. Each document holds every other top-level field of the input, and holds `generics` or `nodes` only - when its namespace has some. Fields are copied as they are, including fields this SDK version does not know. + Namespaces keep the order of the input. Each document holds every other top-level field of the input, such as + `version` and `infrahub_version`, and holds `generics` or `nodes` only when its namespace has some. A mapping is + copied as it is, including fields this SDK version does not know; a `SchemaExportDocument` holds only the fields + the server set. The documents share the elements and the top-level values with the input instead of copying them. """ + if isinstance(document, SchemaExportDocument): + document = document.model_dump(mode="json", exclude_unset=True) shared = {key: value for key, value in document.items() if key not in EXPORT_ELEMENT_SECTIONS} documents: dict[str, dict[str, Any]] = {} for section in EXPORT_ELEMENT_SECTIONS: diff --git a/infrahub_sdk/schema/generated/contract.py b/infrahub_sdk/schema/generated/contract.py index b1e527d5b..3284e8316 100644 --- a/infrahub_sdk/schema/generated/contract.py +++ b/infrahub_sdk/schema/generated/contract.py @@ -1,12 +1,16 @@ # Generated by "invoke backend.generate", do not edit directly -"""Read-only fields of the write contract, keyed by generated write class name. +"""Field tables of the write contract, keyed by generated write class name. -A field listed here is one the contract knows at that location but the user may not set: -a field the read API returns, the bookkeeping a schema dumped from the internal models +`READ_ONLY_FIELDS` lists the fields the contract knows at that location but the user may not +set: a field the read API returns, the bookkeeping a schema dumped from the internal models carries, or a field belonging to a sibling variant of a discriminated union. Submitting one is reported as a warning and the value is dropped, where an extra field that is not listed -is an error. Each entry already includes what the class inherits, so a lookup is by class -name alone. +is an error. + +`KEEP_IN_EXPORT_FIELDS` lists the optional fields a schema export keeps unless they hold +their default. + +Each entry already includes what the class inherits, so a lookup is by class name alone. """ READ_ONLY_FIELDS: dict[str, frozenset[str]] = { diff --git a/tests/unit/sdk/test_schema_export.py b/tests/unit/sdk/test_schema_export.py index 9410c1e1d..8bd0af2d4 100644 --- a/tests/unit/sdk/test_schema_export.py +++ b/tests/unit/sdk/test_schema_export.py @@ -356,3 +356,24 @@ def test_export_errors_survive_serialisation(round_trip: Callable[[Exception], E "1.13.0", "The schema export requires Infrahub 1.13.0 or later.", ) + + +def test_split_by_namespace_splits_the_document_export_returns() -> None: + documents = split_by_namespace(SchemaExportDocument.model_validate(EXPORT_RESPONSE)) + + assert documents == split_by_namespace(EXPORT_RESPONSE) + + +@pytest.mark.parametrize("client_type", client_types) +async def test_export_payload_returns_every_field_the_server_returned( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + response = {**EXPORT_RESPONSE, "unknown_document_setting": "kept"} + httpx_mock.add_response(method="GET", url="http://mock/api/schema/export?branch=main&mode=FULL", json=response) + + if client_type == "standard": + payload = await clients.standard.schema._export_payload(branch="main", mode=SchemaExportMode.FULL) + else: + payload = clients.sync.schema._export_payload(branch="main", mode=SchemaExportMode.FULL) + + assert payload == response From 9cb60d540a35f2524955e74631cc2fc5b8e59bd8 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Mon, 30 Nov 2026 14:07:13 +0000 Subject: [PATCH 13/21] fix(ctl): write each value of an exported schema file on one line [IFC-3669] PyYAML wraps values longer than 80 characters, which split Jinja2 templates over several lines in the files `infrahubctl schema export` writes. The files loaded back to the same values, but read as broken. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-endpoint.changed.md | 1 + infrahub_sdk/ctl/schema.py | 11 +++++++- tests/unit/ctl/schema/test_schema.py | 28 ++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md index 5fc78227a..6bf954170 100644 --- a/changelog/+schema-export-endpoint.changed.md +++ b/changelog/+schema-export-endpoint.changed.md @@ -10,5 +10,6 @@ - NumberPool `start_range` and `end_range` are written as one entry of `ranges`. - Each file has an `infrahub_version` field with the version of the Infrahub server that built it. - The files hold every field the server returned, including fields that a later Infrahub release adds and this SDK version does not know. +- Each value is written on one line, however long it is. Earlier versions split a value longer than about 80 characters, such as a Jinja2 template, over several lines. `--namespaces` with a namespace that does not exist on the branch, or with a namespace reserved for Infrahub such as `Core`, now prints an error for each such namespace and exits with code 1. diff --git a/infrahub_sdk/ctl/schema.py b/infrahub_sdk/ctl/schema.py index bead953e0..493e05002 100644 --- a/infrahub_sdk/ctl/schema.py +++ b/infrahub_sdk/ctl/schema.py @@ -2,6 +2,7 @@ import asyncio import difflib +import sys import time from datetime import datetime, timezone from enum import Enum @@ -49,6 +50,8 @@ SchemaContainer = Literal["nodes", "generics", "relationships"] _EXPORT_LEADING_KEYS = ("version", "infrahub_version", "generics", "nodes") +_EXPORT_LINE_WIDTH = sys.maxsize +"""Line width for the exported files, so that a long value such as a Jinja2 template stays on one line.""" app = AsyncTyper() console = Console() @@ -369,7 +372,13 @@ def _write_schema_file(document: dict[str, Any], output_file: Path) -> None: data = dict(document) leading = {key: data.pop(key) for key in _EXPORT_LEADING_KEYS if key in data} output_file.write_text( - yaml.dump({**leading, **data}, default_flow_style=False, sort_keys=False, allow_unicode=True), + yaml.dump( + {**leading, **data}, + default_flow_style=False, + sort_keys=False, + allow_unicode=True, + width=_EXPORT_LINE_WIDTH, + ), encoding="utf-8", ) diff --git a/tests/unit/ctl/schema/test_schema.py b/tests/unit/ctl/schema/test_schema.py index 59fa7fe4e..ed84b5d5f 100644 --- a/tests/unit/ctl/schema/test_schema.py +++ b/tests/unit/ctl/schema/test_schema.py @@ -488,6 +488,34 @@ def test_schema_export_sends_mode_and_namespaces(httpx_mock: HTTPXMock, tmp_path assert len(httpx_mock.get_requests()) == 1 +LONG_TEMPLATE = ( + "https://example.com/{{ name__value|lower }}-{{ profession__name__value|upper }}/{{ race__name__value }}/" +) + + +def test_schema_export_writes_each_long_value_on_one_line(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + site = { + "name": "Site", + "namespace": "Location", + "attributes": [ + { + "name": "url", + "kind": "URL", + "read_only": True, + "computed_attribute": {"kind": "Jinja2", "jinja2_template": LONG_TEMPLATE}, + } + ], + } + httpx_mock.add_response(method="GET", url=EXPORT_URL, json={**EXPORT_RESPONSE, "nodes": [site]}) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path), "--single-file"]) + + assert result.exit_code == 0, result.stdout + lines = [line.strip() for line in (tmp_path / "schema.yml").read_text(encoding="utf-8").splitlines()] + assert f"jinja2_template: {LONG_TEMPLATE}" in lines + assert _read_yaml(tmp_path / "schema.yml")["nodes"] == [site] + + def test_schema_export_empty_document(httpx_mock: HTTPXMock, tmp_path: Path) -> None: httpx_mock.add_response( method="GET", From 7f4a90d7672b5ef30b4290dfe189d990486b0ed2 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Tue, 1 Dec 2026 09:57:43 +0000 Subject: [PATCH 14/21] feat(ctl): write exported schema files in the layout of schema format [IFC-3669] infrahubctl schema export now passes each file through format_schema_text, the function behind infrahubctl schema format, before it writes it. The files get the yaml-language-server header and the key order of that command, and the function raises FormatError rather than write a file whose values changed. schema format now writes infrahub_version directly after version, and has no line-width limit, so a long value such as a Jinja2 template stays on one line in both commands. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-endpoint.changed.md | 3 ++ ...+schema-format-infrahub-version.changed.md | 1 + infrahub_sdk/ctl/schema.py | 25 ++++++++------- infrahub_sdk/ctl/schema_format.py | 7 ++-- tests/unit/ctl/schema/test_schema.py | 32 +++++++++++++++++++ tests/unit/ctl/test_schema_format.py | 8 +++++ 6 files changed, 61 insertions(+), 15 deletions(-) create mode 100644 changelog/+schema-format-infrahub-version.changed.md diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md index 6bf954170..daabe06ea 100644 --- a/changelog/+schema-export-endpoint.changed.md +++ b/changelog/+schema-export-endpoint.changed.md @@ -11,5 +11,8 @@ - Each file has an `infrahub_version` field with the version of the Infrahub server that built it. - The files hold every field the server returned, including fields that a later Infrahub release adds and this SDK version does not know. - Each value is written on one line, however long it is. Earlier versions split a value longer than about 80 characters, such as a Jinja2 template, over several lines. +- The files are laid out as `infrahubctl schema format` lays out a schema file: they start with the `yaml-language-server` header, and the keys of each node, generic, attribute, relationship and dropdown choice are in the order that command uses. +- The deprecated `default_filter` of a node or generic is no longer written. A `FULL` export still writes it. +- A dropdown choice has no `state` field. `--namespaces` with a namespace that does not exist on the branch, or with a namespace reserved for Infrahub such as `Core`, now prints an error for each such namespace and exits with code 1. diff --git a/changelog/+schema-format-infrahub-version.changed.md b/changelog/+schema-format-infrahub-version.changed.md new file mode 100644 index 000000000..06ab62e84 --- /dev/null +++ b/changelog/+schema-format-infrahub-version.changed.md @@ -0,0 +1 @@ +`infrahubctl schema format` writes the `infrahub_version` field of a schema file directly after `version`. diff --git a/infrahub_sdk/ctl/schema.py b/infrahub_sdk/ctl/schema.py index 493e05002..bfc2e2b41 100644 --- a/infrahub_sdk/ctl/schema.py +++ b/infrahub_sdk/ctl/schema.py @@ -49,7 +49,6 @@ SchemaContainer = Literal["nodes", "generics", "relationships"] -_EXPORT_LEADING_KEYS = ("version", "infrahub_version", "generics", "nodes") _EXPORT_LINE_WIDTH = sys.maxsize """Line width for the exported files, so that a long value such as a Jinja2 template stays on one line.""" @@ -369,18 +368,20 @@ async def export( def _write_schema_file(document: dict[str, Any], output_file: Path) -> None: - data = dict(document) - leading = {key: data.pop(key) for key in _EXPORT_LEADING_KEYS if key in data} - output_file.write_text( - yaml.dump( - {**leading, **data}, - default_flow_style=False, - sort_keys=False, - allow_unicode=True, - width=_EXPORT_LINE_WIDTH, - ), - encoding="utf-8", + """Write an exported document in the layout that `infrahubctl schema format` gives a schema file. + + Raises: + FormatError: When formatting would change a value of the document. + + """ + text = yaml.dump( + document, + default_flow_style=False, + sort_keys=False, + allow_unicode=True, + width=_EXPORT_LINE_WIDTH, ) + output_file.write_text(format_schema_text(text), encoding="utf-8") @app.command(name="list") diff --git a/infrahub_sdk/ctl/schema_format.py b/infrahub_sdk/ctl/schema_format.py index 7dd0a6c7b..2985f8765 100644 --- a/infrahub_sdk/ctl/schema_format.py +++ b/infrahub_sdk/ctl/schema_format.py @@ -32,6 +32,7 @@ import json import re +import sys from dataclasses import dataclass from io import StringIO from typing import Any @@ -73,7 +74,7 @@ # Canonical key orders. Each pair is (leading keys, trailing keys); any key not # listed is preserved in its original position between the two groups so the # formatter never drops data. -FILE_ORDER = ["version", "generics", "nodes", "extensions"] +FILE_ORDER = ["version", "infrahub_version", "generics", "nodes", "extensions"] NODE_ORDER = [ "name", @@ -205,9 +206,9 @@ def _build_yaml() -> YAML: # Match the schema-library layout: block sequences indented under their key # (`attributes:\n - name: ...`). yaml_handler.indent(mapping=2, sequence=4, offset=2) - # A very wide value keeps long scalars (descriptions, Jinja2 templates) on + # An unlimited width keeps long scalars (descriptions, Jinja2 templates) on # their original line instead of being re-wrapped. - yaml_handler.width = 4096 + yaml_handler.width = sys.maxsize return yaml_handler diff --git a/tests/unit/ctl/schema/test_schema.py b/tests/unit/ctl/schema/test_schema.py index ed84b5d5f..5eb24fa89 100644 --- a/tests/unit/ctl/schema/test_schema.py +++ b/tests/unit/ctl/schema/test_schema.py @@ -11,6 +11,7 @@ from typer.testing import CliRunner from infrahub_sdk.ctl.cli_commands import app +from infrahub_sdk.ctl.schema_format import SCHEMA_HEADER, format_schema_text from infrahub_sdk.schema import SCHEMA_EXPORT_MIN_INFRAHUB_VERSION, NodeSchemaAPI from tests.helpers.cli import remove_ansi_color @@ -516,6 +517,37 @@ def test_schema_export_writes_each_long_value_on_one_line(httpx_mock: HTTPXMock, assert _read_yaml(tmp_path / "schema.yml")["nodes"] == [site] +UNORDERED_EXPORT_RESPONSE: dict[str, Any] = { + "nodes": [ + { + "relationships": [{"optional": False, "cardinality": "one", "peer": "LocationSite", "name": "site"}], + "attributes": [{"unique": True, "kind": "Text", "name": "name"}], + "namespace": "Network", + "name": "Device", + }, + ], + "infrahub_version": "1.13.0", + "version": "1.0", +} + + +def test_schema_export_writes_files_that_schema_format_leaves_unchanged(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=UNORDERED_EXPORT_RESPONSE) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path)]) + + assert result.exit_code == 0, result.stdout + text = (tmp_path / "network.yml").read_text(encoding="utf-8") + assert text.startswith(SCHEMA_HEADER) + assert format_schema_text(text) == text + network = yaml.safe_load(text) + assert list(network) == ["version", "infrahub_version", "nodes"] + assert list(network["nodes"][0]) == ["name", "namespace", "attributes", "relationships"] + assert list(network["nodes"][0]["attributes"][0]) == ["name", "kind", "unique"] + assert list(network["nodes"][0]["relationships"][0]) == ["name", "peer", "cardinality", "optional"] + assert network == UNORDERED_EXPORT_RESPONSE + + def test_schema_export_empty_document(httpx_mock: HTTPXMock, tmp_path: Path) -> None: httpx_mock.add_response( method="GET", diff --git a/tests/unit/ctl/test_schema_format.py b/tests/unit/ctl/test_schema_format.py index b76cb725c..5f78e7832 100644 --- a/tests/unit/ctl/test_schema_format.py +++ b/tests/unit/ctl/test_schema_format.py @@ -72,6 +72,14 @@ def test_node_key_order_is_canonical() -> None: ] +def test_infrahub_version_follows_version() -> None: + raw = 'nodes:\n - name: Device\n namespace: Dcim\ninfrahub_version: "1.13.0"\nversion: "1.0"\n' + + text = format_schema_text(raw) + + assert _keys_of(text, []) == ["version", "infrahub_version", "nodes"] + + def test_attribute_relationship_and_choice_inner_order() -> None: text = format_schema_text(NODE_DOC) From 3dd712bf780bf0b501411cd501512fb5a9b19727 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Tue, 1 Dec 2026 10:07:05 +0000 Subject: [PATCH 15/21] docs(changelog): note that schema export files hold no state field [IFC-3669] The server now leaves out state on every node, generic, attribute, relationship and dropdown choice, in both modes. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-endpoint.changed.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md index daabe06ea..4ffad0a92 100644 --- a/changelog/+schema-export-endpoint.changed.md +++ b/changelog/+schema-export-endpoint.changed.md @@ -13,6 +13,6 @@ - Each value is written on one line, however long it is. Earlier versions split a value longer than about 80 characters, such as a Jinja2 template, over several lines. - The files are laid out as `infrahubctl schema format` lays out a schema file: they start with the `yaml-language-server` header, and the keys of each node, generic, attribute, relationship and dropdown choice are in the order that command uses. - The deprecated `default_filter` of a node or generic is no longer written. A `FULL` export still writes it. -- A dropdown choice has no `state` field. +- No `state` field is written on a node, generic, attribute, relationship or dropdown choice, in either mode. `--namespaces` with a namespace that does not exist on the branch, or with a namespace reserved for Infrahub such as `Core`, now prints an error for each such namespace and exits with code 1. From 0a5fd179b3fd08ff1ef761f3ddd09eda3e385687 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Tue, 1 Dec 2026 10:09:15 +0000 Subject: [PATCH 16/21] docs(ctl): describe the default and the behavior of schema export --directory [IFC-3669] The help text showed "(dynamic)" as the default. It now shows the name pattern of the default directory, and says that the command creates the directory and overwrites files with the same name. Co-Authored-By: Claude Opus 5.5 --- docs/docs/infrahubctl/infrahubctl-schema.mdx | 2 +- infrahub_sdk/ctl/schema.py | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/docs/infrahubctl/infrahubctl-schema.mdx b/docs/docs/infrahubctl/infrahubctl-schema.mdx index 7d7c4295e..1a0f9951d 100644 --- a/docs/docs/infrahubctl/infrahubctl-schema.mdx +++ b/docs/docs/infrahubctl/infrahubctl-schema.mdx @@ -78,7 +78,7 @@ $ infrahubctl schema export [OPTIONS] **Options**: -* `--directory PATH`: Directory path to store schema files [default: (dynamic)] +* `--directory PATH`: Directory to write the schema files to. Created if it does not exist; existing files with the same name are overwritten. [default: (./infrahub-schema-export-<YYYYMMDD-HHMMSS>)] * `--branch TEXT`: Branch from which to export the schema * `--namespaces TEXT`: Namespace(s) to export (default: all user-defined) * `--mode [BRIEF|FULL]`: BRIEF leaves out the values Infrahub derives when the schema is loaded; FULL writes every value [default: BRIEF] diff --git a/infrahub_sdk/ctl/schema.py b/infrahub_sdk/ctl/schema.py index bfc2e2b41..aca13df64 100644 --- a/infrahub_sdk/ctl/schema.py +++ b/infrahub_sdk/ctl/schema.py @@ -314,7 +314,11 @@ def _default_export_directory() -> Path: @app.command() @catch_exception(console=console) async def export( - directory: Path = typer.Option(_default_export_directory, help="Directory path to store schema files"), + directory: Path = typer.Option( + _default_export_directory, + show_default="./infrahub-schema-export-", + help="Directory to write the schema files to. Created if it does not exist; existing files with the same name are overwritten.", + ), branch: str = typer.Option(None, help="Branch from which to export the schema"), namespaces: list[str] = typer.Option([], help="Namespace(s) to export (default: all user-defined)"), mode: SchemaExportMode = typer.Option( From 07b7f64d16c435f8fea6165ecff0ea383e3734bb Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Tue, 1 Dec 2026 10:20:14 +0000 Subject: [PATCH 17/21] fix(ctl): write no partial schema export and keep scalar lists inline [IFC-3669] The export now renders every file before it writes any. When formatting a file would change a value, the command prints the error, writes no file and exits with code 1, instead of leaving the files of earlier namespaces behind with a traceback. A list that holds no mapping, such as human_friendly_id or uniqueness_constraints, is now written inline as [[device, name__value]]. With the indentation of schema format, block style wrote a nested list as "- - device", which is hard to read. The long-value tests now use values over 4096 characters, so they fail if the line-width limit comes back. The changelog fragments describe the --- marker, the inline lists, the error case and the width change of schema format. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-endpoint.changed.md | 2 +- ...+schema-format-infrahub-version.changed.md | 2 +- infrahub_sdk/ctl/schema.py | 53 +++++++++++++++---- tests/unit/ctl/schema/test_schema.py | 47 +++++++++++++++- tests/unit/ctl/test_schema_format.py | 9 ++++ 5 files changed, 98 insertions(+), 15 deletions(-) diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md index 4ffad0a92..6ae46c172 100644 --- a/changelog/+schema-export-endpoint.changed.md +++ b/changelog/+schema-export-endpoint.changed.md @@ -11,7 +11,7 @@ - Each file has an `infrahub_version` field with the version of the Infrahub server that built it. - The files hold every field the server returned, including fields that a later Infrahub release adds and this SDK version does not know. - Each value is written on one line, however long it is. Earlier versions split a value longer than about 80 characters, such as a Jinja2 template, over several lines. -- The files are laid out as `infrahubctl schema format` lays out a schema file: they start with the `yaml-language-server` header, and the keys of each node, generic, attribute, relationship and dropdown choice are in the order that command uses. +- The files are laid out as `infrahubctl schema format` lays out a schema file: they start with `---` and the `yaml-language-server` comment, and the keys of each node, generic, attribute, relationship and dropdown choice are in the order that command uses. A list that holds no mapping, such as `human_friendly_id` or `uniqueness_constraints`, is written on one line, as in `[[device, name__value]]`. When a file cannot be formatted without changing a value, the command writes no file, prints the error and exits with code 1. - The deprecated `default_filter` of a node or generic is no longer written. A `FULL` export still writes it. - No `state` field is written on a node, generic, attribute, relationship or dropdown choice, in either mode. diff --git a/changelog/+schema-format-infrahub-version.changed.md b/changelog/+schema-format-infrahub-version.changed.md index 06ab62e84..8170883d3 100644 --- a/changelog/+schema-format-infrahub-version.changed.md +++ b/changelog/+schema-format-infrahub-version.changed.md @@ -1 +1 @@ -`infrahubctl schema format` writes the `infrahub_version` field of a schema file directly after `version`. +`infrahubctl schema format` writes the `infrahub_version` field of a schema file directly after `version`. It no longer splits a value longer than 4096 characters over several lines, so such a value in an existing file is written on one line the next time you format the file. diff --git a/infrahub_sdk/ctl/schema.py b/infrahub_sdk/ctl/schema.py index aca13df64..2ab7419b7 100644 --- a/infrahub_sdk/ctl/schema.py +++ b/infrahub_sdk/ctl/schema.py @@ -52,6 +52,23 @@ _EXPORT_LINE_WIDTH = sys.maxsize """Line width for the exported files, so that a long value such as a Jinja2 template stays on one line.""" + +class _ExportDumper(yaml.SafeDumper): + """Writes a list that holds no mapping inline, as in `[[device, name__value]]`, as schema files usually do.""" + + +def _represent_export_list(dumper: yaml.SafeDumper, data: list[Any]) -> yaml.Node: + return dumper.represent_sequence("tag:yaml.org,2002:seq", data, flow_style=not _holds_mapping(data)) + + +def _holds_mapping(value: Any) -> bool: + if isinstance(value, dict): + return True + return isinstance(value, list) and any(_holds_mapping(item) for item in value) + + +_ExportDumper.add_representer(list, _represent_export_list) + app = AsyncTyper() console = Console() @@ -356,23 +373,36 @@ async def export( console.print("[yellow]No user-defined schema found to export.") return - directory.mkdir(parents=True, exist_ok=True) - if single_file: output_file = directory / "schema.yml" - _write_schema_file(document=document, output_file=output_file) - console.print(f"[green] Exported schema to {escape(str(output_file))}") + files = [(output_file, document, f"Exported schema to {escape(str(output_file))}")] else: - for ns, namespace_document in sorted(split_by_namespace(document).items()): - output_file = directory / f"{ns.lower()}.yml" - _write_schema_file(document=namespace_document, output_file=output_file) - console.print(f"[green] Exported namespace '{escape(ns)}' to {escape(str(output_file))}") + files = [ + ( + directory / f"{ns.lower()}.yml", + namespace_document, + f"Exported namespace '{escape(ns)}' to {escape(str(directory / f'{ns.lower()}.yml'))}", + ) + for ns, namespace_document in sorted(split_by_namespace(document).items()) + ] + + try: + # Every file is rendered before any is written, so a failure leaves no partial export behind. + rendered = [(output_file, _render_schema_file(content), message) for output_file, content, message in files] + except FormatError as exc: + console.print(f"[red]Error: {escape(str(exc))}") + raise typer.Exit(code=1) from exc + + directory.mkdir(parents=True, exist_ok=True) + for output_file, text, message in rendered: + output_file.write_text(text, encoding="utf-8") + console.print(f"[green] {message}") console.print(f"[green] Schema exported to {escape(str(directory))}") -def _write_schema_file(document: dict[str, Any], output_file: Path) -> None: - """Write an exported document in the layout that `infrahubctl schema format` gives a schema file. +def _render_schema_file(document: dict[str, Any]) -> str: + """Return an exported document as YAML in the layout that `infrahubctl schema format` gives a schema file. Raises: FormatError: When formatting would change a value of the document. @@ -380,12 +410,13 @@ def _write_schema_file(document: dict[str, Any], output_file: Path) -> None: """ text = yaml.dump( document, + Dumper=_ExportDumper, default_flow_style=False, sort_keys=False, allow_unicode=True, width=_EXPORT_LINE_WIDTH, ) - output_file.write_text(format_schema_text(text), encoding="utf-8") + return format_schema_text(text) @app.command(name="list") diff --git a/tests/unit/ctl/schema/test_schema.py b/tests/unit/ctl/schema/test_schema.py index 5eb24fa89..14ec55347 100644 --- a/tests/unit/ctl/schema/test_schema.py +++ b/tests/unit/ctl/schema/test_schema.py @@ -11,7 +11,7 @@ from typer.testing import CliRunner from infrahub_sdk.ctl.cli_commands import app -from infrahub_sdk.ctl.schema_format import SCHEMA_HEADER, format_schema_text +from infrahub_sdk.ctl.schema_format import SCHEMA_HEADER, FormatError, format_schema_text from infrahub_sdk.schema import SCHEMA_EXPORT_MIN_INFRAHUB_VERSION, NodeSchemaAPI from tests.helpers.cli import remove_ansi_color @@ -490,8 +490,9 @@ def test_schema_export_sends_mode_and_namespaces(httpx_mock: HTTPXMock, tmp_path LONG_TEMPLATE = ( - "https://example.com/{{ name__value|lower }}-{{ profession__name__value|upper }}/{{ race__name__value }}/" + "https://example.com/{{ name__value|lower }}-{{ profession__name__value|upper }}/{{ race__name__value }}/" * 50 ) +"""A value longer than the 4096 characters at which the YAML writers of the CLI used to split a line.""" def test_schema_export_writes_each_long_value_on_one_line(httpx_mock: HTTPXMock, tmp_path: Path) -> None: @@ -548,6 +549,48 @@ def test_schema_export_writes_files_that_schema_format_leaves_unchanged(httpx_mo assert network == UNORDERED_EXPORT_RESPONSE +def test_schema_export_writes_lists_without_mappings_inline(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + device = { + "name": "Device", + "namespace": "Network", + "inherit_from": ["NetworkEndpoint"], + "human_friendly_id": ["name__value"], + "uniqueness_constraints": [["site", "name__value"]], + "attributes": [{"name": "name", "kind": "Text"}], + } + httpx_mock.add_response(method="GET", url=EXPORT_URL, json={**EXPORT_RESPONSE, "generics": [], "nodes": [device]}) + + result = runner.invoke(app, ["schema", "export", "--directory", str(tmp_path), "--single-file"]) + + assert result.exit_code == 0, result.stdout + lines = [line.strip() for line in (tmp_path / "schema.yml").read_text(encoding="utf-8").splitlines()] + assert "inherit_from: [NetworkEndpoint]" in lines + assert "human_friendly_id: [name__value]" in lines + assert "uniqueness_constraints: [[site, name__value]]" in lines + assert "- name: name" in lines + assert _read_yaml(tmp_path / "schema.yml")["nodes"] == [device] + + +def test_schema_export_writes_no_file_when_a_file_cannot_be_formatted( + httpx_mock: HTTPXMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, json=EXPORT_RESPONSE) + + def format_all_but_network(text: str) -> str: + if "namespace: Network" in text: + raise FormatError("Formatting would change the schema content; aborting to avoid data loss.") + return format_schema_text(text) + + monkeypatch.setattr("infrahub_sdk.ctl.schema.format_schema_text", format_all_but_network) + directory = tmp_path / "export" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory)]) + + assert result.exit_code == 1 + assert "Error: Formatting would change the schema content; aborting to avoid data loss." in result.stdout + assert not directory.exists() + + def test_schema_export_empty_document(httpx_mock: HTTPXMock, tmp_path: Path) -> None: httpx_mock.add_response( method="GET", diff --git a/tests/unit/ctl/test_schema_format.py b/tests/unit/ctl/test_schema_format.py index 5f78e7832..6e4f9555a 100644 --- a/tests/unit/ctl/test_schema_format.py +++ b/tests/unit/ctl/test_schema_format.py @@ -72,6 +72,15 @@ def test_node_key_order_is_canonical() -> None: ] +def test_value_longer_than_4096_characters_stays_on_one_line() -> None: + template = "{{ name__value }}-" * 300 + raw = f'version: "1.0"\nnodes:\n - namespace: Dcim\n name: Device\n display_label: "{template}"\n' + + text = format_schema_text(raw) + + assert f'display_label: "{template}"' in [line.strip() for line in text.splitlines()] + + def test_infrahub_version_follows_version() -> None: raw = 'nodes:\n - name: Device\n namespace: Dcim\ninfrahub_version: "1.13.0"\nversion: "1.0"\n' From b969aa34cbbe4e27f44e1249f9f2c7671630c8c4 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Tue, 1 Dec 2026 11:41:59 +0000 Subject: [PATCH 18/21] test(schema): cover a schema export response whose body is not JSON [IFC-3669] A 200 response with a body that is not JSON, such as a proxy page, raises JsonDecodeError from export for both clients, and infrahubctl schema export prints the error, writes no file and exits with code 1. Co-Authored-By: Claude Opus 5.5 --- tests/unit/ctl/schema/test_schema.py | 11 +++++++++++ tests/unit/sdk/test_schema_export.py | 17 +++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/tests/unit/ctl/schema/test_schema.py b/tests/unit/ctl/schema/test_schema.py index 14ec55347..b4e10a361 100644 --- a/tests/unit/ctl/schema/test_schema.py +++ b/tests/unit/ctl/schema/test_schema.py @@ -591,6 +591,17 @@ def format_all_but_network(text: str) -> str: assert not directory.exists() +def test_schema_export_reports_a_body_that_is_not_json(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", url=EXPORT_URL, text="proxy page") + directory = tmp_path / "export" + + result = runner.invoke(app, ["schema", "export", "--directory", str(directory)]) + + assert result.exit_code == 1 + assert "Error: Invalid schema export response received from the server" in result.stdout + assert not directory.exists() + + def test_schema_export_empty_document(httpx_mock: HTTPXMock, tmp_path: Path) -> None: httpx_mock.add_response( method="GET", diff --git a/tests/unit/sdk/test_schema_export.py b/tests/unit/sdk/test_schema_export.py index 8bd0af2d4..8d763ffff 100644 --- a/tests/unit/sdk/test_schema_export.py +++ b/tests/unit/sdk/test_schema_export.py @@ -13,6 +13,7 @@ AuthenticationError, BranchNotFoundError, InvalidResponseError, + JsonDecodeError, SchemaNamespaceNotFoundError, URLNotFoundError, VersionNotSupportedError, @@ -312,6 +313,22 @@ async def test_export_with_a_value_the_sdk_cannot_read_raises_invalid_response( await _export(clients, client_type, branch="main") +@pytest.mark.parametrize("client_type", client_types) +async def test_export_with_a_body_that_is_not_json_raises_json_decode_error( + httpx_mock: HTTPXMock, clients: BothClients, client_type: str +) -> None: + httpx_mock.add_response( + method="GET", url="http://mock/api/schema/export?branch=main&mode=BRIEF", text="proxy page" + ) + + with pytest.raises( + JsonDecodeError, + match=r"^Invalid schema export response received from the server at " + r"http://mock/api/schema/export\?branch=main&mode=BRIEF: proxy page \[200\]$", + ): + await _export(clients, client_type, branch="main") + + @pytest.mark.parametrize("client_type", client_types) @pytest.mark.parametrize("status_code", [401, 403]) async def test_export_rejected_for_the_credentials_raises_authentication_error( From ee79914d6d618555f1ff09389a9aa9457a69bd4b Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Tue, 1 Dec 2026 13:13:20 +0000 Subject: [PATCH 19/21] fix(schema): keep the namespace order when nodes come before generics [IFC-3669] split_by_namespace went through generics before nodes whatever the order of the input, so a namespace that only had nodes moved behind the generics namespaces when the input listed nodes first. It now goes through the sections in the order of the input, as its docstring says. The changelog no longer says that every value is written on one line: a value that holds a line break still takes several lines. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-endpoint.changed.md | 2 +- infrahub_sdk/schema/export.py | 6 ++++-- tests/unit/sdk/test_schema_export.py | 12 ++++++++++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md index 6ae46c172..a87326349 100644 --- a/changelog/+schema-export-endpoint.changed.md +++ b/changelog/+schema-export-endpoint.changed.md @@ -10,7 +10,7 @@ - NumberPool `start_range` and `end_range` are written as one entry of `ranges`. - Each file has an `infrahub_version` field with the version of the Infrahub server that built it. - The files hold every field the server returned, including fields that a later Infrahub release adds and this SDK version does not know. -- Each value is written on one line, however long it is. Earlier versions split a value longer than about 80 characters, such as a Jinja2 template, over several lines. +- A value without a line break is written on one line, however long it is. Earlier versions split a value longer than about 80 characters, such as a Jinja2 template, over several lines. - The files are laid out as `infrahubctl schema format` lays out a schema file: they start with `---` and the `yaml-language-server` comment, and the keys of each node, generic, attribute, relationship and dropdown choice are in the order that command uses. A list that holds no mapping, such as `human_friendly_id` or `uniqueness_constraints`, is written on one line, as in `[[device, name__value]]`. When a file cannot be formatted without changing a value, the command writes no file, prints the error and exits with code 1. - The deprecated `default_filter` of a node or generic is no longer written. A `FULL` export still writes it. - No `state` field is written on a node, generic, attribute, relationship or dropdown choice, in either mode. diff --git a/infrahub_sdk/schema/export.py b/infrahub_sdk/schema/export.py index 39d6d7147..34dc8b9a4 100644 --- a/infrahub_sdk/schema/export.py +++ b/infrahub_sdk/schema/export.py @@ -37,8 +37,10 @@ def split_by_namespace(document: SchemaExportDocument | Mapping[str, Any]) -> di document = document.model_dump(mode="json", exclude_unset=True) shared = {key: value for key, value in document.items() if key not in EXPORT_ELEMENT_SECTIONS} documents: dict[str, dict[str, Any]] = {} - for section in EXPORT_ELEMENT_SECTIONS: - for element in document.get(section, []): + for section, elements in document.items(): + if section not in EXPORT_ELEMENT_SECTIONS: + continue + for element in elements: namespace_document = documents.setdefault(element["namespace"], dict(shared)) namespace_document.setdefault(section, []).append(element) return documents diff --git a/tests/unit/sdk/test_schema_export.py b/tests/unit/sdk/test_schema_export.py index 8d763ffff..fced7068f 100644 --- a/tests/unit/sdk/test_schema_export.py +++ b/tests/unit/sdk/test_schema_export.py @@ -136,6 +136,18 @@ def test_split_by_namespace_keeps_versions_and_input_order() -> None: } +def test_split_by_namespace_keeps_the_namespace_order_when_nodes_come_before_generics() -> None: + document = { + "version": "1.0", + "nodes": [{"name": "Site", "namespace": "Location"}], + "generics": [{"name": "Interface", "namespace": "Network"}], + } + + documents = split_by_namespace(document) + + assert list(documents) == ["Location", "Network"] + + def test_split_by_namespace_copies_every_other_top_level_field() -> None: documents = split_by_namespace({**EXPORT_RESPONSE, "unknown_document_setting": "kept"}) From 980d2b8f3c88b919d877be792f224eacde786b9d Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Tue, 1 Dec 2026 14:14:59 +0000 Subject: [PATCH 20/21] docs(schema): say a kept export field is left out when it holds its default [IFC-3669] The comment on KEEP_IN_EXPORT_FIELDS said the export writes every value of a marked field, but the export leaves out a marked field that holds its default. Regenerated from the Infrahub template. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/schema/generated/contract.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/infrahub_sdk/schema/generated/contract.py b/infrahub_sdk/schema/generated/contract.py index 3284e8316..469abbcb3 100644 --- a/infrahub_sdk/schema/generated/contract.py +++ b/infrahub_sdk/schema/generated/contract.py @@ -40,7 +40,7 @@ } # Optional fields a schema export keeps unless they hold their default, keyed the same way: a -# shortened export without them fails validation, so the export writes every value. +# shortened export without them fails validation. KEEP_IN_EXPORT_FIELDS: dict[str, frozenset[str]] = { "AttributeSchemaBaseWrite": frozenset({"choices", "read_only", "unique"}), "GenericAttributeWrite": frozenset({"choices", "read_only", "unique"}), From 4980fc50048f2d2ce3a0e5efbddab370f7ef8eb7 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Wed, 2 Dec 2026 07:39:28 +0000 Subject: [PATCH 21/21] docs(changelog): say which generated-kind relationships the export now writes [IFC-3669] Earlier versions left out every relationship of kind Group, Profile or Hierarchy, including the ones the schema owner defined, and wrote the generated object_template relationship. The server export writes a relationship of these kinds that the schema owner defined, and writes one that matches a generated relationship only when it differs from it. Co-Authored-By: Claude Opus 5.5 --- changelog/+schema-export-endpoint.changed.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog/+schema-export-endpoint.changed.md b/changelog/+schema-export-endpoint.changed.md index a87326349..5cde72d24 100644 --- a/changelog/+schema-export-endpoint.changed.md +++ b/changelog/+schema-export-endpoint.changed.md @@ -5,7 +5,7 @@ - When an attribute has `unique: true`, the `human_friendly_id` and `uniqueness_constraints` that Infrahub derives from it are left out, and `unique` is written. - The relationship `identifier`, `cardinality` and `optional`, and the attribute `read_only` and `choices`, are written when they differ from their default value. - `IpamNamespace` is no longer written. -- The `object_template` relationship that Infrahub generates is no longer written. +- A relationship of kind `Group`, `Profile`, `Hierarchy` or `Template` that you defined is now written. A relationship with the kind, name and identifier of one that Infrahub generates, such as `member_of_groups` or `object_template`, is written only when it differs from the relationship Infrahub generates. Earlier versions left out every relationship of kind `Group`, `Profile` or `Hierarchy`, and wrote the `object_template` relationship that Infrahub generates. - On a `Text` or `TextArea` attribute, `regex`, `min_length` and `max_length` are written under `parameters`. On a `List` attribute, `regex` is written under `parameters`, and `min_length` and `max_length` stay at the top level. On an attribute of any other kind, these settings stay at the top level. - NumberPool `start_range` and `end_range` are written as one entry of `ranges`. - Each file has an `infrahub_version` field with the version of the Infrahub server that built it.