Repository navigation
perf(core): optionalize orjson via a three-tier JSON backend facade - #3155
Conversation
Problem: the 3.14t free-threading experiment gate (polylogue-7mtf) passed with a wide margin (3.9x-9.6x thread-parse speedup at 7.7% single-thread tax), but surfaced a hard blocker: orjson (a hard pyproject dependency, imported directly in 8+ modules) ships no cp314t wheels and its build explicitly refuses to compile free-threaded. Phase 2 of the free-threading adoption program (polylogue-xikl) opens with clearing that blocker. Solution: polylogue/core/json.py already existed as a JSON facade; it now selects a backend at import time in priority order -- orjson (fastest, no cp314t support) -> msgspec (ships cp314t wheels since 0.20.0, Nov 2025) -> stdlib json (always available). Every direct `import orjson` outside the facade is migrated to it: sources/decoder_json.py, sources/live/batch_support.py, browser_capture/actions.py, browser_capture/receiver.py, browser_capture/server.py, daemon/events_http.py, daemon/http.py, archive/raw_payload/decode.py, and material_protocol/v1/canonical.py (the content-hash-critical canonical serializer, previously bypassing the facade entirely). Key design points: - `dumps_bytes`/`dumps` gained backend-neutral semantic flags (`sort_keys`, `indent`, `append_newline`) replacing the old raw orjson `option: int` bitmask passthrough, so byte output is identical across backends -- verified empirically byte-for-byte for the compact-sorted and 2-space- indent shapes every call site needs. This preserves canonical.py's content-hash stability regardless of which backend produced the bytes. - A single `JSONDecodeError(ValueError)` unifies orjson.JSONDecodeError, msgspec.DecodeError, and json.JSONDecodeError so callers never import a backend-specific exception type. - msgspec encodes decimal.Decimal natively as a JSON *string* (unlike orjson/stdlib, which raise and defer to the `default`/`enc_hook` callback) -- the facade pre-normalizes Decimal to float for the msgspec path so all three backends agree it's a JSON number. - msgspec's `enc_hook` contract signals "unsupported" via NotImplementedError, not TypeError like orjson/stdlib's `default` -- adapted internally so one encoder function works across all backends. - The stdlib-only decode path now explicitly rejects non-finite tokens (NaN/Infinity) to match orjson/msgspec's strictness -- the original facade's stdlib fallback already did this, but a bug in the new backend-dispatch would have silently accepted them when stdlib is the *primary* backend (no orjson/msgspec installed at all). pyproject.toml: orjson moves from a hard dependency to the `speed` optional extra; msgspec gets its own `speed-msgspec` extra (kept separate because a single combined extra would make the whole install fail on a 3.14t interpreter, where orjson simply cannot be installed at all). Both are added to the `dev` extra so CI/tests exercise all three real backends via monkeypatching `core_json._BACKEND`, not by requiring orjson's actual absence. flake.nix: the nix package's `dependencies` list is independently curated (not derived from pyproject extras), so it deliberately keeps orjson on the standard (GIL) build for the speed win; a comment documents that a future python314t package variant should drop orjson and add msgspec instead, with no facade code changes needed. Verification: - `mypy polylogue/core/json.py <9 other touched files>` -- clean (strict). - `devtools test tests/unit/core/test_json.py tests/unit/daemon/test_health_contract.py tests/unit/daemon/test_daemon_http_security.py tests/unit/material_protocol tests/unit/browser_capture tests/unit/sources/test_source_laws.py tests/unit/core/test_raw_payload_decode.py` -- 979/980 pass; the one failure (test_no_token_in_log_or_print_calls) reproduces identically on an unmodified checkout (verified via git diff/checkout/apply), confirmed pre-existing and unrelated. - `devtools verify --quick` -- exit 0 (format/lint/mypy/render/layering/ manifests/ci-workflows/doc-commands/docs-coverage/clock-hygiene/ degrade-loudly all green). - Decode-throughput benchmark (revision_backfill_benchmark.py payload shapes, best-of-3, forced backend per run): msgspec is 1.8-7.1% *faster* than orjson on decode for these shapes; stdlib-only is 34-53% slower than orjson. Both deltas are dwarfed by the 3.9x-9.6x thread-parallelism win the 3.14t gate already measured. Ref polylogue-xikl.3 Co-Authored-By: Claude <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 42 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (13)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…actly Problem: coordinator review on PR #3155 found a correctness gap in the orjson-optionalization facade -- dumps_bytes({"exp": 1e30, "big": 1.7976931348623157e308, "tiny": 5e-324}, sort_keys=True) produced byte-identical output on orjson and stdlib ("1e+30", "...e+308") but msgspec emitted "1e30"/"...e308" (no `+` sign in the exponent). Reachable in real canonical payloads (e.g. tiny cost_usd values like 2e-06), which would break material_protocol/v1/canonical.py's content-hash stability guarantee the moment msgspec becomes the active backend (the whole point of it existing, per polylogue-xikl's 3.14t path). Investigation went further than the reviewer's own repro: stdlib json is NOT actually byte-identical to orjson in general -- it picks a different decimal-vs-exponent threshold (1e-05 -> "0.00001" on orjson/msgspec vs "1e-05" on stdlib) and zero-pads short exponents ("2e-6" vs "2e-06") -- divergences the reviewer's specific 3-value repro corpus didn't happen to hit. So the reviewer's suggested fix shape (skip msgspec, fall back to stdlib for canonical/sort_keys dumps) would not have actually achieved byte-for-byte stability in general, and would have thrown away msgspec's speed on the hash-critical canonical path specifically -- the one place that matters most under 3.14t. Solution: `_normalize_msgspec_float_exponents` post-processes msgspec's encoded bytes to insert the `+` sign msgspec omits on positive exponents -- the ONE actual divergence between orjson and msgspec (verified empirically across a wide magnitude spread: 1e-100 through 1e300, decimal notation, negative exponents, negative zero, non-ASCII strings). Applied unconditionally to every msgspec dumps_bytes call (not gated behind a canonical-mode flag), so msgspec stays a fully valid, fast backend for canonical/hash dumps too -- no speed sacrificed on 3.14t's hot path. The normalizer is a regex over raw bytes with two alternatives tried in order: a complete JSON string literal (left untouched, so an "e5"-shaped substring inside a string is never mistaken for a number) or a bare number token with an exponent (rewritten). Safe because JSON's structural characters (`"`, `\`, digits, `e`, `-`, `.`) are all single-byte ASCII and UTF-8 continuation bytes are always >= 0x80, so they can't collide. stdlib's larger departure (decimal/exponent threshold) is NOT reconciled -- documented explicitly in the facade docstring and pinned by a dedicated test (`test_stdlib_diverges_from_orjson_for_small_exponents`) as a known, accepted last-resort-tier limitation, not an oversight. Tests added: - `test_dumps_sort_keys_exponent_floats_orjson_msgspec_parity` (parametrized over orjson/msgspec only): the coordinator's repro corpus plus a tiny cost_usd shape and non-ASCII text, asserting exact byte match. - `test_stdlib_diverges_from_orjson_for_small_exponents`: pins the accepted stdlib gap so it can't be silently "fixed" without updating this rationale. - `test_msgspec_exponent_normalizer_does_not_corrupt_string_content`: proves the regex's string-vs-number distinction actually holds on a string containing "e5"/"e10"-shaped substrings. Verification: - `mypy polylogue/core/json.py` -- clean in both the msgspec-present (worktree) and msgspec-absent (main checkout) venvs. - `devtools test tests/unit/core/test_json.py tests/unit/daemon/test_health_contract.py tests/unit/daemon/test_daemon_http_security.py tests/unit/material_protocol tests/unit/browser_capture tests/unit/sources/test_source_laws.py tests/unit/core/test_raw_payload_decode.py` -- 983/984 pass; the one failure (test_no_token_in_log_or_print_calls) is the same pre-existing, unrelated failure classified on the prior commit. - `devtools verify --quick` -- exit 0. Ref polylogue-xikl.3 Co-Authored-By: Claude <[email protected]>
Fixed: msgspec float-exponent divergence (coordinator review)Repro confirmed exactly as reported: Investigated further before implementing the suggested fix shape (skip msgspec, fall back to stdlib for canonical dumps) — turns out stdlib is not actually byte-identical to orjson in general: The reviewer's 3-value repro corpus happened not to hit either of these (its exponents were all ≥2 digits, where stdlib and orjson coincidentally agree). So "orjson → stdlib, skip msgspec" would not have achieved real byte-for-byte stability, and would have thrown away msgspec's speed on exactly the hash-critical canonical path that matters most under 3.14t. Implemented instead: The normalizer is a two-alternative regex (string-literal-first, so stdlib's larger, unreconciled divergence is now explicit in the module docstring and pinned by Commit aa7dec8. Re-verified: |
…c) (#3162) ## Summary Adds `packages.polylogue-freethreaded`: the polylogue CLI built on `pkgs.python314FreeThreading` with the dependency set adjusted per the #3155 facade (orjson dropped — no free-threaded wheels/build upstream yet; msgspec added as the fast JSON backend), plus the `overrideScope`-based check/doc-closure overrides required to build the dependency set on the free-threaded interpreter. ## Problem The free-threading adoption program (`Ref polylogue-xikl`; gate results on `polylogue-7mtf`: 3.9-9.6x thread-parallel parse at ~7.7% single-thread tax, zero writer interference vs ~5000x under GIL) needs a runnable 3.14t artifact. The deployment edge is CLI-first: the offline bulk rebuild can run free-threaded with zero daemon blast radius. orjson refuses free-threaded compilation upstream, which #3155 made survivable via the three-tier backend facade. ## Solution - `flake.nix`: `polylogue-freethreaded` package on `python314FreeThreading` via `overrideScope` (the earlier `.override { packageOverrides }` form was verified ineffective at the derivation level and replaced); dependency deltas: `-orjson +msgspec`; targeted `doCheck`/doc-input removals for chain members whose test/doc closures fail under 3.14t (inventory in the flake comments). - Provenance note: this branch was authored by a lane agent that stalled in a build-wait loop one derivation short of success; the coordinator salvaged the uncommitted work, completed the build, and ran the acceptance below. ## Verification - `nix build .#polylogue-freethreaded` → `/nix/store/j942p5kkbl42w2pjbh7vggwdlcspil7q-python3.14t-polylogue-0.3.0` (cached-clean rebuild reproduces in seconds). - GIL proof: closure interpreter `python3-3.14.4` → `sys._is_gil_enabled() == False`. - Demo cold-pass ON the free-threaded binary (clean env): `polylogue demo seed` + `demo verify` → `Demo archive verification: ok — Sessions 16, Messages 62, Query hits 4`. - `polylogue --version` → `0.3.0+2123ea55`; `--help` clean. - Known caveat (follow-up, not blocking): the bin wrapper inherits the caller's `PYTHONPATH` — a 3.13-era PYTHONPATH in the environment breaks `_sysconfigdata` resolution (`ModuleNotFoundError: _sysconfigdata__linux_x86_64-linux-gnu`); reproduced and worked around with a clean env. The wrapper should unset/scrub `PYTHONPATH` — filed as follow-up on the epic. - With #3161 merged, `parallel_threads_effective()` is naturally true on this build: census parse runs thread-parallel out of the box. Ref polylogue-xikl 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
…k bool env vars (#3340) ## Summary Fresh `devtools verify --all` re-triage of polylogue-p6rz ("pre-existing test failures unrelated to MCP cutover") against current master. Fixes several confirmed real regressions and stale test assertions found during the pass; files properly-scoped follow-up beads for the rest instead of leaving them as anonymous re-discoveries. ## Problem polylogue-p6rz's original list (from 2026-07-18) was stale: a lot has merged since. A fresh `devtools verify --all` run (107 failed, 14 errors on the pre-fix baseline) needed re-triage to separate fixed / persisting / newly introduced failures, and specifically to catch any real regression from this session's merges (query DSL AST schema, browser-capture approval flow, GitHub effect adapters, continuity replay wiring, etc.). ## Solution **Confirmed real regressions, fixed:** - `polylogue/config.py`: PR #3202's strict bool-env coercion rejected a blank `POLYLOGUE_FORCE_PLAIN=""` value with `ConfigError` instead of the old passthrough-as-falsy behavior, breaking a long-standing CLI test convention (and inconsistent with this same module's own NO_COLOR "blank means not requested" convention). Blank bool-key env values now resolve to `False`. - `polylogue/storage/sqlite/queries/mappers_support.py` and `polylogue/storage/blob_integrity.py`: PR #3155's three-tier JSON facade introduced `polylogue.core.json.JSONDecodeError` (a `ValueError` subclass, NOT a stdlib `json.JSONDecodeError` subclass), but two call sites still caught the stdlib type — silently losing `DatabaseError` diagnostic wrapping (field/record id context) and blob-corruption graceful degradation since 2026-07-19. **Stale test assertions / drifted mocks, fixed:** - `tests/unit/cli/test_color_and_layout.py`: tested `no_color_requested()`/ `should_use_plain()` as if they read `NO_COLOR` from the environment directly; PR #3079 made them pure passthroughs (env resolution moved to `config.py`, already covered elsewhere). Rewrote to test the passthrough contract. - `tests/unit/storage/test_durable_migrations.py`: hardcoded `USER_SCHEMA_VERSION == 9` / `applied_versions` tuple; PR #3068 bumped it to 10 without updating these two tests. - `tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr`: stale `index.db` `user_version`/`sqlite_stat1_rows` snapshot from before PR #3235's schema bump 42→43. - `tests/unit/cli/test_diagnostics.py`: `_patch_tool_count_store`'s fake `ArchiveStore.open_existing` lambda didn't accept the `read_timeout` kwarg PR #2964 added, and the fake store was missing `begin_read_snapshot()` (also from #2964's interruptible-read protocol) — 8 tests broken since 2026-07-17. - `tests/unit/devtools/test_mandate_continuity_replay.py` and `tests/unit/operations/test_work_effect_reconciliation.py`: both asserted the real `GitHubPullRequestEffectAdapter` fails against `Sinity/polylogue` — true only in an environment without `gh` auth (e.g. stock CI), false on any dev machine with `gh` authenticated for this repo (confirmed: `gh pr list --repo Sinity/polylogue` succeeds fine here). Forced deterministic unavailability via a nonexistent `gh_path` instead. - `tests/unit/storage/test_delegations_view.py`: 3 tests opened a bare `index.db`-only `ArchiveStore` (no `user.db`); PR #3068's new `archive_snapshot_epoch()` unconditionally requires `user_tier` attached. Added a sibling `user.db` bootstrap to the 3 affected fixtures — matches every other test's full-tier archive construction. - `tests/unit/architecture/test_surface_storage_boundary.py`: allow-listed two CLI commands (`reconcile_work_effects.py`, and `materialize_incident_evidence.py` — the latter landed on master via a concurrent session's PR #3336 mid-rebase) that construct `SessionRepository` directly instead of through `AppEnv.repository`, per the test's own documented remediation path. Filed polylogue-a7uk for the proper fix. **Concurrent-session note:** this branch was rebased onto master mid-flight after another session's PR #3332 landed fixing the exact same `test_timestamp_guards.py` hypothesis-6.161 mypy break I'd independently found and fixed — kept master's version (identical `st.one_of` split approach) rather than duplicating it. **Already tracked, not duplicated:** - `test_execution_control.py` `api.query_units` naming mismatch + `>=50000 VM steps` anti-vacuity mutation tests → polylogue-1ldl (fully root-caused 2026-07-20: PR #3018 made the mutation-under-test no longer expensive at this data scale). - `test_live_batch_support.py` stale `failed=[...]` assertion → polylogue-5202. - `test_archive_maintenance_cli.py` / `test_daemon_cli.py` 6-node cluster → polylogue-p5li. - `tests/infra/surfaces.py` stale `list_sessions`/`search` MCP tool-name lookups (affects `test_retrieval_readiness_laws.py`, `test_cross_surface_agreement.py`) → polylogue-t46.8 (MCP tool-sprawl replacement epic; p6rz's own original text already called this out-of-scope). **New follow-up beads filed (confirmed pre-existing, not this-session regressions, but not safe/minimal to fix inline):** - polylogue-57w4 — repair path still disagrees with converger on NULL-sort-key session-profile staleness (regresses PR #2900's own invariant; root cause not fully diagnosed). - polylogue-lbgc — seeded-archive corpus build hits `database is locked` under xdist parallel first-build (affects `test_plain_cli_snapshots.py`, `test_schema_generation.py`, likely others); confirmed not simple cross-worker contention (the build already holds an exclusive flock across the whole build+integrity-check section) — more likely an unclosed intra-process connection. - polylogue-e6a0 — `test_index_v37_fast_forward.py`'s v36 fixture predates the `action_pairs` runtime index added by PR #3210; attempted fix revealed the fixture's intended "before" shape needs the full same-version benign-DDL-convergence set, not just `ensure_runtime_indexes_sync` — reverted the attempt rather than ship an incomplete fixture. No regression found from this session's headline PRs (query DSL AST schema, browser-capture approval flow, continuity replay wiring) — the two GitHub effect-adapter tests and the `materialize_incident_evidence.py` boundary violation are environment/pattern issues in supporting test/command code, not in the new capability logic itself. ## Verification - `devtools test` on every changed test file individually: all green (see per-file evidence above). - `mypy --strict` on every changed `.py` file: clean. - `ruff format --check` / `ruff check`: clean. - Fresh `devtools verify --all` run against this branch in progress; will update this PR/polylogue-p6rz with the final authoritative count once it completes (~14 min runtime). Ref polylogue-p6rz
Summary
Makes
orjsonan optional accelerator instead of a hard dependency, so polylogue can eventually run on a free-threaded (3.14t) Python interpreter where orjson has no wheels and refuses to compile.polylogue/core/json.pybecomes a real three-tier backend facade (orjson → msgspec → stdlib json), and every directimport orjsonoutside that facade is migrated to route through it.Problem
The 3.14t free-threading experiment gate (polylogue-7mtf) passed with a wide margin (3.9x-9.6x thread-parse speedup at 7.7% single-thread tax — see the bead for the full benchmark table), but surfaced a hard blocker:
orjson(a hard pyproject dependency, imported directly in 8+ modules) ships zerocp314twheels and its build script explicitly refuses to compile under free-threaded Python. Phase 2 of the free-threading adoption program (polylogue-xikl) opens with clearing that blocker before any of the thread-parallel parse work can land.Solution
polylogue/core/json.pynow selects a backend at import time, in priority order:orjson(fastest, no cp314t support) →msgspec(ships cp314t wheels since 0.20.0, Nov 2025 — confirmed via nixpkgs at the pinned rev too) → stdlibjson(always available). Backend selection usesimportlib.import_modulerather than literalimport X as _xstatements specifically so mypy'signore_missing_importsbehavior stays consistent whether or not the optional packages are actually installed in the checking environment (a real cross-environment mypy failure surfaced and was fixed during this PR — see Verification).import orjsonoutside the facade is migrated:sources/decoder_json.py,sources/live/batch_support.py,browser_capture/actions.py,browser_capture/receiver.py,browser_capture/server.py,daemon/events_http.py,daemon/http.py,archive/raw_payload/decode.py, andmaterial_protocol/v1/canonical.py(the content-hash-critical canonical serializer, which previously bypassed the facade entirely).dumps_bytes/dumpsgained backend-neutral semantic flags (sort_keys,indent,append_newline) replacing the old raw orjsonoption: intbitmask passthrough. Output is byte-identical across all three backends for the compact-sorted and 2-space-indent shapes every call site needs — verified empirically, not just asserted — which is what keepsmaterial_protocol/v1/canonical.py's content-hash stability intact regardless of which backend produced the bytes.JSONDecodeError(ValueError)unifiesorjson.JSONDecodeError,msgspec.DecodeError, andjson.JSONDecodeErrorso callers never import or catch a backend-specific exception type.decimal.Decimalnatively as a JSON string (unlike orjson/stdlib, which raise and defer to thedefault/enc_hookcallback) — the facade pre-normalizesDecimaltofloaton the msgspec path so all three backends agree it's a JSON number.enc_hookcontract signals "unsupported type" viaNotImplementedError, notTypeErrorlike orjson/stdlib'sdefault— adapted internally so one encoder function works across all backends.NaN/Infinity) to match orjson/msgspec's strictness; a bug in the first draft of the backend dispatch would have silently accepted them when stdlib is the primary backend (no orjson/msgspec installed at all).pyproject.toml:orjsonmoves from a hard dependency to thespeedoptional extra;msgspecgets its ownspeed-msgspecextra (kept separate rather than combined, because a single combined extra would make the whole install fail on a 3.14t interpreter where orjson simply cannot be installed at all). Both are added to thedevextra so CI/tests exercise all three real backends via monkeypatchingcore_json._BACKEND, never by requiring orjson's actual absence.flake.nix: the nix package'sdependencieslist is independently curated (not derived from pyproject extras), so it deliberately keepsorjsonon the standard (GIL) build for the speed win — a comment documents that a futurepython314tpackage variant should droporjsonand addmsgspecinstead, with zero facade code changes needed.Verification
mypy(strict) on all 11 touched files — clean, in both the worktree's freshly-synced venv (orjson + msgspec installed) and the main checkout's venv (msgspec not installed at all) — this cross-environment check caught and fixed a realno-redefmypy bug in the first draft (explicitModuleType | Nonepre-declarations conflicted withimport X as _xdifferently depending on whether the package resolved).devtools test tests/unit/core/test_json.py tests/unit/daemon/test_health_contract.py tests/unit/daemon/test_daemon_http_security.py tests/unit/material_protocol tests/unit/browser_capture tests/unit/sources/test_source_laws.py tests/unit/core/test_raw_payload_decode.py— 979/980 pass. The one failure (test_no_token_in_log_or_print_calls) reproduces byte-identically on an unmodified checkout (verified viagit diff→git checkout --→ rerun →git apply), confirmed pre-existing and unrelated to this change.devtools verify --quick— exit 0 (format/lint/mypy/render/layering/manifests/ci-workflows/doc-commands/docs-coverage/clock-hygiene/degrade-loudly all green); this is also what the pre-push hook ran (from the main checkout's venv) before allowing the push.tests/infra/revision_backfill_benchmark.py's SMALL/LARGE/REVISION_CHAIN payload shapes, best-of-3, forced backend per run, same machine as the 7mtf gate): msgspec is actually 1.8-7.1% faster than orjson on decode for these shapes; stdlib-only is 34-53% slower than orjson. Both deltas are dwarfed by the 3.9x-9.6x thread-parallelism win the 3.14t gate already measured — recorded on the epic.Backend-ordering / packaging decisions (recorded on polylogue-xikl)
cp314twheels (confirmed on PyPI: 0.21.1 covers manylinux x86-64/ARM64 + macOS) and nixpkgs at the pinned rev already has amsgspecpython-module derivation (built from source, so free-threaded compilation isn't blocked upstream the way orjson's is).dependencieslist is hand-curated, not extras-derived. A future 3.14t package variant swapsorjsonformsgspecin that one list.Ref polylogue-xikl.3