refactor: standardize SDK JSON serialization on orjson
Why
The SDK used two JSON libraries interchangeably — ujson (~16 modules) and stdlib json (~7; utils.py and playback.py imported both) — with no rule for which to use. This left a latent exception-handling hazard: ujson.JSONDecodeError and json.JSONDecodeError do not catch each other, so a future mismatched decode/except pair would silently fail to catch malformed input.
Goal: converge on a single JSON library — orjson (Rust-backed, faster, stricter) — for a no-behaviour-change speedup on the SDK's hot path (transforms, generators, checks, imports/exports, GraphQL round-trips).
Non-goals: no benchmark harness / CI perf gate; no change to the query-group naming scheme; no migration of JSON usage outside infrahub_sdk/.
What changed
Behavioral:
orjsonis now the sole JSON library;ujson+types-ujsonremoved and all stdlibjsonusage eliminated ininfrahub_sdk/.- JSON output is preserved byte-for-byte at every consumed/compared site (indent=2 →
OPT_INDENT_2;infrahubctldatetime rendering preserved viaOPT_PASSTHROUGH_DATETIME+default=str). - One documented behaviour change: the tracking-group name derived from query parameters containing non-ASCII characters shifts once on upgrade (orjson emits raw UTF-8 where the previous library emitted escaped sequences). Changelog entry added.
Implementation notes:
- All decode/except pairs unified on
orjson.JSONDecodeError(decoding switched toorjson.loads(response.content)at httpx sites) — this incidentally fixes a latent bug in the pytest plugin whereexcept ujson.JSONDecodeErrornever caught the stdlib error raised byresponse.json(). orjson.dumps()returns bytes:.decode()added at str-consuming sites;OPT_NON_STR_KEYSpreserves prior int-key coercion at arbitrary-data sites; file-object I/O (recorder/playback) rewritten since orjson has noload/dump.
What stayed the same: dict_hash public signature and str return type; ASCII/int/float hashes are byte-identical; API contract unchanged.
Suggested review order
infrahub_sdk/utils.py—dict_hash+decode_json.- Decode/except sites (
schema/__init__.py,ctl/parsers.py,template/infrahub_filters.py,pytest_plugin/items/*). - Encode/
.decode()sites andpyproject.toml. - Tests +
dev/specs/002-orjson-json-migration/(decision trail).
How to review
Focus scrutiny on except-clause correctness at decode sites and the non-ASCII dict_hash change. The rest is mechanical import swaps + .decode().
How to test
uv sync --all-groups --all-extras
uv run pytest tests/unit/
grep -rn "import ujson" infrahub_sdk/ # returns nothing
uv run invoke lint-code
Note: 8 pre-existing unit failures reproduce identically on stable (a worktree-path artifact where Rich strips [...] from console output) — unrelated to this change. Integration tests require a live Infrahub server (run in CI).
Impact & rollout
- Backward compatibility: No public API change;
dict_hashstill returnsstr. One-time non-ASCII tracking-group rename (documented); orphaned-group cleanup is manual. - Performance: ad-hoc benchmark — orjson
dumps~11.8x, round-trip ~2.1x faster than stdlibjson. - Config/env changes: new runtime dependency
orjson>=3.10;ujson+types-ujsonremoved. - Deployment notes: safe to deploy.
Checklist
- Tests added/updated
- Changelog entry added (
changelog/+orjson-json-migration.changed.md) - External docs updated (verified no user-facing doc referenced the JSON library)
- Internal .md docs updated (spec artifacts under
dev/specs/)
Summary by cubic
Standardized all SDK JSON serialization on orjson to unify error handling and improve performance. Output remains functionally the same; non-ASCII JSON is now emitted as raw UTF‑8 and tracking‑group names with non‑ASCII query params shift once.
-
Refactors
- Replaced
ujsonand stdlibjsonwithorjsonacrossinfrahub_sdk/(encode/decode, CLI, JSON formatter, Jinja filters, pytest plugin). - Unified decoding via
orjson.loads(response.content)withexcept orjson.JSONDecodeError; fixes the pytest plugin mismatch on HTTP JSON errors. - Pretty-printing standardized to 2 spaces; preserved sorted keys and datetime rendering via
default=str+OPT_PASSTHROUGH_DATETIME; added.decode()where strings are required. - Preserved non-string key coercion using
OPT_NON_STR_KEYSat arbitrary-data sites (CLI transform/formatter, GraphQL multipart, exporter, playback request payload). - Updated recorder/playback and transfer import/export to
orjson; GraphQL string escaping now usesorjson.dumps.
- Replaced
-
Migration
- No API changes. JSON with non-ASCII characters is now written as raw UTF‑8 (not
\uXXXX); bytes differ but content is equivalent. - One-time shift for tracking-group names when query params contain non-ASCII; clean up old groups manually if needed.
- Playback recordings made with older SDKs may not be found due to filename differences; re-record if needed.
- Dependencies: add
orjson>=3.10; removeujsonandtypes-ujson.
- No API changes. JSON with non-ASCII characters is now written as raw UTF‑8 (not