feat: unify and re-root the not-found classes under GraphQLError

Merged
OG
2mo ago
+1195-85

Why

NodeNotFoundError, BranchNotFoundError, and SchemaNotFoundError each represent a failure the server has a catalogue code for, but they sat outside the ApiError tree — so there was no single clause that catches a lookup miss regardless of whether the server reported it, the SDK decided it, or a REST 404 produced it. A catalogued failure's message also led with the GraphQL query text rather than with what actually went wrong.

Goal: make the hierarchy a tree under ApiError, have the three not-found classes adopt their catalogue codes, and make a server-reported failure's message say which failure it was.

Non-goals: no generated per-code classes and no infrahub_sdk/exceptions/catalogue.py. The typed per-code exceptions, the error_handling.mdx topic page, and the Infrahub-side generator are separate changes.

What changed

Behavioral changes:

  • except GraphQLError now also catches a node, branch, or schema lookup miss, including client-side ones and the REST 404 the file handler converts. NodeInvalidError inherits it.
  • exc.errors, exc.query, and exc.variables are readable on those classes instead of raising AttributeError, since they now go through the constructor that owns that state.
  • A catalogued failure reports as UNIQUENESS_VIOLATION: Node of kind TestPerson already has name 'John' instead of embedding the query. An uncatalogued one keeps today's message byte for byte.
  • infrahubctl reports a catalogued failure by its code instead of labelling every 401 "Authentication failure" or printing a bare error list.

Implementation notes:

  • The three classes declare a CODE attribute. Nothing here reads it — Infrahub's generator parses it out of base.py to know which codes are already represented — so a test pins the three strings.
  • The CLI branch keys on exc.code is not None rather than on a class, so no future re-rooting can shadow it.
  • The message names only the governing error (the first, which determines the class raised). The full list stays on exc.errors, and the CLI renders it beneath.

What stayed the same:

  • Nothing renamed or removed, no constructor loses a signature. A snapshot test pins that every name importable from infrahub_sdk.exceptions still is, and now that each still descends from Error.
  • An uncatalogued failure's message and CLI rendering are unchanged.

How to review

Start with infrahub_sdk/exceptions/base.py — the re-rooting and the CODE declarations are the whole compatibility surface. Then infrahub_sdk/ctl/utils.py, where ladder order matters: the lookup-miss branch has to sit above GraphQLError or re-rooting makes it unreachable.

Where I'd want scrutiny:

  • The auth message now carries the code too. The requirement is written about a server-reported catalogued failure rather than about a transport, so I applied it to both factories. That changed two assertions which landed in #1348. If you read it as GraphQL-only, it's a one-line revert plus those two assertions.
  • infrahub_sdk/transfer/importer/json.py is outside this change's nominal file set. Re-rooting broke it: isinstance(result, GraphQLError) now matches classes whose errors is [], so --continue-on-error reported NodeNotFoundError: [] with no reason attached. Now guarded on result.errors. It is the one fix here with no direct test — that loop is not unit-testable without a refactor I judged disproportionate.

How to test

uv run pytest tests/unit/sdk/test_exceptions.py tests/unit/ctl/test_utils.py -v
uv run pytest tests/unit/ -q
uv run invoke format lint-code
uv run invoke docs-generate && uv run invoke docs-validate

Unit suite passes (1981). On macOS, 11 failures are pre-existing and environmental — a psutil.cpu_freq() crash in the infrahub-testcontainers plugin kills the inner pytester subprocess in tests/unit/pytest_plugin/, and three ctl tests wrap Rich table output at the local terminal width — and all reproduce identically on the base commit.

Impact & rollout

  • Backward compatibility: three deliberate broadenings, each with a changelog fragment — except GraphQLError catches more, described message text changes shape, and a server-reported adopted code now raises its own class so except NodeNotFoundError sees server-side misses too. Nothing renamed or removed.
  • Performance: none.
  • Config/env changes: none.
  • Deployment notes: safe on its own. Blocks the Infrahub-side generator, which needs the CODE declarations to exist.

Found along the way, not fixed here: #1366

Reviewing the one line this PR touches in transfer/importer/json.py turned up an unrelated two-year-old bug. execute_batches never unpacks the (node, result) pair its batch yields, so isinstance(result, Exception) always tests a tuple and the error branch is unreachable: infrahubctl load records a failed import task as a success, and --continue-on-error is a no-op.

Fixing it here made the branch reachable and turned six test_export_import integration tests red, exposing an HTTP 500 from update_optional_relationships that those tests had been passing through for as long as the bug existed. That is a separate fault, likely server-side, and it should not hold an error-catalogue PR red, so both were reverted in cbb31943 and written up in #1366 with the fix, a standalone repro, and regression tests.

The only thing left here from that detour is a defensive err.get("message", err) where the error branch read err["message"]. It guards code that cannot currently run, which is why it ships without a test.

Checklist

  • Tests added/updated
  • Changelog entry added
  • External docs updated — the topic page belongs to the follow-up that adds the classes it documents
  • Internal .md docs updated

Assisted-by: speckit-implement unversioned
Assisted-by: code-review unversioned
Assisted-by: opsmill-dev-commit 0.1.0
Assisted-by: opsmill-dev-pr 0.1.0


Summary by cubic

Re-roots the not-found classes under GraphQLError and makes a server-reported NODE_NOT_FOUND, BRANCH_NOT_FOUND, or SCHEMA_NOT_FOUND raise the matching class instead of a generic GraphQLError, so one clause catches a lookup miss however it arose. Implements IHS-294.

Behavior

  • except GraphQLError now also catches node, branch, and schema lookup misses, including client-side ones and the REST 404; NodeInvalidError inherits the broadening but clears CODE.
  • A described failure's message names the code and the server's message unless the governing error said nothing, in which case the message is what the call site would otherwise produce; UNDEFINED_ERROR and errors with no code keep today's message byte-identical.
  • Authentication failures now also prefix the reported code when described, which changed two existing test assertions.
  • infrahubctl renders a described failure by its code, keeps the path when the server sent one, lists the remaining server errors beneath it, and escapes every printed message, including the fallback traceback.
  • exc.errors, exc.query, exc.variables, and exc.code are readable on all three re-rooted classes.

Notes

  • code_names_the_failure() is the test for "the server described this": UNDEFINED_ERROR is coded but names nothing, so it never shapes the message or the CLI headline.
  • The three classes declare CODE attributes and gain from_payload classmethods, which the factory dispatches server payloads through; query_groups catches NodeNotFoundError with a legacy-message fallback for servers older than the catalogue.
  • The infrahubctl load importer fix was reverted, so failed import tasks are still counted as successes; only the defensive .get guard remains.
  • Nothing is renamed or removed; constructors keep their signatures, and the exceptions facade re-exports only names that have a caller.