Skip to content

CBEF-135: Set the generated key of owned collection items on save - #196

Open
davidkelly wants to merge 2 commits into
mainfrom
owned-collection-keys
Open

davidkelly wants to merge 2 commits into
mainfrom
owned-collection-keys

Conversation

@davidkelly

@davidkelly davidkelly commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

The issue in brief: saving an OwnsMany collection whose item type has no key of its own fails once it has two or more items. EF Core keys each item by its owner's key plus an integer it generates (Id, or __synthesizedOrdinal with ToJson()), and the provider never set that integer. After the save every item had 0, and the provider's save interceptor threw InvalidOperationException ("... is already being tracked"). It threw after the document was written, so a retry failed with DocumentExistsException. This is the default shape for an owned collection, and the integration tests missed it because their item type has an explicit Id.

Change

  • CouchbaseDatabaseWrapper.AssignOwnedCollectionKeys runs before any document is built. It gives each added item with a temporary key value a number unique within its collection: the highest existing value plus one (so 1, 2, 3 for a new collection). A key value the app set is kept. It applies only to an int or long key that contains the owner's foreign key. A shadow key is not stored: owned items are written without shadow properties and rebuilt from the document when read. When the item type has its own CLR key property, the value is also set on the object before the document is built, so the document and the tracked object agree.
  • RefreshOwnedCollectionSnapshots now creates the owned-collection snapshot for an owner that has none, through CouchbaseCollectionSnapshot.Record (one copy of the snapshot code). Change detection reads field-only collections too, the same way. Before, only entities read by a query had one, so changes to the collections of an entity added in the same context were silently not saved by a later SaveChangesAsync. That bug was hidden until now, because the first save threw.
  • CHANGELOG (Fixed).

Tests

  • Unit: 9 new tests, with no cluster. Each one does what the save does around the write (detect changes, assign keys, accept changes, detect changes again). They cover plain OwnsMany and ToJson(), nested collections, two owners, adding after a save, and app-set keys. Without the fix, 8 fail; if existing values are ignored, the 2 add-after-save tests fail. More tests cover a CLR key left at 0, a key of the generated property alone, and a short key (both left alone).
  • Unit, through SaveChangesAsync with a recording ICouchbaseClientWrapper (CouchbaseOwnedCollectionSaveTests): they check the written documents for keyless items, a CLR Id left at 0 (document has 1 and 2), and a failed save followed by a retry. They fail if the call in the save is removed. 1,246/1,246 pass.
  • Integration: OwnedCollectionKeyTests saves two keyless items, changes one and adds one in the same context, reads back, adds again, and reads back. It fails without either change (one change at a time). It is plain OwnsMany only, because the query path does not support ToJson() collections. Full suite 409/410; the one failure is the known EnsureCreatedSeedingTests race, which passed on two reruns.
  • Spec, local 3-node 8.0.1 cluster, on CBEF-131: Fix legacy keys with non-public parts; default to V2 keys #193's branch with this change: no new failures, and 411 tests now pass. All three FindCouchbaseTest classes go from 0/411 to 387/411. JsonQuery/JsonUpdate still also need CBEF-134 and the known "relational model built twice for JSON entity types" fix.

Ticket: CBEF-135

🤖 Generated with Claude Code

Motivation
==========
An OwnsMany item type with no key of its own is keyed by its owner's
key plus an integer EF Core generates (Id, or __synthesizedOrdinal
with ToJson()). The save path never replaced its temporary value, so
after the save every item had 0. With two or more items, change
detection in the save interceptor threw "already being tracked" after
the document was written. Also, an entity added in a context got no
owned-collection snapshot, so later changes to its collections in the
same context were not saved.

Modification
============
- AssignOwnedCollectionKeys: before documents are built, give each
  added item with a temporary key its 1-based position; new items
  after a save get the highest existing value plus one. The value is
  not stored (owned items are written without shadow properties).
- RefreshOwnedCollectionSnapshots: create the snapshot for an owner
  that has none, not only refresh existing ones.

