Skip to content

CBEF-133: Reject table splitting and TPT when the model is built - #198

Open
davidkelly wants to merge 1 commit into
mainfrom
table-splitting-validation
Open

davidkelly wants to merge 1 commit into
mainfrom
table-splitting-validation

Conversation

@davidkelly

@davidkelly davidkelly commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

The issue in brief: the provider writes one document per entity, in its type's collection, keyed only by the primary key. It accepted two mappings that cannot work like that:

  • Table splitting (two entity types that are not owned types, in one collection): both types write to the same document key. An insert fails with DocumentExistsException, and an update overwrites the other type's fields. This caused most of the spec-test "seeding inserts a key that already exists" failures.
  • TPT: queries join the base type's collection, but saves write only to the derived type's collection. On a cluster, a saved Dog was stored in the Dog collection only, and ctx.Animals, OfType<Dog>() and ctx.Dogs all returned nothing.

Both now fail when the model is built, with a message that says what to do instead.

Breaking: a model that uses table splitting or TPT now throws at startup. Before, it built, and then failed or returned wrong results at run time.

Change

  • CouchbaseModelValidator rejects:
    • entity types from different hierarchies (not owned, with a key) mapped to one collection. The fix it suggests: give each type its own collection, or make the dependent an owned type (OwnsOne).
    • a TPT hierarchy: UseTptMappingStrategy(), or a derived type in a different collection from its root with no strategy set. The fix it suggests: TPH.
  • Collection names are compared in full (bucket.scope.collection): a bare name is resolved with the context's bucket and scope first. To do that, the validator is registered with a factory that passes them in (bucket and scope are already part of the service-provider key).
  • TPH and TPC are still accepted. On a cluster, TPC saves, base-set queries, Find, updates and deletes all work, so docs/limitations.md now describes what TPC supports. It also states one limit: keys are not checked across the hierarchy, so two types can save the same key.
  • docs/limitations.md and the CHANGELOG (Breaking) describe both rules.

Spec tests

  • The ComplexNavigations shared-type classes are removed. They map Level2–Level4 into Level1's collection, so every test failed. That removes their 1,240 known-failures lines.
  • The ManyToMany and F1 fixtures give their table-splitting types their own collections and map their TPT hierarchies as TPH, so their other tests keep running (helpers in CouchbaseSpecModel). The F1 classes already fail completely for an unrelated reason (the SwagBag table mapping), so nothing changes for them yet.
  • 2 lines added to known-failures: AdHocAdvancedMappingsQueryCouchbaseTest.Hierarchy_query_with_abstract_type_sibling_TPT, which tests TPT itself.
  • root-causes.tsv: rows for the two new errors.

Tests

  • Unit (CouchbaseMappingValidationTests, 15): rejected and accepted mappings, including bare and full names for the same collection, and TPH and TPC hierarchies. With the table-splitting rule turned off, 6 fail; with the TPT rule turned off, 2 fail. Full unit suite 1,246/1,246.
  • A TPH model built with ConfigureToCouchbase keeps every type in the root's collection, so it is not rejected (checked with and without ToTable and lowercase names).
  • Compliance tests pass. Integration 409/409 (one known flake passed on rerun).
  • Spec runs on a cluster over the 40 affected classes (ManyToMany, F1, NonShared, AdHoc, GearsOfWar, TPC/TPH inheritance and others): no new failures, apart from ManyToManyTrackingCouchbaseTest.Can_Attach_or_Update_a_many_to_many_with_mixed_set_and_unset_keys. Its 4 variants fail at random from run to run, it does not use the entities this changes, and 2 of the variants are already in the baseline.

Merge note: this conflicts with #193 in root-causes.tsv. Whichever merges second needs a small rebase.

Ticket: CBEF-133

🤖 Generated with Claude Code

Motivation
==========
The provider writes one document per entity, in the collection of
the entity's type, keyed only by the primary key. Two mappings do not
fit that, but the provider accepted them. With table splitting, two
entity types in one collection write to the same document key: an
insert fails with DocumentExistsException and an update overwrites
the other type's fields. With TPT, queries join the base collection,
which the save path never writes to, so they return nothing.

Modification
============
- CouchbaseModelValidator rejects a TPT hierarchy, and entity types
  from different hierarchies (not owned, with a key) in one
  collection. Bare collection names are resolved with the context's
  bucket and scope first. The errors name the types and collections
  and say what to do instead (own collection or owned type; TPH).
