feat: typed exceptions for the server's error catalogue

Merged
OG
2mo ago
+8374-148

The SDK's half of Infrahub's error catalogue, end to end. Every catalogued code now reaches the
caller as an exception class carrying its payload as directly typed attributes, so branching on one
specific server failure never means matching words in a message.

Ref: IFC-3034. Related: IFC-2279 (spike), INFP-468 (backend catalogue), GitHub #7498 (out of scope).


πŸ‘€ What actually needs review

Most of this PR has already been reviewed and approved in three separate pull requests (listed
below). What has not been through a review is small:

1. a2abeca β€” a CLI rendering fix (6 files, +44/-7) ← the only production-code change here

infrahub_sdk/ctl/cli_commands.py. Re-rooting the not-found classes under GraphQLError in #1363
put them inside the except GraphQLError that the transform path uses, where the renderer prints a
server error list a client-side lookup miss does not have, and its actual message goes unshown. They
now propagate to the shared handler, which has a branch for them.

That clause also raised typer.Abort, which is an ordinary exception with no branch in
handle_exception, so it reached the tail that prints Error: and dumps a traceback after the
command had already rendered the real failure. It exits instead.

Found by cubic on this PR; the same hazard was fixed in ctl/utils.py during #1363 but this second
site was missed.

2. 2af53e7 β€” retry-suite alignment (2 files, +23/-4)

tests/unit/sdk/test_retry.py plus the pyproject.toml pytest markers. Pushed straight to this
branch rather than through one of the PRs below.

3. beb37f1 β€” changelog de-duplication (2 files, +5/-5)

Three entries were repeating each other's sentences. Each passage now sits in the single entry that
owns it.


βœ… Already reviewed and approved

PRWhat it landedApproved by
#1348Parse the server error envelope onto the base exception classes. ApiError above both transports; code, http_status, extensions, errors on every server-reported failure.@polmichel
#1363Unify and re-root the not-found classes under GraphQLError, so one class covers a lookup miss however it arose.@ajtmccarty
#1373Raise a typed exception per catalogue code: nine generated classes, the generated bindings, per-code resolution with a validation-failure fallback, both-client parity, live-server integration tests, the topic page.@gmazoyer

What a caller will notice

  • A catalogued failure raises its own class. UNIQUENESS_VIOLATION raises
    UniquenessViolationError with .node_kind and .fields populated. All of them descend from
    GraphQLError, so no existing except clause stops catching what it catches today.
  • The three authentication codes deliberately have no class.
    AUTHENTICATION_REQUIRED, TOKEN_EXPIRED and PERMISSION_DENIED are the codes a server reports
    for failures it rejects a request on, so they routinely arrive on either transport, and each
    transport already has a class existing code depends on. Catch ApiError and test exc.code.
  • query and variables are readable on every ApiError, where reading either off an
    AuthenticationError previously raised AttributeError.
  • Exceptions survive pickle and copy.deepcopy, which the keyword-only generated constructors
    and GraphQLError's error-list-first constructor both broke.
  • The silent token refresh is decided by code, not message text β€” TOKEN_EXPIRED, falling back
    to the legacy "Expired Signature" string for pre-catalogue servers. An API-token client no longer
    replays a stale token it cannot refresh.

The rule worth understanding

Which class a failure lands on follows the transport the SDK observed, never the status the code
declares.
A code read from an errors array raises GraphQLError even when it declares 401; a
response the SDK rejected before the query ran raises AuthenticationError whatever code it carries.

That is what lets the three authentication codes have no class of their own: each reaches the SDK on
either transport, and every catalogued class descends from GraphQLError, so raising one on the
authentication branch would put that failure out of reach of except AuthenticationError.

Decisions settled while drafting

  • A new ApiError base above both AuthenticationError and GraphQLError. Authentication failures reach consumers from the REST path as well as GraphQL, so they cannot simply be re-rooted under GraphQLError. A 401/403 on a GraphQL call is handled as an httpx.HTTPStatusError and raises AuthenticationError before the body is parsed for GraphQL errors β€” so except GraphQLError never caught auth failures, and no dual inheritance is needed to preserve compatibility.
  • .code is a catalogue string or None. The /api/... envelope's extensions.code is an integer mirroring the HTTP status, a different thing with a different type; it is not surfaced through .code. The catalogue is GraphQL-only today.
  • Infrahub generates the bindings into this repo as its python_sdk submodule, matching how protocols.py and the generated schema models already arrive. No copy of the catalogue schema is vendored here, so there is one freshness invariant instead of two, policed by extending Infrahub's existing validate-generated check.
  • Query text is dropped from the message for catalogued errors only; uncatalogued errors keep today's message verbatim.
  • The faΓ§ade re-exports by explicit name, not import *. A wildcard would promote the payload models, both lookup maps and the dispatch helper onto the package surface, where a name is a stability promise. Three tests hold the hand-written lists in step with their sources.

