Skip to content

Read converted collection identifiers as provider values - #39369

Merged
AndriySvyryd merged 7 commits into
dotnet:mainfrom
benedict-odonovan:fix/converted-key-identifier-hang
Nov 3, 2026
Merged

AndriySvyryd merged 7 commits into
dotnet:mainfrom
benedict-odonovan:fix/converted-key-identifier-hang

Conversation

@benedict-odonovan

@benedict-odonovan benedict-odonovan commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #39366

  • 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
  • Tests for the changes have been added (for bug fixes / features)
  • Code follows the same patterns and style as existing code in this repo

A query whose rows are told apart by a value-converted property of a reference type never returns; one core stays at 100%. Two examples:

// Tag is a class without Equals, mapped with HasConversion(t => t.Name, n => new Tag { Name = n })
context.Posts.GroupBy(p => p.Tag)
    .Select(g => new { g.Key, Ids = g.Select(p => p.Id).ToList(), Count = g.Count() });

context.Posts.Select(p => p.Tag).Distinct()
    .Select(t => new { Tag = t, Ids = context.Posts.Where(p => p.Tag == t).Select(p => p.Id).ToList() });

Cause.

  • A collection shaper tells its rows apart by identifier values. When a query has no entity key to identify its rows by (grouping terms, a Distinct projection, set-operation columns), SelectExpression uses those columns as identifiers.
  • Each identifier read materializes a new Tag through the converter, and the default key comparer for a class without Equals falls back to reference equality. So an identifier never equals the one just read from the same row.
  • The collection shaper then ends the collection and sets HasNext = true without advancing the reader, which makes the same row the start of the next parent, again and again.

Change. A collection's identifiers are now read and compared as the database returned them, the way the database told the rows apart when it grouped or applied DISTINCT:

  • Where an identifier column's type mapping has a value converter, the identifier accessor wraps its projection binding in a new internal ProviderValueProjectionBindingExpression and pairs it with the mapping's ProviderValueComparer. Every other identifier keeps its accessor and comparer, as before.
  • The shaper reads that node with the converter skipped (a new applyConverter flag on CreateGetValueExpression). The node never survives shaper processing, so precompiled queries are unaffected.
  • The decision is made where identifier accessors are built, not where identifiers are collected. It covers every path that contributes identifiers: entity keys, ApplyDistinct (including the columns of a distinct complex type and the non-key properties of a JSON-owned entity), both ApplyGrouping overloads, and both set-operation paths. It also covers single and split queries.
  • The generated SQL doesn't change: the identifier columns were already projected.

Final GroupBy is the exception. Its key identifier isn't a row's identity but the LINQ grouping key, which LINQ compares as the model value. So it's still read through the converter and compared with the key comparer. With a converter that reads different database values as the same one ("1" and "01" through int.Parse), comparing provider values would have produced two groupings with key 1. A converted reference type without Equals as a final GroupBy key gives one grouping per row, as LINQ to Objects does with reference equality, and doesn't hang.

Behavior change. This applies to every converted collection identifier, not only reference types that compare by reference: enums and strongly typed IDs are now compared as their provider values too. That gives the same result for any converter that reads each database value as a distinct model value. With one that doesn't, the collection shapes now follow the database. For example, rows with "1" and "01" in a Distinct() + correlated collection, or a GroupBy with an element list, come back as two results with model value 1. On main they were merged on the client, which mixed aggregates computed per database group: the merged group listed all three posts but its Count() was 1.

Alternatives considered

  • Compare the materialized values with a comparer that converts them back to provider values. This was the first version of this PR. It needed a reflection check on the model type (an Equals override, ==, interfaces, structural equality) to decide which types compare by reference. It also ran the write converter, which needn't give the same provider value twice (randomized encryption doesn't), and it only reached the identifiers that SelectExpression built from type mappings, missing a distinct complex type's properties.
  • Use the property's own comparer (GetKeyValueComparer()). Column expressions don't carry their property, and it wouldn't help the common case with no comparer configured, which is the repro.
  • Detect the loop (an identifier that doesn't equal itself on the row it was read from) and throw. That turns the hang into an error but doesn't make the query work.

Tests

New tests in AdHocMiscellaneousQueryRelationalTestBase, each run sync and async on SQL Server (with SQL baselines) and SQLite:

  • GroupBy_value_converted_reference_type_key_with_elements_and_aggregate
  • Distinct_value_converted_reference_type_with_collection
  • Distinct_value_converted_object_with_collection
  • Distinct_complex_type_with_value_converted_reference_type_with_collection and _with_split_collection
  • Distinct_value_converted_string_with_nondeterministic_write_with_collection: a write converter that doesn't give the same provider value twice
  • Distinct_primitive_collection_with_collection
  • Union_value_converted_reference_type_with_collection: a set operation's projected columns as identifiers
  • Union_entity_with_value_converted_key_with_collection and _with_split_collection: a strongly typed converted entity key as the identifier of a set operation
  • Final_GroupBy_value_converted_key_read_as_same_value_from_different_database_values: the final GroupBy exception above

Both repro queries above hang on main, and so does a run of the new Union tests. Converted entity keys with Include are also covered by the existing KeysWithConverters suites, which pass on SQL Server and SQLite.

Copilot AI balanced review requested due to automatic review settings October 22, 2026 13:37
@benedict-odonovan
benedict-odonovan requested a review from a team as a code owner October 22, 2026 13:37

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.

🟡 Changes recommended

Reapplying write converters can introduce infinite loops and break precompiled queries when converter expressions capture objects.

2 open issues

Review effort: Balanced

- Grouping terms, a Distinct projection and set-operation columns identify rows on the client by their materialized values,
  compared with the type mapping's KeyComparer. Through a value converter, the same database value materializes as a new
  instance each time, and the default key comparer of a class without Equals compares by reference; so an identifier never
  equalled the one just read from the same row, and the collection shaper kept starting a new parent on that row forever.
- Values of a converted reference type are now compared by their provider values, as the database compared them, using a
  comparer composed from the converter's ConvertToProviderExpression and the mapping's ProviderValueComparer, which also works
  as an expression for precompiled queries.
- Add tests for a GroupBy over such a key projecting its elements and an aggregate, and for a Distinct over such a column
  followed by a collection.

Fixes dotnet#39366
- Comparing identifiers by converting them back to provider values runs the write converter, which the read never did. A
  converter needn't give the same provider value twice (randomized encryption doesn't), and then an identifier doesn't equal
  even the one read from the same row, so a converted string key that worked before now never finished. A write converter
  capturing state also had to be inlined into precompiled queries, which can't generate it.
