refactor: standardize SDK JSON serialization on orjson

Draft
DG
4mo ago
+896-227

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/.

Closes #1165
Closes #1171

What changed

Behavioral:

  • orjson is now the sole JSON library; ujson + types-ujson removed and all stdlib json usage eliminated in infrahub_sdk/.
  • JSON output is preserved byte-for-byte at every consumed/compared site (indent=2 → OPT_INDENT_2; infrahubctl datetime rendering preserved via OPT_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 to orjson.loads(response.content) at httpx sites) — this incidentally fixes a latent bug in the pytest plugin where except ujson.JSONDecodeError never caught the stdlib error raised by response.json().
  • orjson.dumps() returns bytes: .decode() added at str-consuming sites; OPT_NON_STR_KEYS preserves prior int-key coercion at arbitrary-data sites; file-object I/O (recorder/playback) rewritten since orjson has no load/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

  1. infrahub_sdk/utils.py — dict_hash + decode_json.
  2. Decode/except sites (schema/__init__.py, ctl/parsers.py, template/infrahub_filters.py, pytest_plugin/items/*).
  3. Encode/.decode() sites and pyproject.toml.
  4. 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_hash still returns str. 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 stdlib json.
  • Config/env changes: new runtime dependency orjson>=3.10; ujson + types-ujson removed.
  • 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 ujson and stdlib json with orjson across infrahub_sdk/ (encode/decode, CLI, JSON formatter, Jinja filters, pytest plugin).
    • Unified decoding via orjson.loads(response.content) with except 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_KEYS at 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 uses orjson.dumps.
  • 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; remove ujson and types-ujson.