Hazards the code survey found

  • An ordered isinstance ladder gets shadowed. infrahub_sdk/ctl/utils.py tested GraphQLError before the not-found classes. Re-rooting makes the later branch unreachable, silently changing CLI output for exactly the errors this feature makes specific. Fixed in #1363 β€” and item 1 above is the second site that fix missed.
  • A renderer with no server errors to render. That same branch renders exc.errors; a unified NodeNotFoundError raised purely client-side has an empty list.
  • identifier carries two types. The client-side NodeNotFoundError has identifier as a mapping of filters; the catalogue payload has it as a single string. The annotation widens, called out in its own changelog fragment.

Scope and checks

Six prioritised user stories, 28 functional requirements. FR-025 to FR-027 land in the Infrahub
repository (generation plus the extended drift check) and are tagged as such; everything else lands
here. The generator is Infrahub #10678, which must merge after this one β€” it pins its submodule
pointer at the commit this branch produces.

invoke format lint-code clean with zero suppressions; docs-generate/docs-validate show no drift;
2315 unit tests pass; requirements checklist 16/16.


Summary by cubic

Makes the SDK consume Infrahub's GraphQL error catalogue: authentication and GraphQL failures surface the server's error envelope, every catalogued code raises an exception class of its own carrying typed payload attributes, and the three lookup-miss codes now raise their own classes under GraphQLError. The IFC-3034 specification, plan, contracts, and 83-task breakdown land in dev/specs/ifc-3034-error-catalogue/ alongside the generated bindings.

What changed

  • AuthenticationError and GraphQLError share a new ApiError base carrying code, http_status, extensions, errors, query, and variables, so callers can branch on the catalogue code instead of matching message text.
  • Nine catalogue codes raise a generated class each with the payload as typed attributes (UniquenessViolationError.node_kind, .fields); the three 401/403 codes get payload models but no class, since the SDK routes those by the transport it observed.
  • NODE_NOT_FOUND, BRANCH_NOT_FOUND, and SCHEMA_NOT_FOUND raise NodeNotFoundError, BranchNotFoundError, and SchemaNotFoundError, all re-rooted under GraphQLError; NodeInvalidError inherits the re-rooting with CODE cleared.
  • A catalogued failure's message names the code and the server's message instead of embedding the query text; uncatalogued failures keep the old message verbatim.
  • GraphQLError and its subclasses now survive pickle and copy.deepcopy, which previously corrupted the message or raised TypeError on the per-code classes.
  • A payload that violates the catalogue falls back to the generic class for the transport with the code still readable; an unknown code from a newer server surfaces the same way.
  • A 401/403 with an unreadable body raises AuthenticationError with the best reason available instead of JsonDecodeError, TypeError, or the generic default; a file 404 always raises NodeNotFoundError whatever the body contains.
  • infrahubctl routes lookup misses to the shared error handler instead of rendering an empty server error list, exits rather than dumping a traceback after a rendered failure, prints the exception's message instead of "0 error(s)" for an unreadable GraphQL failure, and escapes bracketed text so rich no longer eats branch names.
  • A client authenticating with an API token no longer retries after an expired-token 401.
  • infrahub_sdk/exceptions.py became a strictly layered package (base, catalogue, factory, faΓ§ade); infrahub_sdk.exceptions stays the one supported import path, pinned by a snapshot test.

Design notes

  • The hierarchy is single-inheritance; the raised class comes from the response's first error code and the transport observed, never from payload validity or binding freshness.
  • code_names_the_failure() separates a described failure from a merely coded one: UNDEFINED_ERROR stays readable on exc.code but does not shape the message.
  • The Infrahub-side generator that produces the bindings lands in a separate pull request; this PR carries its generated output.