Skip to content

fix(ts): repair overflowing JSON model output - #554

Open
Yezheng Li (yezhengli-Mr9) wants to merge 3 commits into
microsoft:mainfrom
yezhengli-Mr9:fix/repair-overflowing-json-numbers
Open

Yezheng Li (yezhengli-Mr9) wants to merge 3 commits into
microsoft:mainfrom
yezhengli-Mr9:fix/repair-overflowing-json-numbers

Conversation

@yezhengli-Mr9

@yezhengli-Mr9 Yezheng Li (yezhengli-Mr9) commented Dec 1, 2026 •

Copy link
Copy Markdown

Alternative-tool counterpart PRs

Tool PR Status (2026-12-04) Relationship / limits
Vercel AI SDK #21240 - Throw errors for NaN or Infinity values Open, not merged Closest verified component-level counterpart: rejects non-finite numbers in canonical JSON instead of letting JSON serialization silently produce null. Its fix is in canonicalization/hashing, not model-output parsing, and does not add TypeChat's bounded model-repair behavior.
LangChain.js #12150 - Keep non-finite numeric strings as strings in structured query casting Open, not merged Related finite-number guard using Number.isFinite, preserving ordinary conversions and string values. Addresses structured-query casting of "Infinity"/"-Infinity", not overflowing JSON numeric literals such as 1e400 or parse-repair retries.

These are related non-finite-number fixes, not exact equivalents. No verified alternative-tool PR was found combining rejection of overflowing JSON model-output numbers before schema validation with the existing single-repair budget. Counterpart bodies and diffs were checked; their existence is not evidence that they are merged or that this PR's behavior is already implemented elsewhere.

Review overview

Reject overflowing JSON numbers before schema validation and reuse the existing bounded parse-repair path.

Area Change / compatibility
Numeric parsing Reject nonfinite numeric results such as 1e400 before null stripping or application validation.
Repair behavior Preserve one-repair budget, prompt roles, original diagnostics, finite values, actual nulls, and strings.
API boundary Provider-neutral TypeScript translator fix; no arbitrary precision or direct-validator API change.

Validation and evidence

Check / environment Recorded result / boundary
Windows 11 / Node 24.22.1 16 tests passed across CommonJS and ESM; zero skips.
Ubuntu 24.04 / Node 24.22.1 Same 16 tests passed; changed-core strict checks passed in both module modes on both OSes.
Earlier iteration 181 selected tests passed on Node 20.19.5; separate from the supported-Node result, not a fresh 181-test rerun.
Build boundary Registry E401/TLS blocked normal restoration; fallback emission used --noCheck plus separate changed-core strict checks.
Review boundary Detail
Limitations / follow-up Offline real-validator experiments with mocked model responses. Full npm test/full-source strict build/build-all remain unverified; no inference/token-savings claim.
Evidence status Summarized from the existing PR record; no new tests or benchmarks were run for this description-only update. Detailed commands, provenance, checklists, disclosures, and caveats are preserved below.

Related issues, work items, and PRs

Reference Type Relationship / scope
Public issue / work item Tracking status No directly matching public issue or work-item link was verified in PR evidence or targeted public overflow issue search.
Original detailed description, reproduction, and repository checklist

Summary

Reject numeric model responses outside JavaScript's finite number range before schema validation, using the existing parse-failure/one-repair path. Provider-neutral; no model calls were made.

At main d61044d51da50ec89a756b9ad5fb8a023b69762f, the real TypeScript validator and translator returned successful data containing Infinity for {"value":1e400} against value: number | null. JSON.parse produces Infinity, and serialization silently validates null instead of the returned value. Negative and nested overflow behave the same way.

Commit d7d0856 checks numbers in the JSON.parse reviver, retaining the existing bounded repair path, original response diagnostics and prompt roles. Finite numbers, actual nulls and strings are unchanged. This does not introduce arbitrary precision or change direct validator APIs. README documents the behavior.

