json.loads Accepted timeout=NaN in My Agent's Tool Call
Python's json.loads accepts NaN, Infinity and 1e999 even though the JSON spec forbids them, so a tool call like {"cmd": ["sleep", "3"], "timeout": NaN} passes straight through to subprocess.run(timeout=nan), which never
Python's json.loads accepts NaN, Infinity and 1e999 even though the JSON spec forbids them, so a tool call like {"cmd": ["sleep", "3"], "timeout": NaN} passes straight through to subprocess.run(timeout=nan), which never times out. Validate tool arguments with a Pydantic model that sets allow_inf_nan=False and an upper bound, and the bad call is rejected in 0.00 s before anything runs.
This story was written with the assistance of an AI writing program. Every number below comes from CPython 3.14.9 and Pydantic 2.14.1 (pydantic-core 2.50.1) on Linux, and each script ran twice with the same results.
This is the guard I now put in front of every agent tool that takes a number:
import json, subprocess
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class ShellArgs(BaseModel):
model_config = ConfigDict(allow_inf_nan=False, extra="forbid")
cmd: list[str]
timeout: float = Field(gt=0, le=60)
def run_shell(raw_arguments: str) -> str:
try:
args = ShellArgs.model_validate_json(raw_arguments)
except ValidationError as e:
return json.dumps({"error": e.errors(include_url=False)[0]["msg"]})
p = subprocess.run(args.cmd, timeout=args.timeout, capture_output=True, text=True)
return json.dumps({"rc": p.returncode})
The rest of this post is why both settings are needed, and what each non-finite value does once it reaches real code.
Where the number comes from
Tool arguments arrive as a JSON string written by the model. In the last three posts I looked at agent tools that outlive their timeout: subprocess.run orphans, ThreadPoolExecutor threads, asyncio.gather siblings. All of those assumed the timeout value was sane. This time I tested what happens when it is not.
I have not seen a hosted model emit NaN on its own. But the arguments come from text the model writes, and that text is shaped by user input, retrieved pages and other tool output. A single prompt-injected "timeout": 1e999 is enough. The parser is the first line of defense, and it lets these values through.
What the parser and the tools did
One run of exp2.py. The child process sleeps 3 s, so a working 1 s timeout should fire at 1.00 s:
subprocess.run(timeout=inf): returned after 3.03s
subprocess.run(timeout=nan): returned after 3.03s
subprocess.run(timeout=1.0): TimeoutExpired after 1.00s: Command '['sleep', '3']' timed out after 1.0 seconds
asyncio.wait_for(timeout=inf): returned after 3.00s
asyncio.wait_for(timeout=nan): ValueError after 0.00s: cannot convert float NaN to integer
asyncio.wait_for(timeout=1.0): TimeoutError after 1.00s:
time.sleep(inf): OverflowError after 0.00s: timestamp out of range for C PyTime_t
time.sleep(nan): ValueError after 0.00s: Invalid value NaN (not a number)
json.loads returned nan for NaN and inf for both Infinity and 1e999, with no warning. A plain Pydantic model with timeout: float accepted all three as well.
subprocess.run is the dangerous one. With timeout=nan it waited for the child to finish, the same as having no timeout at all. With a 3 s child that just looks slow. With a command that hangs, the agent hangs too. The asyncio and time.sleep paths fail loudly, which is better, but you get a ValueError or OverflowError deep inside the tool instead of a clear message back to the model.
Why a bound alone is not enough
The obvious fix is Field(gt=0), and it is only half a fix. NaN compares false to everything, so any bound rejects it. Infinity only fails the side it is on. From bounds.py:
A {"budget": Infinity}: accepted inf
B {"budget": -Infinity}: accepted -inf
nan >= 0: False | nan <= 100: False
Model A had only ge=0, and model B had only le=100. A lower bound alone lets Infinity through, and that is exactly the value that turns a timeout off. You need both an upper bound and allow_inf_nan=False. The bound states what is reasonable. The flag says what the field means: a finite number. With both set, fix.py printed Input should be a finite number for NaN and for 1e999, and a normal call with timeout: 5 still ran.
If you are not using Pydantic
The standard library can do it, but there are two hooks and you need both. parse_constant catches the literals NaN, Infinity and -Infinity. It does not catch 1e999, because that is a valid-looking number that only overflows to inf during float conversion. For that you need parse_float:
{"timeout": 1e999} parse_constant only: {'timeout': inf}
{"timeout": 1e999} parse_constant + parse_float: ValueError: non-finite JSON number 1e999
It is easy to write the first hook, test it with NaN, and stop there.
The return path has the same hole
It also happens in the other direction. If a tool result contains float("nan"), for example an average over zero rows, json.dumps writes {"balance": NaN, "ok": true}. That is not valid JSON. Whether the model API accepts it depends on the client: httpx refused to build the request (Out of range float values are not JSON compliant), so the tool call fails at send time and not at the line that produced the NaN. Using json.dumps(..., allow_nan=False) in your tool-result serializer moves the error to where the NaN came from.
Takeaways
-
json.loadsacceptsNaN,Infinityand1e999even though the JSON spec does not allow them. -
subprocess.run(timeout=nan)andtimeout=infbehave like no timeout at all. - A lower bound alone still lets
Infinitythrough. Useallow_inf_nan=Falseplus an upper bound. - In stdlib-only code you need both
parse_constantandparse_float. - Serialize tool results with
allow_nan=Falseso a NaN fails where it was created.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.