Serialize intercepted completions directly to JSON bytes - #1795
Merged
Conversation
Contributor
ApprovabilityVerdict: Approved Performance optimization that serializes JSON responses more efficiently using pydantic_core's You can customize Macroscope's approvability policy. Learn more. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Overview
Serialize non-streaming intercepted model completions directly to JSON bytes before returning them to harnesses. This keeps the response contract unchanged while reducing synchronous work and transient allocations on the shared interception-server event loop.
Why
The previous completion-return paths called
web.json_response(completion). That route first uses stdlibjson.dumpsto materialize a complete Python string, then asks aiohttp to UTF-8 encode that string into the final response bytes.Large completions therefore held the JSON string, encoder working memory, and final byte body at the same time. Serialization is synchronous, so it also stalled every rollout multiplexed through that interception server.
Implementation
A focused
_completion_responsehelper now:pydantic_core.to_json;web.Response;application/json; charset=utf-8, status,null, and the existingNaN/Infinitypolicy;web.json_responsewhen pydantic-core cannot encode an otherwise stdlib-compatible value, including escaped lone Unicode surrogates.Only the three successful model-completion return sites use the helper: ordinary/tool returns, user-simulator stop returns, and context-length returns after a completed turn. Error, streaming, auxiliary, state, task, and upstream client codec paths are unchanged.
Performance
Measured with a 32 MiB completion over 10-loop medians:
The retained allocation is the final response body, which must remain alive until aiohttp writes it. The peak reduction comes from eliminating the intermediate JSON string and full-body string-to-bytes encoding pass. These figures isolate response serialization rather than model or network latency.
Note
Low Risk
Narrow change to response encoding on the interception hot path with a stdlib-compatible fallback; wire shape and status behavior for errors are unchanged.
Overview
Non-streaming successful model completion responses from the interception server now go through a new
_completion_responsehelper instead ofweb.json_response(completion).The helper encodes the completion dict with
pydantic_core.to_json(inf_nan_mode="constants") into bytes and returnsweb.Responsewithapplication/json; charset=utf-8. If pydantic-core cannot serialize the payload, it falls back to the previousweb.json_responsepath.Only the three happy-path completion returns in
handle_requestuse this helper: after a @stop/limit with a prior turn, after context_length truncation with a prior turn, and on the normal tool / no-user-simulator return. Error, streaming, aux, and state routes are unchanged.Reviewed by Cursor Bugbot for commit cf1b400. Bugbot is set up for automated code reviews on this repo. Configure here.
Note
Serialize intercepted completions directly to JSON bytes using
pydantic_core.to_jsonAdds a
_completion_responsehelper in server.py that serializes completion dicts to bytes viapydantic_core.to_jsonwithinf_nan_mode="constants", returning aweb.Responsewith explicitapplication/jsoncontent type. Falls back toaiohttp.web.json_responseonPydanticSerializationError. All three completion-returning branches inhandle_request(refusal, context-length exceeded, tool/no-user-simulator) now use this helper.Macroscope summarized cf1b400.