- Only a converted type whose default comparer ends at object.Equals, compared by reference, is now compared by provider
  value; strings, records and anything else with its own equality keep the mapping's key comparer, as before.
- Add a test for a Distinct over a converted string whose write converter isn't deterministic, followed by a collection.

Part of dotnet#39366
@benedict-odonovan
benedict-odonovan force-pushed the fix/converted-key-identifier-hang branch from 0264cb2 to 07849a1 Compare October 24, 2026 20:49
Copilot AI balanced review requested due to automatic review settings October 24, 2026 20:49

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.

- Checking whether a converted type compares by reference looked up its Equals(object) and assumed one was found. An
  interface declares none, so the lookup returned null and set operations and groupings over complex types, in a table or
  in JSON, failed with a NullReferenceException.
- An interface, or object itself, now keeps the mapping's key comparer, as it did before: what Equals does depends on the
  instance, so there is nothing to say it compares by reference.
Copilot AI balanced review requested due to automatic review settings October 25, 2026 10:31

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.

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.

🟡 Changes recommended

Comparer selection still leaves object-typed identifiers vulnerable to hangs and can replace valid custom mapping comparers with nonterminating comparisons.

2 open issues

Review effort: Balanced

…ings' own comparers

- The default comparer for object compares with ==, not through Equals, so a converted object-typed property was compared
  by reference whatever its instances override, and a Distinct over it followed by a collection never finished. object is
  now compared by provider value, like any other class compared by reference; interfaces still call Equals on the instance
  and keep the mapping's key comparer.
- A mapping that was given its own comparers, such as a primitive collection's structural one, now keeps its key comparer
  rather than having it replaced by a comparison through the converter.
- Add tests for a Distinct over a converted object property and over a primitive collection, each followed by a collection.

Part of dotnet#39366
Copilot AI balanced review requested due to automatic review settings October 29, 2026 13:09

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.

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

Two moderate active issues remain: nondeterministic converters on default-comparer reference types and converted reference-type properties within distinct complex projections can still cause non-advancing collection-identifier comparisons.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Use provider comparers for complex distinct projections

src/​EFCore.Relational/​Query/​SqlExpressions/​SelectExpression.cs:462

This only updates the otherExpressions branch of ApplyDistinct. When the projection is a complex type, the same method still fills typeProjectionValueComparers with each property's GetKeyValueComparer, so a converted reference-type property inside a distinct complex projection remains compared by object identity. A correlated collection over that projection can therefore hit the same non-advancing identifier loop; the complex-property identifier path also needs the provider-value comparer or an explicit regression/limitation.

Review effort: Lite

…em through the converter

Rows are told apart on the client by their identifier values, and the database
told them apart by their provider values. Rather than guessing from a converted
type's Equals and operators whether its comparer compares by reference, and
building a comparer that converts back to the provider value, read a converted
identifier column without its converter and compare it with the mapping's
ProviderValueComparer. This covers every identifier path, including the
columns of a distinct complex type, and never runs a write converter that
needn't be deterministic.
A final GroupBy's key identifier isn't a row's identity but the grouping key,
which LINQ compares as the model value. Reading it as a provider value split
rows whose database values the converter reads as the same value - "1" and
"01" through int.Parse - into separate groupings with the same key. Keep
reading it through the converter; only a collection's identifiers are read as
provider values.
Copilot AI lite review requested due to automatic review settings November 2, 2026 17:04
@benedict-odonovan benedict-odonovan changed the title Compare converted reference-type identifiers by their provider values Read converted collection identifiers as provider values Nov 2, 2026

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.

🟡 Changes recommended

A remaining coverage gap leaves the converted entity-key and set-operation remapping paths insufficiently verified, including relevant sync/async and split-query scenarios.

1 open issue

Review effort: Lite

A set operation's projected columns, and the key of an entity it returns,
become its identifiers; test both with value converters, the latter with a
strongly typed key in single and split queries.
Copilot AI lite review requested due to automatic review settings November 2, 2026 17:23

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 broad relational identifier-materialization and comparer changes span many query paths and provider-specific mappings, so the focused SQL Server/SQLite coverage is insufficient without wider human validation.

1 open issue

Review effort: Lite

@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 merged commit 2c70cea into dotnet:main Nov 3, 2026
20 checks passed
@benedict-odonovan
benedict-odonovan deleted the fix/converted-key-identifier-hang branch November 3, 2026 10:07
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 4, 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.

Query never returns (infinite loop on the client) when grouping by a value-converted reference type and projecting the group's elements

3 participants