Follow-up 71e9a71 runs the deterministic regressions through both CommonJS and ESM package entry points, additionally covering overflow after a schema-error repair and rejection before null stripping/application instance validation. No further production-code defect was found in the cross-platform experiments.

Experiments and results

These are offline parser/repair experiments using the real TypeScript validator and mocked model responses, not model benchmarks. No Azure/provider calls, spending, token savings, quality gains or cost gains are claimed.

Environment actually executed Runtime/compiler Outcome
Native Microsoft Windows 11 Enterprise, version 10.0.26300, x64 Official Node 24.22.1, TypeScript 7.0.2 win32-x64 16 passed, 2 suites, 0 skipped
Docker ubuntu:24.04, /etc/os-release: Ubuntu 24.04.5 LTS, x86_64 Official Node 24.22.1, TypeScript 7.0.2 linux-x64 16 passed, 2 suites, 0 skipped

Each environment executed the same eight assertions/cases per module format:

  • Positive, negative and nested overflow fail immediately with repair disabled.
  • Overflow repairs to a finite number, preserving assistant/user roles and the original response.
  • A second overflowing response exhausts the single repair.
  • Overflow after a schema error does not grant another repair.
  • Overflow is rejected before null stripping or application instance validation.
  • Finite extremes, actual nulls and overflow-looking strings are preserved.

Changed-core strict typechecks passed in both CJS and ESM modes on both operating systems. git diff --check passed.

Earlier implementation iteration (before this follow-up): five of six new regressions failed before the reviver fix; all six then passed, with 181 tests passed across the selected prompt-layout, metadata, validator and numeric suites on Node 20.19.5. That earlier result is separate from the new 16-per-platform supported-Node result; the complete 181-test selection was not rerun here.

Reproduction

With normal development dependencies installed, from typescript/, on native Windows or Ubuntu 24.04 with the repository-pinned Node:

npm run build
node --test tests/numeric-output.test.mjs

Constrained-environment procedure actually used

Normal build/test was attempted first, then dependency restoration after missing-dependency failures. npm test initially found the obsolete global compiler because the local executable/dependencies were missing. On supported Node, npm ci --ignore-scripts --fetch-retries=0 --fetch-timeout=30000 failed E401; direct npm-registry access also failed a TLS handshake. No TLS verification, authentication, signing or hook checks were disabled. No manifests or lockfiles changed.

Official downloads worked:

  • Node archives and SHASUMS256.txt: https://nodejs.org/dist/v24.22.1/
  • Compiler packages: https://github.com/microsoft/TypeScript/releases/tag/v7.0.2

Downloaded archive SHA-256 values were checked against Node's published sums / GitHub release asset digests:

node-v24.22.1-win-x64.zip
d2046d28c2c3dcd211ac5145c0bf30e2047ef9dfb306693c8c6e2eccd8b95fa5
node-v24.22.1-linux-x64.tar.xz
6c172a9ab6718f7b801fb5a7bd486af2ee5e32758086a04b84fcce2aa77095e6
typescript.tgz
da2513f4b95176d6dde8b51aab7afe8a927656c9d277369793f77f7e59371c08
typescript-win32-x64.tgz
61fc4e141d2bc687db580e71bbfa63b9c209f0310645d82ca1b457eb3a24fd19
typescript-linux-x64.tgz
7ecad6f67377e831856367ab062ef394f21506a611405bf8ac0ff039348637d3

Extract typescript.tgz into typescript/node_modules/typescript and the matching platform package into typescript/node_modules/@typescript/typescript-{win32,linux}-x64, using --strip-components=1. Put the extracted official Node on PATH.

To reproduce the fallback without unavailable development dependencies, create these configurations in .scratch/cross-platform/ relative to the repository root:

core-cjs.json:

