feat: typed exceptions for the server's error catalogue
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
| PR | What it landed | Approved by |
|---|---|---|
| #1348 | Parse the server error envelope onto the base exception classes. ApiError above both transports; code, http_status, extensions, errors on every server-reported failure. | @polmichel |
| #1363 | Unify and re-root the not-found classes under GraphQLError, so one class covers a lookup miss however it arose. | @ajtmccarty |
| #1373 | Raise 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_VIOLATIONraises
UniquenessViolationErrorwith.node_kindand.fieldspopulated. All of them descend from
GraphQLError, so no existingexceptclause stops catching what it catches today. - The three authentication codes deliberately have no class.
AUTHENTICATION_REQUIRED,TOKEN_EXPIREDandPERMISSION_DENIEDare 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. CatchApiErrorand testexc.code. queryandvariablesare readable on everyApiError, where reading either off an
AuthenticationErrorpreviously raisedAttributeError.- Exceptions survive
pickleandcopy.deepcopy, which the keyword-only generated constructors
andGraphQLError'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
ApiErrorbase above bothAuthenticationErrorandGraphQLError. Authentication failures reach consumers from the REST path as well as GraphQL, so they cannot simply be re-rooted underGraphQLError. A 401/403 on a GraphQL call is handled as anhttpx.HTTPStatusErrorand raisesAuthenticationErrorbefore the body is parsed for GraphQL errors β soexcept GraphQLErrornever caught auth failures, and no dual inheritance is needed to preserve compatibility. .codeis a catalogue string orNone. The/api/...envelope'sextensions.codeis 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_sdksubmodule, matching howprotocols.pyand 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 existingvalidate-generatedcheck. - 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
isinstanceladder gets shadowed.infrahub_sdk/ctl/utils.pytestedGraphQLErrorbefore 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 unifiedNodeNotFoundErrorraised purely client-side has an empty list. identifiercarries two types. The client-sideNodeNotFoundErrorhasidentifieras 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
AuthenticationErrorandGraphQLErrorshare a newApiErrorbase carryingcode,http_status,extensions,errors,query, andvariables, 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, andSCHEMA_NOT_FOUNDraiseNodeNotFoundError,BranchNotFoundError, andSchemaNotFoundError, all re-rooted underGraphQLError;NodeInvalidErrorinherits the re-rooting withCODEcleared.- 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.
GraphQLErrorand its subclasses now survivepickleandcopy.deepcopy, which previously corrupted the message or raisedTypeErroron 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
AuthenticationErrorwith the best reason available instead ofJsonDecodeError,TypeError, or the generic default; a file 404 always raisesNodeNotFoundErrorwhatever the body contains. infrahubctlroutes 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.pybecame a strictly layered package (base,catalogue,factory, faΓ§ade);infrahub_sdk.exceptionsstays 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_ERRORstays readable onexc.codebut 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.