Repository navigation
9.0.0: literals as the default wire form, TypeConverter, culture-free literals - #25
Merged
Merged
Conversation
…y default
The converters were opt-in, and System.Text.Json's fallback for a type
with no converter is a property dump: DateRange wrote {"Length":181}, a
RangeSet [{"Length":5}], a StringSet {"Values":[...],"Count":2,...}, and
none of them read back. Nothing threw on write. An ASP.NET host that
forgot AddRangeConverters() answered every body with a 400.
Every union, every sealed variant, RangeSet and every value set type now
carries [JsonConverter]. System.Text.Json does not inherit the attribute,
so the variants (what a value reached through object presents) carry
their own. Unions, variants and the non-generic sets name a closed
converter type, which a source-generated context instantiates directly;
RangeSet and the wrapper arities name the factory, because an attribute
cannot name an open generic converter.
The attribute is the lowest-precedence route: a converter on the options
or on a property still wins, and AddRangeConverters() stays valid and
redundant.
JsonDefaultContractTests sweeps every discovered range shape (through the
union, through object, inside a RangeSet) and every set family, both
arities, against the registered output. Seeded: reverting all attributes,
dropping only LocalDateRange.Finite's, only StringSet<T>'s, or only
RangeSet's each fails it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
RangeJsonConverter, RangeVariantJsonConverter and RangeSetJsonConverter
did not override ReadAsPropertyName/WriteAsPropertyName, so
Dictionary<DateRange, int> threw NotSupportedException in both
directions, with or without the converters registered.
The key is the same PostgreSQL literal as the value form, parsed through
the same helper, so a key canonicalizes ("[1,10)" reads as [1,9]) and a
malformed or wrong-shape key is the same JsonException as a malformed
value. DictionaryKeyPolicy is not applied: System.Text.Json applies it
only to string keys, and a naming policy would rewrite a literal into
text that does not parse.
The conventions sweep now keys a dictionary by every shape of every
range type, through the union, the variant and a RangeSet. Reverting the
overrides fails it and the new unit tests with the original
NotSupportedException; dropping only the variant converter's overrides
fails the sweep on its own.
Value sets are not covered: their value form is a JSON array, so a key
form would be a new design decision rather than the same literal.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Version 9.0.0, package validation baseline 8.0.0, supported-versions table moved to 9.0.x. A major for the 7.0.0/8.0.0 reason: default-options Serialize(range) answers differently, which no compile error reveals, even though the old answer could never be read back. Changelogs (root and all four packages), a v8 migration section with the before/after payload table, serialization.md (no registration needed, precedence, source-generated contexts and their element-type requirement, dictionary keys, and why a rejection quotes a bounded excerpt of the input), architecture.md (the three attribute rules; drops the stale HandleNull note from before 6.2), both READMEs, value-sets.md, testing.md, and a CLAUDE.md rule that every type and variant carries its own [JsonConverter]. The consumer smoke test now asserts the unregistered wire form, as value and as dictionary key, against the packed package. Co-Authored-By: Claude Opus 5.5 <[email protected]>
None of the types had one, so TypeDescriptor could not convert them from
a string and Microsoft.Extensions.Configuration binding of
"Period": "[2026-01-01,2026-06-30]" into a DateRange property produced
null with no error. Each type now converts to and from its literal.
- Always invariant: the culture argument is ignored, the literal is a
wire format. Seeded: honouring it misreads "[1.5,9.25)" under de-DE.
- An empty string is null (absent), never the empty range ("empty").
- [TypeConverter] IS inherited, unlike [JsonConverter], so a variant
without its own would silently use the union's and return whatever
shape the literal had. Each variant carries a narrowing converter.
Seeded: dropping InstantRange.Finite's is caught.
- Generic types (RangeSet, wrapper arities) name LiteralTypeConverter,
which TypeDescriptor constructs with the closed type via ctor(Type).
ASP.NET Core model binding never needed this: minimal APIs and MVC bind
through the static TryParse (MVC since .NET 7), which the new host tests
confirm by passing with the attribute removed.
New test project CodoMetis.ValueRanges.AspNetCore.Tests: configuration
binding (fails without the attributes), and a TestServer host with no
ValueRanges registration running MVC and minimal-API query binding and
JSON bodies (fail without the type-level [JsonConverter]).
TypeConverterContractTests sweeps every shape and set family; the range
discovery and shape probes move to a shared RangeProbes.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Int32Range, Int64Range and DecimalRange have no FormatValue override, and
the default formatted a null provider (what string interpolation,
string.Format and logging renderers pass) in the current culture. Under
de-DE, $"{DecimalRange [1.5,2)}" was "[1,5,2)", which the parser reads
back as [1,52) with no error; [1.5,2.25) came back as [1,5225). Under
sv-SE a negative bound took U+2212 as its minus sign and stopped parsing.
Found by the value-semantics review of this branch.
Both default FormatValue implementations now treat null as the invariant
culture, as every override already did. ToString(), JSON, the
TypeConverter and the EF bridge pass the invariant culture explicitly and
were never affected.
LiteralCultureContractTests formats every range shape, multirange and set
family under de-DE, sv-SE, fa-IR and th-TH; it was written first and
failed against the unfixed code. The int/long/decimal probe bounds go
negative so the minus sign is exercised. The named de-DE regression test
fails with the fix stripped.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
DecimalRange and DecimalSet parsed with NumberStyles.Any, which accepts
group separators, currency symbols and parenthesised negatives:
["1,000",2000] read as [1000,2000] and "(5)" as -5, literals PostgreSQL
rejects. It is also what turned the culture-formatted "[1,5,2)" into
[1,52) rather than an error, and what made an explicit comma-decimal
provider misread silently: Parse("[1.5,2.5)", de-DE) was [15,25).
NumberStyles.Float (sign, digits, point, exponent, surrounding
whitespace) matches numeric's input grammar; the integer types already
used NumberStyles.Integer. Found by the value-semantics review.
The new tests were written first: the four rejection cases and the de-DE
provider case fail against NumberStyles.Any, the exponent control passes
either way.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… sets
ASP.NET Core 10's OpenAPI generator describes a body range, multirange or
value set as {}: it cannot see through a custom JSON converter, and
.NET 10 has no public way for a converter to declare its schema
(JsonConverter.GetSchema is internal). The only hook is an
IOpenApiSchemaTransformer.
Rather than a fifth package depending on Microsoft.AspNetCore.OpenApi and
Microsoft.OpenApi 2.x, docs/serialization.md#openapi carries a transformer
to copy: ranges and multiranges as type: string with a literal pattern
and a description naming the element type, value sets as arrays of
unique items using the element's own schema.
The copy lives in CodoMetis.ValueRanges.AspNetCore.Tests, compiled and run
against a generated document with and without it; its patterns are
checked to accept every literal form the parsers accept; and
DocumentedSnippet_IsThisFile holds the doc to it verbatim (a one-character
edit to the doc fails it). Query and route parameters bind through
TryParse and are type: string either way, which is now documented.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Parse(s, provider) handed the provider to the element parser and
ToString(null, provider) to the element formatter. th-TH uses the
Buddhist calendar, so DateRange.Parse("[2026-01-01,2026-06-30]", th-TH)
returned [1483-01-01,1483-06-30] and ToString(null, th-TH) wrote 2569;
ar-SA read dates as Hijri; de-DE read the decimal 1.5 as fifteen. None of
it threw. Found by the value-semantics review of this branch.
The literal is PostgreSQL's text and has no culture:
- Parse/TryParse (string and span; every range, RangeSet and value set)
read the invariant literal and ignore the provider, as Guid.Parse does.
The provider stays in the public signatures for IParsable and stops at
RangeFormat/SetFormat.Parse; the element parsers get InvariantCulture.
- Formatting without a format string writes the invariant literal
whatever the provider. A provider still applies with an explicit
format, which asks for display text.
JSON, the TypeConverter, EF Core and ASP.NET Core model binding always
passed the invariant culture and are unaffected.
LiteralProviderContractTests sweeps every shape, multirange and set
family under de-DE, sv-SE, fa-IR, th-TH and ar-SA. It was written first
and failed against the old code; reverting only the parse half or only
the format half each fails it on its own.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A complex or owned type mapped with ToJson() that held any of these could not be saved: the plugin's type mappings had no JsonValueReaderWriter, and SaveChanges threw a bare NullReferenceException from EF's own ModificationCommand.WriteJsonObject. Measured on PostgreSQL for both ComplexProperty(...).ToJson() and OwnsOne(...).ToJson(). Each mapping now writes its store type's literal through LiteralJsonValueReaderWriter<TValue> (public: a compiled model re-creates it via ConstructorExpression). The literal is also what makes queries into the document translate, since EF extracts the text and casts it: CAST(doc ->> 'Period' AS daterange) @> @day. The YearMonth types are written in their store's month-aligned date form instead of their own "2026-01" literal: the cast to daterange/date[] reads dates. Three small reader/writers in the NodaTime satellite reuse the column mappings' conversions, so reads validate month alignment. ValueSetTypeMapping takes an optional reader/writer for this. JsonColumnTests (integration) round-trips and queries all 25 types in one jsonb column and pins the stored text. MappingParityTests now requires a reader/writer on every mapping. Seeded: dropping it from the range mapping alone fails both with the original NRE; putting YearMonthRange back on its own literal fails the query cast and the stored form. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Prepares 9.0.0. It started from three wire-format gaps measured by a TypeKit spike that wrapped
DateRangein a value object (findings 7, 8, 13). A value-semantics review of the result then found three more defects of the same kind: each one returned a wrong value without throwing.What changes
JsonSerializer.Serialize(dateRange)with no registration{"Length":181}, unreadable"[2026-01-01,2026-06-30]"Dictionary<DateRange, int>in JSONNotSupportedException{"[2026-01-01,2026-06-30]":181}"Period": "[…]"→DateRangenull, no error$"{DecimalRange [1.5,2)}"under de-DE[1,5,2)→ parses as[1,52)[1.5,2)DateRange.Parse("[2026-01-01,…]", th-TH)[1483-01-01,…][2026-01-01,…]DecimalRange.Parse("[\"1,000\",2000]")[1000,2000](PostgreSQL rejects it)FormatException{}type: string+ patternToJson()columnSaveChanges→NullReferenceExceptionCAST(doc ->> 'Period' AS daterange) @> @day)Commits
[JsonConverter]),RangeSetand value set carries[JsonConverter]. A converter registered on the options or on a property still wins, andAddRangeConverters()still works but is no longer needed. Non-generic types name a closed converter type, which the source generator instantiates directly. Generic types name the factory, because an attribute cannot name an open generic converter.DictionaryKeyPolicyis not applied.[TypeConverter]on every type, always invariant. An empty string converts tonull. Each variant has its own narrowing converter:[TypeConverter]is inherited, so without one a variant would silently use the union's and accept any shape. ASP.NET Core model binding never needed this, because it binds throughTryParse.nullprovider formats invariantly in the defaultFormatValue. That provider is what interpolation,string.Formatand logging pass.numericgrammar (NumberStyles.Floatinstead ofAny).docs/serialization.md#openapi. It is a snippet to copy, not a new package. The tested copy lives in the new test project, and a test holds the doc to it verbatim.Parse/TryParseignore the provider. Formatting without a format string is always the invariant literal; a provider applies only with an explicit format.JsonValueReaderWriter, soSaveChangesthrew aNullReferenceExceptionfrom inside EF. Each mapping now writes its store type's literal, which is also exactly what EF's text-and-cast query into the document needs. TheYearMonthtypes write their month-aligned date form, because the cast reads dates.Why a major
This follows the rule from the 7.0.0 and 8.0.0 notes: existing calls now give different answers, and no compile error reveals it. Default-options JSON output changes, and so do the culture-sensitive parse and format paths. No signature changed, and package validation against 8.0.0 passes.
Decisions recorded
int.Parse).Verification
RangeSet) and every set family in both arities:JsonDefaultContractTestsTypeConverterContractTestsLiteralCultureContractTestsLiteralProviderContractTestsTypeConverter, a culture-honouring converter, and each half of the provider fix reverted on its own.test/CodoMetis.ValueRanges.AspNetCore.Testsproject: configuration binding, plus aTestServerhost (MVC and minimal APIs) with no ValueRanges registration, plus the OpenAPI document generated with and without the transformer.JsonColumnTests(integration) round-trips and queries all 25 types inside one jsonb column.MappingParityTestsrequires a JSON reader/writer on every mapping.test/consumer-smoke-test.shpasses all 17 checks against the packed packages, including the unregistered JSON wire form.Not in this PR: Native AOT (measured, follow-up)
I ran a NativeAOT probe (osx-arm64, ILCompiler 10.0.12) with a source-generated JSON context.
RangeSet<,>and the wrapper arities, in both JSON and the TypeConverter.MakeGenericTypeproduces an instantiation over a value type that was never compiled, soActivator.CreateInstancethrowsNotSupportedException. Whether a case fails depends on whether something else in the program happens to instantiate that closed type, so an AOT test can turn green by accident.RangeSetconverters, plus a consumer-declared converter per wrapper arity.LiteralTypeConverterandValueSetJsonConverter.The fix (route
RangeSetto the shipped closed converters, add[RequiresDynamicCode]/[RequiresUnreferencedCode], turn onIsAotCompatible, document consumer registration for wrapper arities) is a follow-up.🤖 Generated with Claude Code