Skip to content

Change DateTime JSON serialization to fixed width - #39131

Merged
AndriySvyryd merged 13 commits into
dotnet:mainfrom
mohammedwed:cosmos-datetime-fixed-width
Oct 28, 2026
Merged

AndriySvyryd merged 13 commits into
dotnet:mainfrom
mohammedwed:cosmos-datetime-fixed-width

Conversation

@mohammedwed

@mohammedwed mohammedwed commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor
  • I've read the guidelines for contributing and seen the walkthrough
  • I've posted a comment on an issue with a detailed description of how I am planning to contribute and got approval from a member of the team
  • The code builds and tests pass locally (also verified by our automated build checks)
  • Commit messages follow this format:
        Summary of the changes
        - Detail 1
        - Detail 2

        Fixes #bugnumber
  • Tests for the changes have been added (for bug fixes / features)
  • Code follows the same patterns and style as existing code in this repo

Summary

JsonDateTimeReaderWriter used to write DateTime values with trailing zero fractional seconds omitted (e.g. 2026-01-01T00:00:00Z vs 2026-01-01T00:00:00.1200000Z). Because the string length varies, string comparison (e.g. ORDER BY in Cosmos) doesn't match chronological order. Values are now written in a fixed-width ISO 8601 format with seven fractional digits: yyyy-MM-dd'T'HH:mm:ss.fffffffK.

Changes

  • JsonDateTimeReaderWriter writes the fixed-width format by default. A new public constructor JsonDateTimeReaderWriter(string format) lets the format be customized; "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK" restores the previous behavior. ConstructorExpression handles both the singleton and custom instances (for compiled models).
  • SQL Server datetime/smalldatetime: these types can't convert strings with more than three fractional digits (CAST('2020-01-05T12:30:45.0000000' AS datetime) fails with Msg 241 / 295), which broke JSON queries such as OPENJSON ... WITH ([value] datetime '$'). SqlServerDateTimeTypeMapping therefore uses a reader/writer with three fractional digits (yyyy-MM-dd'T'HH:mm:ss.fffK) for those store types. datetime2 and date keep the seven-digit default.
  • Baselines: updated the affected SQL Server, Cosmos and specification test baselines for the new format.

Existing data in the old format

Reading is unchanged (Utf8JsonReader.GetDateTime() accepts both formats), so documents written by previous versions are still materialized correctly. Note, however, that ordering and range comparisons on the server compare strings, so they can still be wrong between old short-format values and new fixed-width values until existing documents are rewritten (for example by loading and saving them, or by a one-off update script).

Tests

  • JsonDateTimeReaderWriterTest: default fixed-width output, custom format matching the previous Utf8JsonWriter output, round-tripping (value and Kind), and ConstructorExpression.
  • AdHocMiscellaneousQueryCosmosTest.DateTime_in_legacy_short_format_is_read_correctly: inserts a document with a short-format DateTime directly through the Cosmos SDK and asserts it materializes correctly in entity instances, scalar projections and anonymous-type projections.
  • AdHocMiscellaneousQueryCosmosTest.DateTime_with_and_without_fractional_seconds_orders_and_filters_correctly: ordering and filtering on values with and without fractional seconds.

Fixes #39113

- Fall back to Cosmos SDK serialization when parameter values do not match the mapping type
- Preserve default SDK handling for parameter values incompatible with configured type mappings

Fixes dotnet#39113
Copilot AI balanced review requested due to automatic review settings September 30, 2026 10:06
@mohammedwed
mohammedwed requested a review from a team as a code owner September 30, 2026 10:06

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@mohammedwed

Copy link
Copy Markdown
Contributor Author

@dotnet-policy-service agree company="veraxity.dev"

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.

Copilot review overview

🟡 Changes recommended

Legacy Cosmos documents remain incompatible with new parameters, and several shared JSON assertions are currently broken.

Review effort: Balanced
Findings: 3 High severity

Open (3)

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 4, 2026 16:38

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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.

🔵 Needs a closer look

The shared writer changes unrelated providers and breaks existing SQL Server JSON baselines, while legacy-format compatibility remains untested.

1 open finding
1 resolved since last review
Previously missed (1)

In code that hasn't changed since last review

Medium severity Add regression coverage for reading legacy short-form dates

test/​EFCore.Cosmos.FunctionalTests/​Query/​AdHocMiscellaneousQueryCosmosTest.cs:197

This regression test only inserts documents through the new writer, so it does not verify that legacy documents containing the short form (for example, "2026-01-01T00:00:00Z") remain readable. The provider-independent JSON expectations were changed away from that form, leaving the compatibility claim from the review thread uncovered. Seed one document as raw legacy JSON (the existing AdHocCosmosTestHelpers.CreateCustomEntityHelperAsync supports this) and assert it materializes correctly.

🧠 Review effort: Balanced


Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

mohammedwed and others added 3 commits October 20, 2026 16:48
…net#39113)

- Seed a document with a short-format DateTime through the SDK and verify it
  materializes correctly in entity instances and in projections
- Update remaining DateTime expectations missed by the fixed-width change

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add a public JsonDateTimeReaderWriter constructor that takes the format used
when writing values, so the previous behavior can be restored with
"yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…otnet#39113)

datetime and smalldatetime cannot be converted from strings with more than
three fractional second digits, so use a fixed-width millisecond format for
them. Update the affected SQL Server baselines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 20, 2026 13:52

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI balanced review requested due to automatic review settings October 20, 2026 18:34

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@mohammedwed

Copy link
Copy Markdown
Contributor Author

Hi @AndriySvyryd

The PR should be all set now! Tag me if anything else is needed.

…ement mapping

- Serialize elements of List<object>/object[] parameters through the element
  type mapping when all elements match it, so DateTimes use the same fixed-width
  format as stored values
- Fall back to SDK serialization when any element doesn't match
- Add tests for List<object> and object[] Contains over DateTime

Part of dotnet#39113
- Create FromSql parameters via CosmosTypeMapping.CreateParameter so DateTime
  values match the fixed-width format of stored values
- Keep SqlValueParameter for null values and types without a mapping
- Add tests for FromSqlRaw and interpolated FromSql with a DateTime parameter

Part of dotnet#39113
Copilot AI balanced review requested due to automatic review settings October 26, 2026 16:28

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@mohammedwed

mohammedwed commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @AndriySvyryd,

I've addressed the remaining Copilot findings: object-backed DateTime collections and FromSql DateTime parameters

Both now use the same fixed-width format as stored values, with regression tests.

Ready for another look when you have time.

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.

🔵 Needs a closer look

Object-backed collection serialization still has edge cases that silently miss DateTime matches or throw for previously supported mixed collections.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Fallback for mixed object-backed reference collections

src/​EFCore.Cosmos/​Storage/​Internal/​CosmosTypeMapping.cs:97

JsonCollectionOfReferencesReaderWriter reports ValueType == typeof(object), so this check accepts mixed object-backed collections without validating their elements. A captured List<object> { "ALFKI", 1 } used in values.Contains(c.CustomerID) then throws InvalidCastException in the string reader/writer instead of serializing the mixed array as before. Route incompatible reference collections through the elementwise/fallback path too, and add a regression with mixed contents.

Medium severity Preserve mapped serialization for null-containing date collections

src/​EFCore.Cosmos/​Storage/​Internal/​CosmosTypeMapping.cs:154

A captured List<object?> { timestamp, null } or object?[] used in dates.Contains(x.Timestamp) falls back to SDK serialization for the entire collection here. The exact-second DateTime then uses the old short format and silently misses a freshly saved fixed-width value. Write null elements with WriteNullValue() while retaining mapped serialization for non-null elements, and add null-containing variants of the collection regressions.

2 resolved since last review

Review effort: Balanced

@AndriySvyryd

AndriySvyryd commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

CSharpMigrationsGeneratorTest.SeedData_annotations_are_stored_in_snapshot and NorthwindSelectQueryCosmosTest.Select_anonymous_non_numeric_constants need to be updated to use the new format

Copilot AI balanced review requested due to automatic review settings October 27, 2026 23:12

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

…ql parameter serialization (dotnet#39113)

- Use model-level type mappings for FromSql parameters and constants
- Serialize object-backed collections per element, writing nulls directly and falling back only for incompatible elements
- Route collections of references through element compatibility checking

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 27, 2026 23:20

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@mohammedwed

mohammedwed commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @AndriySvyryd

SeedData_annotations_are_stored_in_snapshot
and
Select_anonymous_non_numeric_constants

are updated to the new format

@mohammedwed

Copy link
Copy Markdown
Contributor Author

Hi @AndriySvyryd

SeedData_annotations_are_stored_in_snapshot and Select_anonymous_non_numeric_constants

are updated to the new format

I'm not sure though about the error propagating from the npm modules, I hadn't changed anything in that regards, it could be the test environment itself.

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.

🔵 Needs a closer look

Human assessment is needed because critical DateTime serialization mismatches across parameter paths can cause equality queries to miss newly saved documents.

No open issues 🎉

Review effort: Balanced

@AndriySvyryd AndriySvyryd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your contribution!

@AndriySvyryd AndriySvyryd changed the title Cosmos datetime fixed width Change DateTime JSON serialization to fixed width Oct 28, 2026
@AndriySvyryd
AndriySvyryd merged commit 493b52c into dotnet:main Oct 28, 2026
18 of 19 checks passed
@github-actions github-actions Bot added the api-review This PR or issue is introducing public API changes that need to be reviewed label Oct 28, 2026
@github-actions

Copy link
Copy Markdown
Contributor

API review baseline changes for src/EFCore/EFCore.baseline.json

Show diff

The diff below was generated by ApiChief between the base and the PR.

  sealed class Microsoft.EntityFrameworkCore.Storage.Json.JsonDateTimeReaderWriter :
      Microsoft.EntityFrameworkCore.Storage.Json.JsonValueReaderWriter<System.DateTime>
+ JsonDateTimeReaderWriter(string format);

@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Oct 29, 2026
@AndriySvyryd AndriySvyryd removed the api-review This PR or issue is introducing public API changes that need to be reviewed label Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cosmos DB: DateTime serialization format causing errors in ordering and filtering

3 participants