Skip to content

feat: export the schema through the Infrahub export endpoint [IFC-3669] - #1554

Merged
ogenstad merged 21 commits into
infrahub-developfrom
po-ifc-3669-schema-export-cli
Dec 2, 2026
Merged

ogenstad merged 21 commits into
infrahub-developfrom
po-ifc-3669-schema-export-cli

Conversation

@ogenstad

@ogenstad ogenstad commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Why

infrahubctl schema export wrote values Infrahub generated and elements the schema owner did not define, so the file did not load into another instance without editing. The export rules were written by hand in the SDK and fell behind the schema model (spec).

Infrahub 1.13.0 adds GET /api/schema/export, which builds the export on the server (opsmill/infrahub#11772). This pull request makes the SDK and infrahubctl schema export use that endpoint and removes the client-side export rules.

Jira: IFC-3669, part of IFC-2964.

Breaking changes to the public API

The SDK AGENTS.md lists changes to public API signatures under "Ask first". The feature owner accepted these on 2026-11-27, and the changelog fragments list them:

  • Removed from infrahub_sdk.schema, with no deprecation period: schema_to_export_dict, RESTRICTED_NAMESPACES, NamespaceExport and SchemaExport (changelog/+schema-export-client-rules.removed.md).
  • New return type: InfrahubSchema.export and InfrahubSchemaSync.export return a SchemaExportDocument instead of a SchemaExport (changelog/+schema-export-document.changed.md).
  • Needs a newer server: against an Infrahub server without the endpoint, export and infrahubctl schema export raise VersionNotSupportedError with the message that Infrahub 1.13.0 or later is required. Before, they exported on the client.
  • Different files: with the default BRIEF mode, infrahubctl schema export writes files that differ from earlier versions. changelog/+schema-export-endpoint.changed.md lists each difference.

What changed

Behavior:

  • export calls GET /api/schema/export with branch, namespaces and a new mode argument (SchemaExportMode.BRIEF by default, or FULL), and returns the server's document as a SchemaExportDocument. This model is a subclass of InfrahubSchemaWrite with a required infrahub_version.

  • infrahubctl schema export has two new options:

    • --mode BRIEF|FULL;
    • --single-file, which writes all namespaces to schema.yml.

    Without --single-file, it writes one file per namespace, as before.

  • The CLI writes the JSON body the server returned, after the SDK has checked it, instead of the SDK models. The files therefore keep a field that a later Infrahub release adds and this SDK version does not know. split_by_namespace accepts the dict body or the SchemaExportDocument that export returns, and returns one dict per namespace.

  • The CLI writes a value without a line break 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 CLI passes each file through format_schema_text, the function behind infrahubctl schema format, before it writes the file:

    • the file starts with --- and the yaml-language-server comment;
    • the keys of each node, generic, attribute, relationship and dropdown choice are in the order of schema format;
    • a list that holds no mapping is written on one line, such as uniqueness_constraints: [[device, name__value]].

    The CLI renders every file before it writes any. When formatting a file would change a value, it writes no file, prints the error and exits with code 1.

  • infrahubctl schema format writes infrahub_version directly after version, and no longer splits a value longer than 4096 characters.

  • The --directory help text shows the default name pattern, ./infrahub-schema-export-<YYYYMMDD-HHMMSS>, and says that the command creates the directory and overwrites files with the same name.

  • Errors of the export are raised as SDK exceptions:

    • 401 or 403: AuthenticationError;
    • 400: BranchNotFoundError;
    • the 422 an older server returns: VersionNotSupportedError;
    • a 404 whose errors each name a namespace in extensions.namespace: the new SchemaNamespaceNotFoundError, with one message per namespace;
    • any other 404: URLNotFoundError;
    • a document this SDK version cannot read: InvalidResponseError;
    • any other error: ApiError.

    The CLI prints one Error: line per namespace and exits with code 1.

  • InfrahubSchemaWrite accepts an infrahub_version field, so validate_schema and infrahubctl schema load accept an exported file.

  • KEEP_IN_EXPORT_FIELDS in the generated contract.py lists the fields a BRIEF export keeps. Infrahub's uv run invoke backend.generate writes it.

What stayed the same: infrahubctl schema load and the other schema commands. export in Python still returns the model, which drops fields this SDK version does not know; only the CLI keeps them.

How to review

  • infrahub_sdk/schema/__init__.py: _parse_export_response, which maps the responses to exceptions, and _export_payload, which the CLI uses.
  • infrahub_sdk/schema/export.py and the export command in infrahub_sdk/ctl/schema.py, including _render_schema_file and _ExportDumper.
  • FILE_ORDER and the line width in infrahub_sdk/ctl/schema_format.py.
  • infrahub_sdk/schema/generated/contract.py and write.py are generated from Infrahub.
  • The tests mock the endpoint's responses with httpx_mock. There is no integration test against a running server yet.

Impact & rollout

  • Backward compatibility: breaking, see above. infrahubctl schema export needs Infrahub 1.13.0 or later.
  • Deployment notes: merge before the opsmill/infrahub pull request. That pull request then moves its python_sdk pointer to this branch's merge commit.

Checklist

  • Tests added/updated
  • Changelog entry added (uv run towncrier create ...)
  • External docs updated: docs/docs/infrahubctl/infrahubctl-schema.mdx is regenerated, and the user guide is docs/docs/schema/export.mdx in opsmill/infrahub
  • Internal .md docs updated (internal knowledge and AI code tools knowledge)

🤖 Generated with Claude Code

ogenstad and others added 11 commits November 26, 2026 14:35
…port 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 <noreply@anthropic.com>
…C-3669]

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s [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 <noreply@anthropic.com>
…FC-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 <noreply@anthropic.com>
…nt [IFC-3669]

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… 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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
…s [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 <noreply@anthropic.com>
… 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 <noreply@anthropic.com>
…t 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 <noreply@anthropic.com>
@github-actions github-actions Bot added the type/documentation Improvements or additions to documentation label Nov 27, 2026
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Deploying infrahub-sdk-python with  Cloudflare Pages  Cloudflare Pages

Latest commit: 4980fc5
Status: ✅  Deploy successful!
Preview URL: https://b60ffc39.infrahub-sdk-python.pages.dev
Branch Preview URL: https://po-ifc-3669-schema-export-cl.infrahub-sdk-python.pages.dev

View logs

@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.63946% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
infrahub_sdk/schema/__init__.py 97.05% 2 Missing ⚠️
@@                 Coverage Diff                  @@
##           infrahub-develop    #1554      +/-   ##
====================================================
+ Coverage             87.92%   88.03%   +0.11%     
====================================================
  Files                   157      157              
  Lines                 15853    15734     -119     
  Branches               2162     2115      -47     
====================================================
- Hits                  13938    13852      -86     
+ Misses                 1336     1320      -16     
+ Partials                579      562      -17     
Flag Coverage Δ
integration-tests 42.85% <8.84%> (+0.10%) ⬆️
python-3.10 63.23% <79.59%> (+0.56%) ⬆️
python-3.11 63.25% <79.59%> (+0.58%) ⬆️
python-3.12 63.23% <79.59%> (+0.58%) ⬆️
python-3.13 63.23% <79.59%> (+0.56%) ⬆️
python-3.14 63.25% <79.59%> (+0.58%) ⬆️
python-3.15 63.23% <79.59%> (+0.56%) ⬆️
python-filler-3.12 23.00% <19.04%> (-0.58%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
infrahub_sdk/ctl/schema.py 80.06% <100.00%> (+7.54%) ⬆️
infrahub_sdk/ctl/schema_format.py 97.56% <100.00%> (+0.01%) ⬆️
infrahub_sdk/exceptions/__init__.py 100.00% <ø> (ø)
infrahub_sdk/exceptions/base.py 95.68% <100.00%> (+0.15%) ⬆️
infrahub_sdk/schema/export.py 100.00% <100.00%> (+17.64%) ⬆️
infrahub_sdk/schema/generated/contract.py 100.00% <100.00%> (ø)
infrahub_sdk/schema/generated/write.py 99.40% <100.00%> (-0.17%) ⬇️
infrahub_sdk/schema/__init__.py 74.70% <97.05%> (+0.68%) ⬆️

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

ogenstad and others added 7 commits November 30, 2026 06:42
…ead 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 <noreply@anthropic.com>
…C-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 <noreply@anthropic.com>
… [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 <noreply@anthropic.com>
…FC-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 <noreply@anthropic.com>
…irectory [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 <noreply@anthropic.com>
… [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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
@ogenstad
ogenstad marked this pull request as ready for review December 1, 2026 12:53
@ogenstad
ogenstad requested a review from a team as a code owner December 1, 2026 12:53

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 19 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="infrahub_sdk/schema/__init__.py">

<violation number="1" location="infrahub_sdk/schema/__init__.py:667">
P2: This new request path is covered only by mocked responses; add an integration test against a compatible Infrahub server to verify the endpoint, payload model, and error envelopes at runtime.

(Based on your team's feedback about real-server coverage.)</violation>
</file>

<file name="infrahub_sdk/ctl/schema.py">

<violation number="1" location="infrahub_sdk/ctl/schema.py:355">
P2: `_export_payload` is the new production path across the SDK/server boundary, but the added CLI tests only mock `GET /api/schema/export`; add a functional test against a compatible Infrahub server that runs the command and reloads the generated YAML.

(Based on your team's feedback about real-server coverage.)</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

if not user_schemas.namespaces:
try:
# 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: _export_payload is the new production path across the SDK/server boundary, but the added CLI tests only mock GET /api/schema/export; add a functional test against a compatible Infrahub server that runs the command and reloads the generated YAML.

(Based on your team's feedback about real-server coverage.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At infrahub_sdk/ctl/schema.py, line 355:

<comment>`_export_payload` is the new production path across the SDK/server boundary, but the added CLI tests only mock `GET /api/schema/export`; add a functional test against a compatible Infrahub server that runs the command and reloads the generated YAML.

(Based on your team's feedback about real-server coverage.) </comment>

<file context>
@@ -294,42 +331,92 @@ def _default_export_directory() -> Path:
-    if not user_schemas.namespaces:
+    try:
+        # 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:
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is a problem with the current testing setup with testcontainers. We'll have a follow up issue for this test.

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This new request path is covered only by mocked responses; add an integration test against a compatible Infrahub server to verify the endpoint, payload model, and error envelopes at runtime.

(Based on your team's feedback about real-server coverage.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At infrahub_sdk/schema/__init__.py, line 667:

<comment>This new request path is covered only by mocked responses; add an integration test against a compatible Infrahub server to verify the endpoint, payload model, and error envelopes at runtime.

(Based on your team's feedback about real-server coverage.) </comment>

<file context>
@@ -579,28 +641,44 @@ async def export(
         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))
+        _, document = self._parse_export_response(response=response, branch=branch)
+        return document
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is a problem with the current testing setup with testcontainers. We'll have a follow up issue for this test.

Comment thread infrahub_sdk/schema/export.py Resolved
ogenstad and others added 2 commits December 1, 2026 13:13
… [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 <noreply@anthropic.com>
…efault [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 <noreply@anthropic.com>

@ajtmccarty ajtmccarty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just one minor changelog comment that may or may not be accurate

- 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A relationship of kind Group, Profile or Hierarchy that the schema owner defined is now written, and this list does not say so

Earlier versions left out every relationship of kind Group, Profile or Hierarchy (export.py#L67, #L116), including relationships the schema owner defined with a name and identifier of their own. The server now leaves out only the six relationships that processing adds, matched by kind, name and identifier (exporter.py#L59-L68). The variation schema USER_RELATIONSHIP_OF_A_GENERATED_KIND has such a relationship, switch_groups of kind Group (export_variations.py#L401-L424), and test_export_writes_a_user_relationship_of_a_kind_processing_also_adds checks that both modes write it (test_exporter.py#L106).

A schema owner who exports again sees these relationships appear in the files. Suggested line, next to the one about object_template:

- A relationship of kind `Group`, `Profile` or `Hierarchy` that you defined is now written, unless it has the name and identifier of a relationship that Infrahub generates, such as `member_of_groups`. Earlier versions left out every relationship of these kinds.

…w 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 <noreply@anthropic.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 1 file (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

View guided diff | Turn on auto-fix | Re-trigger cubic

@ogenstad
ogenstad merged commit c43f5ff into infrahub-develop Dec 2, 2026
32 checks passed
@ogenstad
ogenstad deleted the po-ifc-3669-schema-export-cli branch December 2, 2026 13:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type/documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants