feat: parse the server error envelope onto the base exception classes

Merged
OG
3mo ago
+1826-168

Why

Part of the error enrichment that was included in 1.10.0 the overall epic aims to allow the SDK to raise more specific errors when there are problems such as node not found instead of the generic GraphQLError


When Infrahub rejects a request, the SDK throws away almost everything the server said about why. A caller who needs to react to a specific failure has only the message text to go on, so the only way to branch on "this was a uniqueness violation" rather than "something failed" is to string-match prose that is free to change between releases. The SDK does this to itself too, matching the literal "Expired Signature" to decide whether a 401 is worth a silent token refresh.

Goal: carry the server's error envelope onto the exception, so exc.code is the thing you branch on.

Non-goals: this is issue 1 of the four in the spec's PR split. It deliberately does not add generated per-code bindings (issue 3), re-root the not-found classes or touch the CLI error ladder (issue 2), or change any error message. No class anyone catches changes shape.

Part of IFC-3034 / IHS-293.

What changed

Behavioural:

  • AuthenticationError and GraphQLError now carry code, http_status, extensions, and errors from the server's response, via a new shared ApiError base. Callers can branch on the catalogue code instead of the message.
  • The silent token refresh is decided by TOKEN_EXPIRED in the envelope, with the legacy "Expired Signature" string kept only for servers that predate the catalogue. That literal now appears once in the SDK, down from twice.
  • Fixes a crash: a 401 whose body was valid JSON but not an object (a bare array, string, or null, as a proxy or gateway can return) raised AttributeError out of the client. It now surfaces as AuthenticationError like every other unreadable 401.
  • Rejected file uploads now raise AuthenticationError too. The multipart path called raise_for_status() bare, so a 401 or 403 on an upload surfaced a raw httpx.HTTPStatusError while every other request raised AuthenticationError. Pre-existing rather than introduced here, but squarely inside FR-015's "every failure the SDK observes as HTTP 401 or 403". The silent refresh already covered this path; only the error type was inconsistent.

Implementation:

  • infrahub_sdk/exceptions.py becomes a package: base.py (the hand-written hierarchy), factory.py (two raise-time factories), __init__.py (a star-import façade). The import path infrahub_sdk.exceptions is unchanged, and a committed snapshot test pins that nothing dropped out of it.
  • Fifteen call sites that each hand-rolled " | ".join(messages) or built a GraphQLError now funnel through the factories, so envelope parsing lives in one place.
  • Both factories are total. Any shape the parser cannot read degrades to the generic exception that call site raised anyway, never to an SDK error of our own. That is the property the malformed_* fixtures exist to pin.

What stayed the same: no message text changed, no class was removed from any MRO, and ApiError is inserted strictly between Error and the two classes, so every existing except and isinstance still matches exactly what it matched. The CLI error ladder is byte-for-byte untouched.

Suggested review order

  1. infrahub_sdk/exceptions/base.py and factory.py for the new shape.
  2. infrahub_sdk/client.py _should_refresh_token for the crash fix, and the two _execute_graphql_with_file methods for the upload path.
  3. The call sites in object_store.py / file_handler.py, which are all the same edit.
  4. Tests last.

How to review

Four things worth a sceptical eye:

  1. Exception types on unreadable 401/403 bodies changed. A non-JSON body previously raised JsonDecodeError (or a raw json.JSONDecodeError from the object store and file handler); a body with no errors key raised TypeError. Both now raise AuthenticationError. FR-015 requires AuthenticationError for every 401/403, so this fixes a pre-existing deviation, but it is visible to external consumers and has a changelog fragment.
  2. GraphQLError.errors drops entries that are not dicts and maps a non-list errors to [], so the declared Sequence[dict[str, Any]] is true at runtime. The payload still reaches the reader through the exception message. Consequence worth knowing: for a malformed envelope infrahubctl now prints nothing and exits 1, where it previously printed the payload. Issue 2's T040 fixes the renderer.
  3. errors is no longer declared list. It inherits Sequence[dict[str, Any]], which removes an unsound mutable-attribute override that pyright flags. is_unknown_field_error and print_graphql_errors were widened to match. Runtime is unaffected; an external consumer only breaks if it annotates list or calls .append() on exc.errors.
  4. Six docstrings carry a # noqa: DOC501. Ruff reads raise make_error(...) as raising something named make_error and asks the docstring to document a function rather than an exception; the docstrings already name the real types. There is no config-level suppression, so the rule keeps working everywhere else. The directive sits after the docstring's closing quotes because that is the only placement ruff honours for this rule, and RUF100 reports it as unused if ruff ever resolves a call to its return type.

The second commit annotates six tasks in tasks.md where the implementation diverged from the plan, each with the reasoning. The one that matters for the next issue: GraphQLError's optional message parameter is deferred to its first caller rather than added unused, so T035 adds it.

How to test

uv run pytest tests/unit/ -q
uv run invoke format lint-code
uv run invoke docs-generate docs-validate

Expected: unit suite green, ruff / ty / mypy clean across 160 files, docs in sync.

On macOS, 11 pre-existing failures are environmental and unrelated: 8 in tests/unit/pytest_plugin/ are psutil.cpu_freq() raising SystemError inside the testcontainers plugin, and 3 in tests/unit/ctl/ are Rich table assertions sensitive to terminal width.

Impact & rollout

  • Backward compatibility: no except clause in the SDK or CLI loses coverage. External consumers catching JsonDecodeError or TypeError around a 401/403 must catch AuthenticationError instead; documented in changelog/+error-catalogue-envelope.changed.md.
  • Performance: none. Parsing happens only on an error path that already decoded the body.
  • Config/env changes: none.
  • Deployment notes: safe to deploy on its own. Per the spec's landing order, the SDK merges before Infrahub bumps its submodule pointer, but that ordering constraint applies to issues 3 and 4, not this one.

Checklist

  • Tests added/updated
  • Changelog entry added (two fragments: one changed, one fixed)
  • External docs updated (if user-facing or ops-facing change) — the catalogue topic page belongs to issue 3, once per-code bindings exist
  • Internal .md docs updated (internal knowledge and AI code tools knowledge)