跳到正文
DEV Community· uehara·· 47 分鐘前AI 評分54

Pydantic 與 Zod 對相同正整數規則得出不同結果,差異源於驗證前的 JSON 解析

Same positive-integer rule, different precision: Pydantic and Zod split because JSON is read differently before validation

AI 導讀

作者公司的 AI 員工 Akari 用 Pydantic 和 Zod 執行相同的「quantity 為正整數」驗證,11 個輸入中有 2 個結果不同,差異來自驗證前的 JSON 解析。

正文

This is part 1 of the series "Akari Tried It." Akari, an AI employee at my company, runs a piece of software or a service on her own machine and reports what she found. Sources are the official documentation and public repositories of what she tried.

Series contents

  1. Same positive-integer rule, different precision: Pydantic and Zod split because JSON is read differently before validation (this article)
  2. Telling a voice AI to stop does not cancel the booking behind it (coming soon)
  3. A skill scanner score is not proof of bad intent: three tiny skills through SkillSpector (coming soon)
  4. In EmDash, *.example.com also lets a plugin reach example.com: eight host names through the real check (coming soon)

{"quantity": 900.0} passes Zod and fails Pydantic. {"quantity": 9007199254740993} passes Pydantic's validation and fails Zod's. Both libraries were given the same rule, "quantity is a positive integer", and the same JSON file. Akari, an AI employee at my company, ran eleven inputs through both and found these two splits. Neither validator is at fault. The gap opens earlier, when each language reads the JSON: JavaScript numbers lose integer precision above 2^53, so 9007199254740993 becomes 9007199254740992, and Python keeps 900.0 as a float while JavaScript has no separate float type. She then built two fixes and checked that each one makes the answers match.

The two inputs that split

The rule, written once for each library:

class Order(BaseModel):
    model_config = ConfigDict(strict=True, extra="forbid")
    quantity: int = Field(gt=0)
const Order = z.strictObject({ quantity: z.int().positive() });

Strict mode stops Pydantic from converting types, so "900" and true are rejected, and extra="forbid" and z.strictObject both reject unknown fields. A value that passes is then checked against a capacity of 1,000, a number chosen for this test: above it is "over capacity", otherwise "accepted". A value that fails validation is "rejected".

Akari ran all eleven inputs through both sides and printed the answers side by side.

Terminal output of compare.mjs in original mode. For each of the 11 cases it shows the Python answer, the TypeScript answer and whether they match. 900.0 is rejected by Python and accepted by TypeScript; 9007199254740993 is over_capacity in Python and rejected in TypeScript. Those two rows are marked DIFF and highlighted. The last line reads "9/11 same, 2 different". Akari stands on the right, pointing at the output

Nine of the eleven matched. Wrong types, a missing field and an extra field were rejected on both sides. Only the two boundary inputs split:

Input Python (Pydantic) TypeScript (Zod)
900.0 rejected accepted
9007199254740993 over capacity rejected

These inputs were picked to sit on the edges, so "2 out of 11" says nothing about how often this happens with real traffic.

The difference starts before validation

Neither library is wrong. The values were already different by the time the validators saw them. Akari printed what each language's standard JSON reader returns for the two inputs.

Terminal output of read-check.py and read-check.mjs. Python reads 900.0 as the float 900.0 and 9007199254740993 as the exact int 9007199254740993; the 900.0 line is highlighted. JavaScript reads 900.0 as the number 900, a safe integer, and reads 9007199254740993 as 9007199254740992 with Number.isSafeInteger false; that line is highlighted too. Akari stands on the right with a hand over her mouth

  • 900.0: Python's json module returns a float. In strict mode Pydantic accepts only an actual int for an int field, so the float is rejected. JavaScript has one number type, so 900.0 and 900 are the same value, and Zod sees a plain integer.
  • 9007199254740993: Python keeps the exact integer, it passes validation, and the capacity check flags it. JavaScript numbers cannot represent every integer above 9007199254740991 (Number.MAX_SAFE_INTEGER), so JSON.parse rounds it to 9007199254740992. The Zod docs say z.int() "restricts to safe integer range", and the rounded value is outside it.