- Unit tests for the rejected and the accepted mappings.
- Spec tests: remove the ComplexNavigations shared-type classes, which
  map Level2-Level4 into Level1's table, and their 1,240
  known-failures lines. The ManyToMany and F1 fixtures give their
  table-splitting types their own collections and map their TPT
  hierarchies as TPH, so their other tests keep running.
- Document both limits, describe what TPC supports, add a CHANGELOG
  entry and correct the seed-doc-exists root-cause description.

Results
=======
Both mappings fail when the model is built, with a message that says
what to do instead. Unit, integration and compliance tests pass, and
the affected spec classes have no new failures.

@emilienbev emilienbev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Both rules are right for the provider today, and both messages name the types, the collections and a fix.

My concerns.

  • A bare collection name already fails at the first save and the first query. So the bucket and scope injection guards a model that cannot run, and the docs now read as if bare names work.
  • EF already marks TPT on the root, so the table comparison looks unneeded.
  • The TPC text in the docs is a bit ahead of the code for an abstract base with ConfigureToCouchbase.
  • On the spec numbers. Removing the ComplexNavigations classes drops 1,240 known failures with no new pass. I agree with removing them, but maybe we track the pass count next to the list size? Could those fixtures run later with Level2 to Level4 as owned types?

FYI for after 2.0. Several entity types in one collection is a normal Couchbase pattern. To support it we would need a type field, a type filter in queries and likely a key prefix.

/// The full <c>bucket.scope.collection</c> name of a table. A bare name stays as it is when the
/// context has no bucket or scope.
/// </summary>
private string CollectionOf(string table)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Small thing. A bare table name throws at the first save and the first query, since ParseKeyspace and CouchbaseKeyspace.Parse both need three parts. Could we drop the bucket and scope injection and group by the table name as it is?


var strategy = root.GetMappingStrategy();
var rootTable = root.GetTableName();
if (strategy != RelationalAnnotationNames.TptMappingStrategy

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Small thing. EF's EntityTypeHierarchyMappingConvention already sets TPT on the root when a derived type has its own table, so I think root.GetMappingStrategy() == TptMappingStrategy is enough. Could we drop the table comparison?

{
// Before the base validation, so that these mappings get a message that says what to do
// instead. EF Core rejects some of them (unrelated types in one table) with its own message.
ValidateNoTablePerType(model);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nit. EF already groups types by table and calls ValidateSharedTableCompatibility once per table. Maybe override that one, check the distinct roots, then call base? Then the extra pass and this comment can go.

/// <remarks>
/// Types in one inheritance hierarchy (TPH) share a collection; that is supported. An owned
/// type is stored inside its owner's document, so it is not checked. A keyless type is never
/// saved, so it cannot overwrite a document, and it is not checked either. A bare collection

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nit. These remarks restate the Where clause below. Maybe keep the summary only, in two lines?

$"The entity types {names} are mapped to the same collection '{collection.Key}'. "
+ "The Couchbase provider does not support table splitting: each entity is stored as its own "
+ "document, keyed by its primary key, so these entity types would write to the same document. "
+ "Map each entity type to its own collection, or make the dependent type an owned type "

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nit. This also fires for two unrelated types that someone put in one collection on purpose, and "the dependent type" does not fit them. Maybe add that the provider stores one entity type or one hierarchy per collection?

Comment thread docs/limitations.md
is mapped to a different collection than its base type is TPT, also without
`UseTptMappingStrategy()`.
* **Table-per-concrete-type (TPC) works for basic use.** Each concrete type is stored in its own
collection. An abstract base type has no collection. Add, query, `Find`, update and delete work

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Small thing. The harness has to clear the collection of an abstract TPC base after ConfigureToCouchbase, EF rejects it otherwise. Could we add that caveat here, or fix ConfigureToCouchbase in a follow-up?

}

[Fact]
public void Tph_HierarchyInOneCollection_IsAccepted()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Small thing. I see no test for TPH through ConfigureToCouchbase, and the comment in CouchbaseSpecModel.Apply says it gives each derived type its own collection. Could we add one with a derived type that sorts before its root, like Car and Vehicle?

{
var ex = Assert.Throws<InvalidOperationException>(() => BuildModel(mb =>
{
mb.Entity<Order>(b =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nit. Six tests build the same Order and OrderDetails model and only change two collection names. Maybe a helper or a Theory? The ComplexProperty assert can go, the message never has that word.

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.

2 participants