{
  "compilerOptions": {
    "target": "es2021",
    "lib": ["es2021"],
    "module": "node20",
    "strict": true,
    "exactOptionalPropertyTypes": true,
    "types": [],
    "noEmit": true,
    "skipLibCheck": true
  },
  "files": ["../../typescript/src/typechat.ts"]
}

core-esm.json:

{
  "extends": "./core-cjs.json",
  "compilerOptions": { "module": "es2022", "moduleResolution": "bundler" }
}

emit-cjs.json:

{
  "extends": "../../typescript/src/tsconfig.json",
  "compilerOptions": { "types": [], "rootDir": "../../typescript/src", "noCheck": true }
}

emit-esm.json:

{
  "extends": "../../typescript/src/tsconfig.esm.json",
  "compilerOptions": { "types": [], "rootDir": "../../typescript/src", "noCheck": true }
}

Then from the repository root (forward slashes below are portable Node CLI arguments; PowerShell also accepts backslashes):

node typescript/node_modules/typescript/lib/tsc.js -p .scratch/cross-platform/core-cjs.json
node typescript/node_modules/typescript/lib/tsc.js -p .scratch/cross-platform/core-esm.json
node typescript/node_modules/typescript/lib/tsc.js -p .scratch/cross-platform/emit-cjs.json
node typescript/node_modules/typescript/lib/tsc.js -p .scratch/cross-platform/emit-esm.json
node -e "require('fs').writeFileSync('typescript/dist/esm/package.json', JSON.stringify({type:'module'}))"
node --test typescript/tests/numeric-output.test.mjs

For Ubuntu, use docker run --rm ... -w /work ubuntu:24.04 sh <script> with the same source/configurations and linux-x64 packages copied/extracted inside /work, rather than running the Windows dependencies. The script runs cat /etc/os-release, uname -m, node --version, compiler --version, then the six commands above. In this execution the Windows checkout was mounted read-only as /source; source and release archives were extracted into container-local /work. The resulting test summary was tests 16; suites 2; pass 16; fail 0; skipped 0.

Environment iterations: the minimal Ubuntu image lacked xz; an initial extraction onto the Windows bind mount was also prohibitively slow. Host-side decompression to an uncompressed tar followed by container-local extraction resolved that. The shell script's Windows CRLF was normalized before execution. These were harness/setup failures, not TypeChat failures.

Verification limits: source emission used --noCheck in the fallback; only the changed core and its imports received the separate strict checks above. Full npm test, full-source strict build and workspace build-all are still not claimed. Keep this PR draft pending normal dependency-backed CI and maintainer review.

Reject numeric model output outside the finite JavaScript number range before serialization can validate it as null. Reuse the existing parse failure and bounded repair path, preserving the original response diagnostics.
Run the deterministic overflow regressions through both package formats and cover schema-error repair exhaustion plus rejection before null stripping and instance validation. Document the focused offline command.
@yezhengli-Mr9
Yezheng Li (yezhengli-Mr9) marked this pull request as ready for review December 4, 2026 22:49
Copilot AI balanced review requested due to automatic review settings December 4, 2026 22:49
@microsoft-github-policy-service

Copy link
Copy Markdown

Yezheng Li (@yezhengli-Mr9) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

Copilot AI 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.

🟢 Approval recommended

No active review issues were identified for the numeric-overflow hardening change.

No open issues 🎉

What changed in this PR

This PR hardens the TypeScript translator against overflowing JSON numbers while preserving its existing single-repair budget.

Changes:

  • Reject non-finite numbers during parsing, before validation.
  • Add offline CommonJS and ESM regressions for rejection, repair, and unchanged valid values.
  • Document numeric behavior and focused test commands.
File Description
typescript/​tests/​numeric-output.test.mjs Tests overflow handling and compatibility across both module formats.
typescript/​src/​typechat.ts Rejects non-finite numbers through a JSON parse reviver.
typescript/​README.md Explains overflow rejection, repair behavior, and regression tests.

Review effort: Balanced

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants