Skip to content

9.0.0: literals as the default wire form, TypeConverter, culture-free literals - #25

Merged
CaffeinatedCoder merged 9 commits into
mainfrom
fix/json-wire-defaults
Oct 11, 2026
Merged

CaffeinatedCoder merged 9 commits into
mainfrom
fix/json-wire-defaults

Conversation

@CaffeinatedCoder

@CaffeinatedCoder CaffeinatedCoder commented Oct 11, 2026 •

Copy link
Copy Markdown
Owner

Prepares 9.0.0. It started from three wire-format gaps measured by a TypeKit spike that wrapped DateRange in 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

Before After
JsonSerializer.Serialize(dateRange) with no registration {"Length":181}, unreadable "[2026-01-01,2026-06-30]"
Dictionary<DateRange, int> in JSON NotSupportedException {"[2026-01-01,2026-06-30]":181}
config binding "Period": "[…]" → DateRange null, no error the range
$"{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
OpenAPI schema of a range body {} documented transformer: type: string + pattern
a range/set inside an EF ToJson() column SaveChanges → NullReferenceException stored as the literal; queries translate (CAST(doc ->> 'Period' AS daterange) @> @day)

Commits

  1. fix: every union, every sealed variant (System.Text.Json does not inherit [JsonConverter]), RangeSet and value set carries [JsonConverter]. A converter registered on the options or on a property still wins, and AddRangeConverters() 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.
  2. feat: ranges, variants and multiranges can be JSON dictionary keys, written as the same literal; DictionaryKeyPolicy is not applied.
  3. docs: version 9.0.0, package validation baseline 8.0.0, changelogs, migration notes.
  4. feat: [TypeConverter] on every type, always invariant. An empty string converts to null. 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 through TryParse.
  5. fix: a null provider formats invariantly in the default FormatValue. That provider is what interpolation, string.Format and logging pass.
  6. fix: decimal bounds and elements parse with PostgreSQL's numeric grammar (NumberStyles.Float instead of Any).
  7. docs: an OpenAPI schema transformer in 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.
  8. fix: a culture provider no longer changes the literal. Parse/TryParse ignore the provider. Formatting without a format string is always the invariant literal; a provider applies only with an explicit format.
  9. fix: ranges, multiranges and value sets inside an EF Core JSON column. Before, the plugin's mappings had no JsonValueReaderWriter, so SaveChanges threw a NullReferenceException from 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. The YearMonth types 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

  • Rejection messages still quote the input, capped at 64 characters plus its length since 6.2.1. The excerpt is what makes a 400 diagnosable, and the BCL does the same (int.Parse).
  • OpenAPI is a doc snippet, not a package. .NET 10 has no public API for a converter to declare its schema, so a transformer is the only hook. A fifth package would bring release wiring and a dependency on Microsoft.OpenApi 2.x for about 50 lines.
  • Value sets are not dictionary keys. Their value form is a JSON array, not a string.

Verification

  • Every fix was written test-first or proven by reverting it. The new conventions sweeps cover every discovered range shape (through the union, the variant and RangeSet) and every set family in both arities:
    • JsonDefaultContractTests
    • TypeConverterContractTests
    • LiteralCultureContractTests
    • LiteralProviderContractTests
  • Seeded defects caught, among others: a single missing variant attribute, a single inherited TypeConverter, a culture-honouring converter, and each half of the provider fix reverted on its own.
  • New test/CodoMetis.ValueRanges.AspNetCore.Tests project: configuration binding, plus a TestServer host (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. MappingParityTests requires a JSON reader/writer on every mapping.
  • All test projects pass locally, including the live-PostgreSQL integration suite (1,356 tests). test/consumer-smoke-test.sh passes 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.

  • What works under AOT: all range types and variants, JSON dictionary keys, the non-generic value sets, parsing, the algebra, and the TypeConverter for non-generic types.
  • 6 of 25 cases fail. They are the generic routes: RangeSet<,> and the wrapper arities, in both JSON and the TypeConverter. MakeGenericType produces an instantiation over a value type that was never compiled, so Activator.CreateInstance throws NotSupportedException. 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.
  • What fixes it: registering closed converters. That covers the 7 shipped RangeSet converters, plus a consumer-declared converter per wrapper arity.
  • The 14 library-side analyzer warnings are all in the factory, LiteralTypeConverter and ValueSetJsonConverter.

The fix (route RangeSet to the shipped closed converters, add [RequiresDynamicCode]/[RequiresUnreferencedCode], turn on IsAotCompatible, document consumer registration for wrapper arities) is a follow-up.

🤖 Generated with Claude Code

CaffeinatedCoder and others added 9 commits October 11, 2026 14:05
…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]>
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.

1 participant