Skip to content

fix(server_utils): send request bodies that hold integers wider than 64 bits - #5049

Merged
cmunley1 merged 3 commits into
mainfrom
cmunley1/fingerprint-bigint-args
Nov 8, 2026
Merged

cmunley1 merged 3 commits into
mainfrom
cmunley1/fingerprint-bigint-args

Conversation

@cmunley1

@cmunley1 cmunley1 commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

server_utils.request() encodes JSON request bodies with orjson, 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. When orjson rejects the body, request() now falls back to json.dumps(separators=(",", ":")), which accepts arbitrary-precision integers. Its default ASCII escaping also sends a lone surrogate in a model-written string, which orjson rejects too and ensure_ascii=False could not encode as UTF-8. Bodies orjson accepts take the same path as before.

This PR first fixed the same orjson failure in the token-capture fingerprint. That fallback landed on main in #4128, so after the rebase this PR keeps only its test for it: a tool call with a 2**70 argument still fingerprints, matches its reserialized form, and changes when the value changes.

Validation

  • test_request_sends_a_json_body_orjson_rejects, for a 2**70 integer and a lone surrogate: both fail on main with the orjson TypeError and pass here, and the sent body round-trips through json.loads.
  • test_arguments_with_an_integer_wider_than_64_bits_still_fingerprint: passes on main and here.
  • pytest tests/unit_tests/test_server_utils.py tests/unit_tests/test_conversation_fingerprint.py: 252 passed.
  • Local review with three independent reviewers and per-finding verification. It confirmed the lone-surrogate case, fixed here. Its other confirmed finding, json.loads raising ValueError for integers over 4300 digits in simple_agent tool arguments, predates this PR and is in other files.
  • ruff check and ruff format --check (ruff 0.9.9) on the changed files: clean.

Rollouts

N/A: no environment or agent behavior changes. Requests orjson can 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

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Documentation added or updated, or N/A with justification. N/A: internal helper, no documented behavior changes.
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format checks pass). Ran ruff 0.9.9 check and format on the changed files.
  • New source files include the required Apache-2.0 SPDX header. N/A: no new files.
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

@copy-pr-bot

copy-pr-bot Bot commented Oct 24, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@cmunley1

Copy link
Copy Markdown
Contributor Author

/ok to test 3263305

@cmunley1

Copy link
Copy Markdown
Contributor Author

/review

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 24, 2026 16:46
@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:model Model servers, inference providers, and model adapters bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer labels Oct 24, 2026

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@cmunley1

Copy link
Copy Markdown
Contributor Author

/ok to test 8fca921

@cmunley1

Copy link
Copy Markdown
Contributor Author

/review

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ananthsub
ananthsub previously approved these changes Oct 26, 2026
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Oct 26, 2026
@cmunley1
cmunley1 force-pushed the cmunley1/fingerprint-bigint-args branch from 8fca921 to 0090cd3 Compare October 27, 2026 07:54
@cmunley1

Copy link
Copy Markdown
Contributor Author

/ok to test 0090cd3

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team October 27, 2026 07:55
@cmunley1

cmunley1 commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

/review

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 6, 2026 22:07

@ananthsub ananthsub left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cmunley1 could you address the merge conflicts? then we can merge in

…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]>

@ananthsub ananthsub left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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**70 tool 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/messages reply fails on the same 2**70 argument. AnthropicConverter parses the tool arguments into a dict (anthropic_converter.py:783), and _orjson_dispatch_response then encodes the reply with no fallback (base_responses_api_model.py:232), so the request returns 500. The streaming path uses json.dumps and works.
  • Reading replies. get_response_json decodes with orjson.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=str does not help: orjson does not call default for 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 as get_response_json.
  • Very long integers in tool arguments. simple_agent catches only JSONDecodeError and TypeError around json.loads (app.py:728-729). An integer with more than 4,300 digits raises ValueError and aborts the /run.

What a complete fix looks like

  1. One shared encoder. Put a function such as dumps_json_bytes(value, *, sort_keys=False) -> bytes in a low-level module. It tries orjson first. If orjson raises, it falls back to the stdlib with compact separators, ensure_ascii=True and allow_nan=False. Like the fingerprint fallback in #4128, it refuses non-str keys rather than coercing them. Then route request(), _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.
  2. 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_json and the record readers use it, so a value read back is the value that was written.
  3. Agent handling. simple_agent (and any other agent that parses tool arguments) treats ValueError from json.loads like a decode error, so the model sees an invalid-arguments tool output and the /run continues.
  4. 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 run on 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")

Comment on lines +447 to +449
# 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")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
# 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.

@ananthsub
ananthsub added this pull request to the merge queue Nov 7, 2026
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42316997589

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 7, 2026
@cmunley1
cmunley1 added this pull request to the merge queue Nov 7, 2026
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42389151177

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 7, 2026
@cmunley1
cmunley1 added this pull request to the merge queue Nov 8, 2026
@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42429819651

@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42430017962

Merged via the queue into main with commit de37a6d Nov 8, 2026
104 of 111 checks passed
@cmunley1
cmunley1 deleted the cmunley1/fingerprint-bigint-args branch November 8, 2026 00:47

This branch was previously deployed

1 inactive deployment
public — 277101ae Deployed Nov 6, 2026 by copy-pr-bot[bot] via release / finalize / notify #10772
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:model Model servers, inference providers, and model adapters bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants