Skip to content

perf(http): encode ?format=json replies with orjson - #902

Merged
sv merged 3 commits into
mainfrom
perf/json-c-encoder
Sep 24, 2026
Merged

sv merged 3 commits into
mainfrom
perf/json-c-encoder

Conversation

@sv

@sv sv commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

What

respond() now encodes ?format=json replies with orjson, as compact JSON, instead of stdlib json.dumps(..., indent=1). Each reply is a single line carrying the same JSON value as before: the same keys, key order and raw UTF-8. The published documents and /stats keep stdlib with indent=1.

Why

I profiled 0.14.3 on the live box (2026-09-24 02:27 UTC, 711 req/s). Encoding these replies took ~24% of GIL-held Python, about 0.5 cores, and all of it was in stdlib's pure-Python _iterencode. Passing any indent turns off stdlib's C encoder. 64% of requests are ?wait long-polls, and their replies go through this path.

Benchmark on real read_messages views, time per encode:

Reply indent=1 (before) orjson (after) Speedup Size
3-message long-poll 10.4 µs 0.2 µs ~50x 703 → 604 B
50-message page 112.5 µs 2.3 µs ~49x 10.1 → 8.7 KB

I expect this to take back nearly all of that ~0.5 cores in production. That's a projection from the benchmark, not a production measurement.

Why it waited for #585: until then, last_seq echoed the caller's ?since=, which can exceed 64 bits, and orjson refuses such integers with a 500. test_numeric_inputs_cannot_overflow_or_amplify caught that, so the first version of this PR used the stdlib C encoder, which is only ~3.4x faster. With #585, last_seq is capped at the room's head. Nothing else in these views can go past 64 bits:

  • Records were written by orjson in the first place, and orjson.loads refuses lone surrogates.
  • A 19-digit nonce fits in unsigned 64-bit.
  • Every other field is a bounded count or a string.

That same test now guards the clamp this relies on.

This changes no core code lines.

Release note: Perf: ?format=json replies are compact single-line JSON with the same value as before, encoded about 50x faster.

Checks

Verified against main at c94ba55, which includes #585.

  • uv run coverage run -m pytest tests -q && uv run coverage report: 849 passed, 1 skipped. The new test fails on c05e6c2, where the reply spans 22 lines. It also pins the JSON value, key order, raw UTF-8 and a 19-digit nonce.
  • uv run ruff check . && uv run ruff format --check . and uv run ty check, plus sz.py --caps. --check fails only on fix(store): clamp since past head to the real head in read_messages #585's own store.py growth, which is already on main.
  • /humans Playwright probe: all checks passed. ?since=2**70&format=json returns 200.
  • Docs that would now be wrong are updated: none, since no doc describes the indentation.
  • New surface on a world-writable service: nothing new

`respond()` passed `indent=1`, and any indent drops stdlib json onto its
pure-Python encoder. That path carries every JSON read, long-poll and
write reply: on the live box (0.14.3, 711 req/s) it was ~24% of
GIL-held Python, all in `_iterencode`.

Compact separators keep it on the C encoder: the same JSON value,
escaping and number repr, in fewer bytes. On real read_messages views
that is 3.1x for a 3-message long-poll reply and 3.6x for a 50-message
page. The published documents and /stats keep indent=1.

Not orjson, though it is ~50x: a caller's own `?since=` is echoed back
as `last_seq` and may be past 64 bits, which orjson refuses
(test_numeric_inputs_cannot_overflow_or_amplify).
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-24T04:08:52.285853Z 3999f85 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

sv added 2 commits September 24, 2026 12:02
With #585 on main, `last_seq` is clamped to the room's head instead of
echoing the caller's `?since=`, so nothing in a `respond()` view can be
wider than 64 bits any more: records are what orjson wrote, and every
other field is a bounded count or a str. That was the only reason this
PR stopped at the stdlib C encoder.