Results
=======
9 unit tests (plain and ToJson(), nested, two owners, add after save,
app-set keys kept) and an integration test that saves, changes, adds
and reads back. Each fails without its fix.

@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.

The layer and the EF calls look right. Cosmos and relational JSON also set the ordinal at save time with HasTemporaryValue and SetStoreGeneratedValue.

My concerns.

  • For an item type with its own Id property left at 0, the document gets 0 for every new item, while the tracked objects get 1, 2, 3 after the save. I ran it on a copy of your Tag model. I think this one is worth fixing before merge. It is not a regression, main wrote the same document and then threw, but now the save succeeds and the mismatch goes unseen.
  • The unit tests call AssignOwnedCollectionKeys themselves, so they still pass if the call in SaveChangesAsync is removed. They also read the entry and never the document.
  • RefreshOwnedCollectionSnapshots is now a second copy of CouchbaseCollectionSnapshot.Record.
  • Bigger picture, see my note on #192. The snapshot is a second change tracker that exists because owned collection items are not tracked on read, and this PR makes it cover more entities. I think that deserves its own design ticket.

Motivation
==========
Review of the owned collection key fix: an item type with a CLR Id
got 0 in the document, a key of the generated property alone was
numbered per owner and collided, short/byte keys could overflow, and
no unit test went through SaveChangesAsync.

Modification
============
- AssignOwnedCollectionKeys: set a CLR key property with SetProperty,
  so the object (and the document) has the value before the write.
  Shadow keys keep SetStoreGeneratedValue.
- GeneratedKeyProperty: the key must contain the whole ownership
  foreign key; int and long only. Shorter doc comment.
- Interceptor: refresh snapshots with CouchbaseCollectionSnapshot.
  Record; change detection reads fields too, like Record.
- Tests: SaveChangesAsync with a recording ICouchbaseClientWrapper
  (keyless items, CLR Id, add after save, retry after a failed
  write); key alone and short key left alone. The integration test
  drops its collection in a finally.

Results
=======
1246 unit tests pass. Each new test fails without its fix.
@davidkelly

Copy link
Copy Markdown
Contributor Author

Thanks @emilienbev. All seven points are in 6d50296. On the bigger picture: agreed that the snapshot is a second change tracker. Tracking owned collection items on read, and building owned items from the entries, are already work items in CBEF-136. Once they land, the snapshot can go.

@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.

A few small things left around Attach and the skipped key shapes.

.Max() + 1;

var clrType = Nullable.GetUnderlyingType(keyProperty.ClrType) ?? keyProperty.ClrType;
foreach (var e in itemEntries.Where(e => e.HasTemporaryValue(keyProperty)))

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. This also sets a value on items that are not Added. After Attach an item is Unchanged with a temporary key, so it becomes Modified with a new key, and the next save throws that Line.Id is read-only after it has been saved (I ran it). Could we add e.EntityState == EntityState.Added to this filter? With it the second save works.

itemsTable[nav.Name] = [];
}
}
Snapshot.Record(entry.Entity, ownedCollections, isTracking: true);

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. After any save this snapshots every Unchanged root, attached ones too, so Attach, Lines.Add, save writes nothing, but an empty save after Attach makes the same change get written (I ran both). Could we refresh only the roots this save wrote, which keeps the main behaviour until CBEF-136 and stops copying every tracked collection on every save? Or record the snapshot when a root starts being tracked, so Attach works too.


// The owned collections whose changes are detected: those the snapshot can read, through the
// property or, for a field-only navigation, the field.
private static IReadOnlyList<INavigation> OwnedCollectionNavigations(IEntityType entityType)

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: after every save this builds a new list for each Unchanged root, also for types with no owned collection. Could we cache it per entity type, like GetTrackedProperties? FYI, #192 changes these same loops to IsOwnedChild(), so this conflicts, and the helper can take that rule when you rebase.

}

// What SaveChangesAsync does around the write: detect changes, assign the keys, then accept the
// changes. Change detection after that is what threw before the keys were assigned.

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 comment and the summary of the integration test ("used to throw", OwnedCollectionKeyTests.cs:11) tell the history of the bug. Maybe say what the test checks instead?

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