Both libraries behave as documented. The rule "positive integer" left two questions open: is a number written with a decimal point allowed, and how large can it be?

Two fixes, both tested

Answering those two questions should make the sides agree. There are two reasonable answers to the first, so Akari built both. Each fix also adds the same upper bound, 1,000,000, on both sides, so large integers are stopped before the languages can disagree about them. Each fix was run against the original eleven inputs plus three more aimed at the fixes: 9e2, 1000000 and 1000001.

Fix A: accept any whole number

Treat 900.0 as 900. Only the Python side changes: a Pydantic BeforeValidator, which runs before Pydantic's own validation, turns a float with no fractional part into an int, and strict mode checks the result.

def float_to_int_if_whole(v):
    if isinstance(v, float) and v.is_integer():
        return int(v)
    return v

quantity: Annotated[int, BeforeValidator(float_to_int_if_whole), Field(gt=0, le=1_000_000)]

Terminal output of compare.mjs in fix-integer-value mode. The original inputs show "11/11 same, 0 different" and the three extra inputs show "3/3 same, 0 different". 900.0 and 9e2 are accepted on both sides; 9007199254740993 is rejected on both sides. Those rows are highlighted. Akari stands on the right with a thumbs up

All fourteen answers match. 900.0 and 9e2 are accepted on both sides, and 9007199254740993 is rejected on both sides: it is above the 1,000,000 bound, and on the TypeScript side the rounded value is also outside the safe integer range.

Fix B: accept digits only

Reject 900.0 on both sides. Only the TypeScript side changes. The reviver passed to JSON.parse receives the raw source text of each primitive in context.source. If the text for quantity has a decimal point or an exponent, the reviver replaces it with a string, which Zod then rejects.

JSON.parse(text, function (key, value, context?: { source?: string }) {
  if (key === 'quantity' && typeof value === 'number' && !/^-?\d+$/.test(context?.source ?? '')) {
    return `not-digits:${context?.source}`;
  }
  return value;
});

Terminal output of compare.mjs in fix-digits-only mode. The original inputs show "11/11 same, 0 different" and the three extra inputs show "3/3 same, 0 different". 900.0, 9e2 and 9007199254740993 are rejected on both sides; those rows are highlighted. Akari stands on the right, hand on her chin, thinking

All fourteen match again. The only difference from fix A is that 900.0 and 9e2 are now rejected on both sides.

What a person still decides

The test shows that either fix works. Which one to use is a business rule, not a library setting:

  • Do any of your senders write quantities like 900.0? If so, fix A. If you can make them send digits only, fix B.
  • What is the real upper bound? The 1,000,000 here was chosen for this test.
  • Are large identifiers, such as order numbers, being sent as numbers? Send them as strings instead.

When you ask an AI to move code from one language to another, ask it for this kind of table too: the same JSON run through the old side and the new side. The rows marked DIFF are what a person needs to look at.

Setup and cost

  • Who ran it: Akari, an AI employee at my company
  • Python 3.14.2 with Pydantic 2.14.4; Node.js 24.22.2 with Zod 4.6.7, running the .mts file directly with Node's type stripping
  • Where: a local Mac, with the libraries installed into a scratch folder only
  • Sources: the official docs for Pydantic strict mode, the Pydantic conversion table, Pydantic validators, the Zod API, and MDN on JSON.parse
  • Licenses: Pydantic and Zod are both MIT licensed
  • Cost: zero. No paid API, no new subscription

In this series, Akari, our AI employee, runs software and services herself and separates what works as-is from what still needs a human decision.
If you are interested, please like and follow.

Our products are listed at https://www.eln.ne.jp/products


EarthLink Network builds its own products to run the whole company on AI — each one born from a need along the way. See the full index of what we build:

→ The 18 products EarthLink Network builds in-house

For more about the company and each product, visit www.eln.ne.jp.

來源:DEV Community · dev.to