orjson is 36-52x the old `indent=1` encode on real read_messages views
(3-message long-poll reply 10.4 -> 0.2 us, 50-message page 112.5 ->
2.3 us), against 3.2-3.6x for the C encoder. Same compact bytes.
test_numeric_inputs_cannot_overflow_or_amplify (`?since=2**70`) now
guards the clamp this depends on: without it the reply is a 500.
@sv sv changed the title perf(http): encode ?format=json replies with the C encoder perf(http): encode ?format=json replies with orjson Sep 24, 2026
@sv
sv merged commit f840f45 into main Sep 24, 2026
13 of 14 checks passed
@sv
sv deleted the perf/json-c-encoder branch September 24, 2026 04:13
@sv sv mentioned this pull request Sep 24, 2026
7 tasks done
sv added a commit that referenced this pull request Sep 24, 2026
## What

This PR cuts **0.14.4**. It touches the same nine files as #899:
- the CHANGELOG section gets its date;
- the version is bumped in the files the service, the MCP wrapper and
the worker share;
- the measured block of `sz-baseline.json` is re-ratcheted. No cap
moves.

## Why

**Main CI is red.** #585 grew `store.py` from 1025 to 1029 code lines,
which is under its cap of 1030. Since then every push to main has failed
`sz.py --check`, and the steps after it have been skipped: the example
e2e, the MCP wrapper build, and the image build and smoke. This PR's CI
is the first to run those steps against #585, #902 and #903.

Changes since v0.14.3. The release is PATCH, because no route, field or
cap changes:
- **#902:** `?format=json` replies are one compact line, encoded ~50x
faster. It's the same JSON value.
- **#903:** starlette 1.7.0, uvicorn 0.53.0 and cryptography 50.0.1. It
also moves the test-only httpx2 past three Dependabot alerts; the
service could never reach them, and none are open now.
- **#585:** a `?since=` past a room's head is clamped to the head
instead of echoed back.
- **#886:** repeated `Accept` lines are honored.
- **#620:** a streamed request body is measured before it is buffered.
- **#757 (edge):** `/favicon.ico?v=…` is served by the edge.

Following precedent, the test and CI PRs #788, #791 and #871 have no
entries.

**After merge:**
- Tag `v0.14.4` on the squash commit. That publishes
`ghcr.io/flop-labs/technocore-chat:0.14.4`, and the box's autoupdate
timer installs it within ~15 min.
- #757 isn't live until `edge/deploy.sh` runs.
- Whether to cut `mcp-v0.14.4` is your call. 0.14.2 and 0.14.3 skipped
it, and the wrapper hasn't changed.

## Checks

Verified against main at 7772a98, which includes #903.

- [x] `uv run coverage run -m pytest tests -q && uv run coverage
report`: 849 passed, 1 skipped.
- [x] `uv run ruff check . && uv run ruff format --check .` and `uv run
ty check`: clean
- [x] `uv lock --check` passes for the root and for `mcp/worker`, after
`uv build --project mcp` built the 0.14.4 wheel. Only version lines
moved in either lock.
- [x] `sz.py --caps` and `sz.py --check` pass.
- [x] Both `release.yml` gates pass: the tag matches the
`pyproject.toml` version, and CHANGELOG has a `[0.14.4]` section.
- [x] Docs that would now be wrong are updated: `CHANGELOG.md` is the
change
- [x] New surface on a world-writable service: nothing new
Magicianhax added a commit to Magicianhax/technocore-chat that referenced this pull request Sep 29, 2026
flop-labs#902 landed a test asserting that a 19-digit nonce comes back from ?format=json as a JSON
integer — the exact contract this PR changes, added after this branch opened. It is not a
stale assertion; it is the opposite decision, so it is updated here deliberately rather
than worked around, and called out in the PR for a maintainer to settle.

What the test pinned that still holds: one compact line, key order, raw UTF-8 rather than
\u escapes, and the record surviving the encoder unchanged. What moves: the nonce is
stored as an int and returned as the canonical decimal text of that int, because 19 digits
are past Number.MAX_SAFE_INTEGER and JSON.parse rounds them, which breaks the signature
the nonce was signed under (flop-labs#711). orjson encoding it losslessly was never the binding
constraint — the reader's parser is. The wire form is asserted directly as well.

tests/http + tests/unit/test_json_backend.py: 428 passed, the four remaining failures are
this machine's Windows-only concurrency cases and fail identically on origin/main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant