Repository navigation
CBEF-135: Set the generated key of owned collection items on save - #196
davidkelly wants to merge 2 commits into
Conversation
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
left a comment
There was a problem hiding this comment.
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
Idproperty 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 yourTagmodel. I think this one is worth fixing before merge. It is not a regression,mainwrote the same document and then threw, but now the save succeeds and the mismatch goes unseen. - The unit tests call
AssignOwnedCollectionKeysthemselves, so they still pass if the call inSaveChangesAsyncis removed. They also read the entry and never the document. RefreshOwnedCollectionSnapshotsis now a second copy ofCouchbaseCollectionSnapshot.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.
|
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
left a comment
There was a problem hiding this comment.
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))) |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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?
The issue in brief: saving an
OwnsManycollection 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__synthesizedOrdinalwithToJson()), and the provider never set that integer. After the save every item had 0, and the provider's save interceptor threwInvalidOperationException("... is already being tracked"). It threw after the document was written, so a retry failed withDocumentExistsException. This is the default shape for an owned collection, and the integration tests missed it because their item type has an explicitId.Change
CouchbaseDatabaseWrapper.AssignOwnedCollectionKeysruns 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 anintorlongkey 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.RefreshOwnedCollectionSnapshotsnow creates the owned-collection snapshot for an owner that has none, throughCouchbaseCollectionSnapshot.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 laterSaveChangesAsync. That bug was hidden until now, because the first save threw.Tests
OwnsManyandToJson(), 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 ashortkey (both left alone).SaveChangesAsyncwith a recordingICouchbaseClientWrapper(CouchbaseOwnedCollectionSaveTests): they check the written documents for keyless items, a CLRIdleft 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.OwnedCollectionKeyTestssaves 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 plainOwnsManyonly, because the query path does not supportToJson()collections. Full suite 409/410; the one failure is the knownEnsureCreatedSeedingTestsrace, which passed on two reruns.FindCouchbaseTestclasses go from 0/411 to 387/411.JsonQuery/JsonUpdatestill also need CBEF-134 and the known "relational model built twice for JSON entity types" fix.Ticket: CBEF-135
🤖 Generated with Claude Code