Skip to content

Request: Add support for non-finite values in schema and data #1239

Closed

Description

@mjcarman

YAML supports non-finite values (.inf, -.inf, and .nan). I'd like to be able to include these values in schemas (if only to forbid them) and validate files which might contain them. The validators for numeric checks don't support non-finite values because they use BigDecimal in numeric comparisons; BigDecimal doesn't define representations for Infinity and NaN.

Activity

  1. justin-tay commented on Apr 2, 2026

    @justin-tay
    Collaborator

    So it's not terribly clear to me what is the appropriate behavior here. Do you know of a JSON Schema library that handles YAML in the way you propose? Can you check in https://github.com/json-schema-org/json-schema-spec whether what you are proposing aligns with the spec? Thanks!

    Schema

    For use in schema, from the specification 4.1. JSON Document

    JSON Schema is only defined over JSON documents. However, any document or memory structure that can be parsed into or processed according to the JSON Schema data model can be interpreted against a JSON Schema, including media types like CBOR.

    Since JSON has no equivalent for YAML's .inf, -.inf, and .nan, I somewhat think a parse error is appropriate if you are trying to load a schema with such values.

    Data

    For use in data, from the specification 4.2.3 Non-JSON Instances

    It is possible to use JSON Schema with a superset of the JSON Schema data model, where an instance may be outside any of the six JSON data types.

    In this case, annotations still apply; but most validation keywords will not be useful, as they will always pass or always fail.

    A custom vocabulary may define support for a superset of the core data model. The schema itself may only be expressible in this superset; for example, to make use of the "const" keyword.

    It sounds like it should be possible to load such data instances, but the behavior of standard validators for such values are undefined.

  2. mjcarman commented on Apr 2, 2026

    @mjcarman
    Author

    Perl's JSON::Schema::Tiny and Python's jsonschema both handle Infinity and NaN (though I'd argue they don't handle const: .nan correctly).

    If the position of the project is that json-schema-validator should only handle YAML which is strictly compatible with JSON then not supporting Infinity and NaN is a reasonable position, but it makes the library less useful. What I'm asking for isn't even really a "superset" of the data model per §4.2.3; it's just extension of the supported values for the number data type. From that perspective, the behavior of numeric validators isn't undefined. e.g.

    minimum:
    The value of minimum MUST be a number, representing an inclusive lower limit for a numeric instance.

    If the instance is a number, then this keyword validates only if the instance is greater than or exactly equal to minimum.

    That's still true for Infinity and NaN.

    While JSON doesn't support Infinity and NaN, Jackson does. Its JsonNode class (really its DoubleNode sub-class) supports them, and thus a call to Schema.validate() could encounter them. In fact, json-schema-validator does support ±Infinity in min/max validators. It doesn't support them in other numeric validators, though, and doesn't handle NaN values in any of them. In those situations they trigger an exception. I'd argue that the library should be more robust and not throw an exception.

  3. justin-tay commented on Apr 2, 2026

    @justin-tay
    Collaborator

    I do agree that it probably shouldn't.throw an exception and that some changes are required.

    That said ultimately the validator is an implementation of a spec and I don't want a case where after implementing this in this way someone comes and creates another issue and says this implementation is not according to the spec. So can you check in https://github.com/json-schema-org/json-schema-spec whether what you are proposing aligns with the spec?

    If the behavior in the spec is undefined, then we can see what other validators do eg. ajv with strictNumbers true/false.

  4. mjcarman commented on Apr 2, 2026

    @mjcarman
    Author

    So can you check in https://github.com/json-schema-org/json-schema-spec whether what you are proposing aligns with the spec?

    The JSON schema spec makes no mention of infinity or NaN. That's not surprising given that it's purpose is "validating and annotating JSON documents" and JSON explicitly doesn't define representations for Infinity or NaN. So those values are definitely invalid in a JSON document, but that doesn't mean JSON Schema can't support them. The sections of the spec you quoted confirm that:

    • "an instance may be outside any of the six JSON data types"
    • "most validation keywords will not be useful, as they will always pass or always fail"

    That clearly allows other data types (if additional values can even be considered a distinct type) and intends that keywords should operate on those data types, just without any particular guarantees. The spec doesn't give any examples of what they had in mind with respect to additional data types, but I imagine it would be something more significantly different from existing data types like "set" or "complex number."

    Infinity and NaN are just two more values that a number could take, and all of the validations for numbers are well-defined with respect to those values. Infinity is bigger than any other value, -Infinity is smaller than any other value, and NaN would fail any numeric comparison because it's not bigger, smaller, or equal to any other value. It's the "...or always fail" the spec mentioned; the key word being "fail."

    For reference, if you:

    You'll get the following test errors due to exceptions:

    [ERROR]   NonFiniteTest.nonFiniteConst:41 » JsonNode 'DoubleNode' method `decimalValue()` cannot convert value Infinity to `java.math.BigDecimal`: value non-Finite ('NaN')
    [ERROR]   NonFiniteTest.nonFiniteDataExclusiveMinMax:92 » NumberFormat Character N is neither a decimal digit number, decimal point, nor "e" notation exponential mark.
    [ERROR]   NonFiniteTest.nonFiniteDataMinMax:76 » NumberFormat Character N is neither a decimal digit number, decimal point, nor "e" notation exponential mark.
    [ERROR]   NonFiniteTest.nonFiniteDataMultipleOf:107 » NumberFormat Character I is neither a decimal digit number, decimal point, nor "e" notation exponential mark.
    [ERROR]   NonFiniteTest.nonFiniteEnum:59 » Schema tools.jackson.databind.exc.JsonNodeException: 'DoubleNode' method `decimalValue()` cannot convert value Infinity to `java.math.BigDecimal`: value non-Finite ('NaN')
    

    The request and PR is to make those validators robust so that they don't throw exceptions when they encounter an Infinity or NaN value. That's it. No new behavior that goes beyond the JSON schema specification, just robust code. As I said before, the validators for minimum, maximum, exclusiveMinimum and exclusiveMaximum handle ±Infinity today. Nobody thought to make enum, const, and multipleOf handle them, though, and nobody added guards to catch a NaN. My PR is to fill in those misses.

  5. justin-tay commented on Apr 2, 2026

    @justin-tay
    Collaborator

    Can you open an issue in https://github.com/json-schema-org/json-schema-spec and discuss what the folks over there think about this?

    Actually what I think should happen is that "type": "number" should fail as it is not a valid JSON number and consequently any validator that expects a number should skip validation like in the case where the instance is actually a string instead of a number. eg https://www.jsonschemavalidator.net/s/xbD8xTT2.

    Possibly the following will need a change to ensure that these values aren't considered as numbers

    public static boolean isNumber(JsonNode node, SchemaRegistryConfig config) {
    if (node.isNumber()) {
    return true;
    } else if (config.isTypeLoose()) {
    if (TypeFactory.getValueNodeType(node, config) == JsonType.STRING) {
    return Strings.isNumeric(node.asString());
    }
    }
    return false;
    }

  6. mjcarman commented on Apr 3, 2026

    @mjcarman
    Author

    Can you open an issue in https://github.com/json-schema-org/json-schema-spec and discuss what the folks over there think about this?

    No. The authors of the JSON schema specification have known about the potential for infinity and NaN values for as long as JSON schema has existed. If they haven't come out with a hard and explicit position on the topic by now, my asking isn't going to change anything. Between reading the current draft of the spec and some of the discussion in their issue tracker, it's clear to me that they are trying to walk a fine line between a) keeping the JSON schema specification strictly compatible with the JSON specification, and b) allowing and intending for JSON schema to be useful and used to validate things other than JSON.

    From the current draft of jsonschema-core (i.e. not 2020-12):

    Note that JSON Schema extensions are free to define their own extended type system.
    [...]
    An extension may define support for a superset of the core data model.

    So at worst they'd consider supporting infinity and NaN as an extension, which is a perfectly acceptable thing to do.

    Actually what I think should be that type: number should fail as it is not a valid JSON number and consequently any validator that expects a number should skip validation like in the case where the instance is actually a string instead of a number.

    FOR THE THIRD TIME: json-schema-validator already supports Infinity, just incompletely. If strict compliance with JSON is your policy you should remove that support from the implementation. Whatever you do, the implementation should robustly handle Infinity and NaN values without throwing an exception.

    I think having a configuration option to opt in/out of strict JSON type compliance is a good idea. Hell, I might even be convinced to implement it and submit a pull request, but right now I just want it to not throw exceptions.

  7. justin-tay commented on Apr 3, 2026

    @justin-tay
    Collaborator

    Support means that there is a defined behavior and not due to incidental behavior due to how it is currently implemented. Strictly speaking there is no support for NaN and Infinity in JSON for numeric values and you should define it as strings with specific formats like what they do over at OpenAPI.

    As it stands your pull request can only be reviewed once Jackson Dataformats Text releases the relevant changes. And even then I am not inclined to support it as-is because the behavior doesn't seem consistent with the spec. Ie. these aren't considered number types and all keywords that expect number types should skip processing. It is fine if const and enum work out of the box for comparisons.

    The line the spec authors seem to be saying is that you are going to need custom keywords/validators if you intend to process these as-is and you can write custom validators with this implementation so you shouldn't expect any built-in support for these values here, but you can expect that it shouldn't be a case where you can't write a custom implementation because some part of the library is throwing an exception.

  8. mjcarman commented on Apr 3, 2026

    @mjcarman
    Author

    Support means that there is a defined behavior and not due to incidental behavior due to how it is currently implemented. Strictly speaking there is no support for NaN and Infinity in JSON for numeric values and you should define it as strings with specific formats like what they do over at OpenAPI.

    My source data is YAML, not JSON. json-schema-validator advertises itself as supporting YAML. YAML documents may contain .inf and .nan. I am not the author of those documents; I am the consumer who needs to validate them. My validation needs to account the possibility that a user included .inf or .nan in a document. For my current purposes I'd be content if json-schema-validator (consistently!) reported "fail" for such instances, but it doesn't. Depending on which value appears where, it might might pass, fail, or throw an exception. From my perspective the current behavior with respect to those values is completely incidental and not well-defined at all.

    As it stands your pull request can only be reviewed once Jackson Dataformats Text releases the relevant changes.

    That's fair; I'm just trying to get this PR in motion so I don't have to wait them to release, then start this process, then wait for you to release before getting the thing I actually need. The test is the only part that depends on jackson-dataformats-yaml 3.2. I don't know if there's a way to mark it as an expected failure for earlier versions. I could remove it from the PR, but I've been writing code for long enough to believe that there should always be tests.

    And even then I am not inclined to support it as-is because the behavior doesn't seem consistent with the spec.

    Then the current behavior isn't consistent with the spec. Again, I'm really just fixing exceptions.

    Ie. these aren't considered number types and all keywords that expect number types should skip processing.

    These changes seem to get you what you want; I'm happy to add them to the PR:

    public static boolean equalsToSchemaType(...) {
        SchemaRegistryConfig config = schemaContext.getSchemaRegistryConfig();
        JsonType nodeType = TypeFactory.getValueNodeType(node, config);
        if (nodeType != schemaType) {
            //...
        }
        else if (config.isStrict("type", Boolean.TRUE) && schemaType == JsonType.NUMBER && node.isNumber() && ((NumericNode) node).isNaN()) {
            return false;
        }
        return true;
    }
    
    public static boolean isNumber(JsonNode node, SchemaRegistryConfig config) {
        if (node.isNumber()) {
            if (config.isStrict("type", Boolean.TRUE) && ((NumericNode) node).isNaN()) {
                return false;
            }
            return true;
        } else if (config.isTypeLoose()) {
            if (TypeFactory.getValueNodeType(node, config) == JsonType.STRING) {
                return Strings.isNumeric(node.asString());
            }
        }
        return false;
    }

    Defaulting the isStrict() calls to Boolean.FALSE would better match the existing behavior of the min/max validators and what appears to be the default value for strictness settings, but I don't really care as long as it's possible to toggle and the code is robust when strict types = false.

    It is fine if const and enum work out of the box for comparisons.

    They don't. If they did I wouldn't have touched them in my PR.

    you can expect that it shouldn't be a case where you can't write a custom implementation because some part of the library is throwing an exception.

    Some part of the library is throwing an exception. :)

  9. mjcarman commented on Apr 3, 2026

    @mjcarman
    Author

    Defaulting the isStrict() calls to Boolean.FALSE would better match the existing behavior

    Just tried it and defaulting to false appears to be necessary. Defaulting to true causes existing tests to fail:

    [ERROR]   MaximumValidatorTest.doubleValueCoarsingExceedRange:270 Validation should succeed as by default double values are used by mapper ==> expected: <true> but was: <false>
    [ERROR]   MaximumValidatorTest.negativeDoubleOverflowTest:199 Maximum 1.7976931348623157E+309 and value 1.7976931348623157e+309 are interpreted as Infinity, thus no schema violation should be reported ==> expected: <true> but was: <false>
    [ERROR]   MinimumValidatorTest.doubleValueCoarsingExceedRange:259 Validation should succeed as by default double values are used by mapper ==> expected: <true> but was: <false>
    [ERROR]   MinimumValidatorTest.negativeDoubleOverflowTest:185 Minimum -1.7976931348623157E+309 and value -1.7976931348623157e+309 are interpreted as Infinity, thus no schema violation should be reported ==> expected: <true> but was: <false>
    

    I don't know that there's a way to distinguish between Infinity as an external value and Infinity as the result of overflow.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions