Repository navigation
fix(server_utils): send request bodies that hold integers wider than 64 bits - #5049
Conversation
|
/ok to test 3263305 |
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP
LGTM — no reliability concerns. Reviewed the serialization fallback, affected lineage and terminal-attribution paths, and the wide-integer regression test. Previously accepted content retains the unchanged orjson path; the new test checks reserialization equivalence and sensitivity to integer-value changes.
Validation was source inspection only; tests were not executed.
Note: formal approval is not available for this request, so this review is posted as a comment only.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
|
/ok to test 8fca921 |
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP
LGTM — no reliability concerns.
Follow-up review against the previously reviewed commit found no introduced regressions. Reviewed the new request-body fallback, parsed tool-argument callers, and transport retry paths. Previously accepted bodies retain the unchanged orjson path; fallback bytes are prepared once and reused across attempts. The new regression test checks exact wide-integer serialization, UTF-8 content, and the JSON content type.
The earlier fingerprint fallback and its regression assertions are unchanged. The prior review had no findings to carry forward. All four changed files were inspected; new-defect discovery remained limited to changes since that review.
Validation was source inspection only; tests were not executed.
Note: formal approval is not available for this request, so this review is posted as a comment only.
Review generated by codex. This was a findings-only review. Request a full review with /review reset=true.
8fca921 to
0090cd3
Compare
|
/ok to test 0090cd3 |
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP
LGTM — no concerns found in the follow-up scope.
I checked the request-body fallback, its callers, and the traced and retry paths. Bodies accepted by orjson retain the same encoding path, and fallback bytes are prepared once before transport retries. The regression assertions check exact wide-integer and lone-surrogate encoding, Unicode round-tripping, and the JSON content type. The retained fingerprint test checks reserialization equivalence and sensitivity to integer-value changes.
The latest bot review had no findings to carry forward. Its reviewed source tree wasn't available, so I couldn't reconstruct the complete inter-review delta; discovery remained limited to identifiable subsequent changes and their directly affected paths. One delegated report wasn't available, so I completed its serialization and caller checks directly.
Validation was source inspection only; I didn't execute tests.
Review generated by codex. This was a findings-only review. Request a full review with /review reset=true.
…r than 64 bits The fingerprint fallback for integers beyond orjson's 64-bit range landed on main in #4128. This keeps the test that a tool call whose arguments hold such an integer still fingerprints, matches its reserialized form, and changes when the value changes. Signed-off-by: Christian Munley <[email protected]>
…64 bits The outbound JSON body in request() is encoded with orjson, which rejects integers outside the 64-bit range. A tool call whose arguments carry one therefore failed before it was sent, the same way the token-capture fingerprint did. Fall back to the stdlib encoder, compact and non-ASCII preserved, which accepts them. Signed-off-by: Christian Munley <[email protected]>
With ensure_ascii=False the fallback still raised UnicodeEncodeError for a lone surrogate, which orjson also rejects and a model can write into a tool argument. The default escaping sends it, and any other non-ASCII text, as valid JSON. Signed-off-by: Christian Munley <[email protected]>
2af64eb to
277101a
Compare
ananthsub
left a comment
There was a problem hiding this comment.
Thanks @cmunley1, this fixes a real gap. Before this change, one tool call whose arguments hold an integer wider than 64 bits made request() raise before sending, and simple_agent does not catch that, so the whole /run aborted. I rebased the branch onto main after #5215 moved request() from server_utils to nemo_gym/client/http_client.py. The diff is the same change at the new paths.
Approving this as the first step. It fixes the request side of the motivating case, which was the most common failure. Wide integers still break other places in Gym, and the section below describes what a complete fix looks like so we can track it as a follow-up.
What we checked
- We ran the motivating flow live through a resources server. A
2**70tool argument is sent, FastAPI and pydantic parse it exactly, and the reply comes back intact. - The new request test fails on the old code for both cases, and fails again if the fallback drops its separators, uses
ensure_ascii=False, or loses the content type header. - The body is encoded once, before the traced and untraced paths split, so retries and tracing reuse the same bytes.
- Bodies that orjson accepts take the same path as before.
The one inline comment proposes allow_nan=False and a reworded comment for the fallback.
Where wide integers still fail
orjson raises for integers wider than 64 bits and for lone surrogates when it encodes. When it decodes, it silently turns a wide integer into a float. Gym calls orjson directly in many places, so this PR fixes one of several boundaries:
- Model server replies. The non-streaming Anthropic
/v1/messagesreply fails on the same2**70argument.AnthropicConverterparses the tool arguments into a dict (anthropic_converter.py:783), and_orjson_dispatch_responsethen encodes the reply with no fallback (base_responses_api_model.py:232), so the request returns 500. The streaming path usesjson.dumpsand works. - Reading replies.
get_response_jsondecodes withorjson.loads(http_client.py:811).{"a":1180591620717411303424}comes back as{"a": 1.1805916207174113e+21}, with no error. Verify replies are read through this function. With this PR a value can now be sent exactly, but it can still come back changed. - Records on disk. The rollout store (rollout_store.py:274, L601, L639) and the model call capture (model_call_capture.py:207) write with
orjson.dumps.default=strdoes not help: orjson does not calldefaultfor an integer that overflows. A verifier result or metadata field that holds a wide integer fails at write time, and the readers have the same float problem asget_response_json. - Very long integers in tool arguments.
simple_agentcatches onlyJSONDecodeErrorandTypeErroraroundjson.loads(app.py:728-729). An integer with more than 4,300 digits raisesValueErrorand aborts the/run.
What a complete fix looks like
- One shared encoder. Put a function such as
dumps_json_bytes(value, *, sort_keys=False) -> bytesin a low-level module. It tries orjson first. If orjson raises, it falls back to the stdlib with compact separators,ensure_ascii=Trueandallow_nan=False. Like the fingerprint fallback in #4128, it refuses non-str keys rather than coercing them. Then routerequest(),_orjson_dispatch_response, the rollout store and the capture writers through it. A body that orjson accepts keeps its exact bytes. Only bodies that raise today take the new path, so no existing record or hash changes. - One shared decoder. Its counterpart keeps orjson for the common case. It switches to the stdlib when the bytes hold something orjson would change, such as a run of 20 or more digits or an escaped surrogate.
get_response_jsonand the record readers use it, so a value read back is the value that was written. - Agent handling.
simple_agent(and any other agent that parses tool arguments) treatsValueErrorfromjson.loadslike a decode error, so the model sees an invalid-arguments tool output and the/runcontinues. - Round-trip tests at each boundary. A wide integer and a lone surrogate go through each path: a tool call to a resources server and back, the non-streaming and streaming model server replies, and a rollout record written then read. Each test checks that the value comes back exact, not just that nothing raises.
PR text
The rebase left the PR text behind the code. Could you:
- retitle to
fix(client): send request bodies that hold integers wider than 64 bits; - point the description at
nemo_gym.client.http_client.request()and the current test paths (tests/unit_tests/client/test_http_client.py,tests/unit_tests/models/test_conversation_fingerprint.py); - add an issue link, or a line saying none is needed;
- tick the pre-commit box only after a
pre-commit runon the changed files?
Optional: nothing pins the orjson fast-path bytes today. The existing body test is pure ASCII, so a regression that always used the stdlib encoder would pass the suite. A one-case test with a non-ASCII body that orjson accepts would cover it:
async def test_request_keeps_orjson_bytes_for_a_body_orjson_accepts(self, monkeypatch: MonkeyPatch) -> None:
client = self._mock_global_client(monkeypatch, ClientOSError(), failures=0)
await nemo_gym.client.http_client.request("POST", "https://example.test", json={"n": 2**64 - 1, "note": "ü"})
assert client.request.call_args.kwargs["data"] == '{"n":18446744073709551615,"note":"ü"}'.encode("utf-8")| # orjson rejects integers wider than 64 bits and lone surrogates, which a model can write into a | ||
| # tool argument. The stdlib encoder escapes non-ASCII text, so both still produce valid UTF-8. | ||
| kwargs["data"] = json.dumps(body, separators=(",", ":")).encode("utf-8") |
There was a problem hiding this comment.
This fallback writes NaN and Infinity as bare tokens, which are not valid JSON. orjson writes null for the same values. So a body that holds a wide integer and a NaN goes out as {"id":1180591620717411303424,"x":NaN}, while the same NaN without the wide integer goes out as null. simple_agent parses tool arguments with json.loads, which accepts NaN, so a model can produce such a body. A strict parser rejects it (orjson.loads fails with "unexpected character"), and a receiver that echoes the value through Starlette's JSONResponse returns 500.
allow_nan=False makes that rare body raise, as it did before this change, rather than send invalid JSON. No caller of request() catches TypeError, so the ValueError it raises changes nothing for callers. The suggestion also rewords the comment: except TypeError catches every orjson encode failure, not only the two causes it names. And the output is ASCII-only, but a strict parser can still reject an escaped lone surrogate, so "valid UTF-8" says less than it seems to.
| # orjson rejects integers wider than 64 bits and lone surrogates, which a model can write into a | |
| # tool argument. The stdlib encoder escapes non-ASCII text, so both still produce valid UTF-8. | |
| kwargs["data"] = json.dumps(body, separators=(",", ":")).encode("utf-8") | |
| # orjson rejects some values a model can write into a tool argument, such as integers wider than | |
| # 64 bits and lone surrogates. The stdlib encoder writes them as ASCII-only JSON. orjson would send | |
| # NaN and Infinity as null, so allow_nan=False raises for them rather than sending invalid JSON. | |
| kwargs["data"] = json.dumps(body, separators=(",", ":"), allow_nan=False).encode("utf-8") |
With this suggestion applied, the two new test cases still pass and ruff is clean.
The same fallback is needed in other places that encode with orjson, such as the model server's non-streaming replies and the rollout store. The review summary describes a shared encoder for the complete fix. Once that exists, this fallback should call it rather than keep its own copy.
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42316997589 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42389151177 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42429819651 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42430017962 |
What does this PR do?
server_utils.request()encodes JSON request bodies withorjson, which rejects integers outside the 64-bit range (TypeError: Integer exceeds 64-bit range). A body that carries one, for example a tool call whose parsed arguments hold a long numeric ID, fails before it is sent. Whenorjsonrejects the body,request()now falls back tojson.dumps(separators=(",", ":")), which accepts arbitrary-precision integers. Its default ASCII escaping also sends a lone surrogate in a model-written string, whichorjsonrejects too andensure_ascii=Falsecould not encode as UTF-8. Bodiesorjsonaccepts take the same path as before.This PR first fixed the same
orjsonfailure in the token-capture fingerprint. That fallback landed onmainin #4128, so after the rebase this PR keeps only its test for it: a tool call with a2**70argument still fingerprints, matches its reserialized form, and changes when the value changes.Validation
test_request_sends_a_json_body_orjson_rejects, for a2**70integer and a lone surrogate: both fail onmainwith theorjsonTypeErrorand pass here, and the sent body round-trips throughjson.loads.test_arguments_with_an_integer_wider_than_64_bits_still_fingerprint: passes onmainand here.pytest tests/unit_tests/test_server_utils.py tests/unit_tests/test_conversation_fingerprint.py: 252 passed.json.loadsraisingValueErrorfor integers over 4300 digits insimple_agenttool arguments, predates this PR and is in other files.ruff checkandruff format --check(ruff 0.9.9) on the changed files: clean.Rollouts
N/A: no environment or agent behavior changes. Requests
orjsoncan encode are unchanged. A request that used to fail before sending is now sent.Compatibility and benchmark impact
None. The fallback only runs where the old code raised.
Checklist
pre-commit run --all-files) (so CI lint/format checks pass). Ran ruff 0.9.9 check and format on the changed files.git commit -s) (so the DCO check passes).