11 KiB
Architecture Decision Record (ADR): 0014 - Closed Generic Persistence Toolkit for Aggregate Graph Persistence
Status
Accepted (2026-09-26)
Context
Repositories in the DataAccess layer persist aggregate graphs: they load a tracked root entity, apply the edited scalar values, reconcile child collections, and add or update shared reference rows. This work was implemented independently in each repository, which produced duplication and drift.
-
Shared reference handling: a shared reference row (a tag or a genre) is keyed by its name and is shared across the whole database. When a graph is inserted or updated, the stored rows whose names already exist have to be reused instead of re-inserted, so that the shared tables are not duplicated, and a name shared by several parents of one request must be tracked only once. This logic existed inline in
BookRepository, and as a privateReconcileTagsAndGenresAsyncmethod inBookRepository,AlbumRepository, andTrackRepository. -
Child collection reconciliation: the same identity-preserving reconcile logic was repeated for every child collection of every aggregate (contributors, ratings, ISBNs, tags, genres, moods, ISRCs, content locations, permissions).
-
Scalar copy on edit:
EditableValuesCopierapplies editable scalar values while leaving the audit columns to the auditing interceptor. Seven auditable repositories (Role,LibraryScan,ScheduledJob,ScheduledJobExecution,Theme,User,UserSettings) still copied scalars withCurrentValues.SetValues, which writes every scalar property, including the primary key and the audit columns. Writing the primary key is destructive whenever the tracked row was located by a key other than its primary key:UserRepositorylocates the row by username, so an incoming entity whose Id differs from, or is unset relative to, the stored one would retarget the tracked row's identity, leaving the guarantee "the stored identity is never overwritten by an edit" to caller convention instead of to the code.
Nemera.DataAccess\Common\Persistence already held CollectionReconciler and EditableValuesCopier, but there was no shared reference primitive and no explicit boundary defining what may live there, so the shared reference concern was expressed per type and per repository.
Decision
Treat Nemera.DataAccess\Common\Persistence as a closed set of generic, entity-agnostic primitives that express the whole of aggregate graph persistence. Per-entity logic stays in the repository, and cross-cutting logic is generalized rather than specialized.
The closed set
| Primitive | Responsibility |
|---|---|
EditableValuesCopier |
Copies only the editable scalar values onto the tracked entity. The primary key is never written, so the tracked identity always wins over the incoming one regardless of how the row was located, and the audit columns are never written, so the auditing interceptor remains their only writer. |
CollectionReconciler |
Reconciles a tracked child collection against a desired set by key selectors, preserving the identity and audit columns of the children that already exist. |
SharedReferenceResolver |
Resolves shared reference rows by name so each distinct name maps to a single tracked instance. The stored row wins over the incoming instance, and within-request duplicates are collapsed. |
Genericity rules
EditableValuesCopieris generic overIAuditableEntity. It reads the primary key from the Entity Framework metadata, so it enforces the key-matching contract for any entity without per-entity code.CollectionReconcileris generic over existing item, incoming item, and key type.SharedReferenceResolveris generic overISharedReferenceEntity, a marker interface implemented by the shared reference records (TagEntity,GenreEntity). This is the one concern that is shaped by a family of entities, expressed through the marker interface rather than through per-entity code, so a new shared reference type adds no new persistence type.
Application
- Insert resolves shared references across the whole aggregate, then normalizes every collection of the aggregate to the resolved instances.
- Update reconciles the tracked shared reference collections in place, reusing the stored rows.
- Scalar edits go through
EditableValuesCopier. The repository decides how the tracked row is located (by its primary key, or by a natural key such as the username), and the copier keeps that row's primary key and audit columns untouched, so the incoming entity never has to carry a matching key. - Child collections are reconciled through
CollectionReconcilerby a stable key.
Consequences
Positive Outcomes
| Aspect | Benefit |
|---|---|
| Bounded surface | The folder holds exactly three generic types; new entity types and new shared reference types add no persistence type |
| Consistency | Every repository persists graphs the same way, with the same identity and audit semantics |
| Correctness | Audit columns are never overwritten by an edit, and shared reference rows are never tracked more than once per request |
| Identity preservation | The tracked primary key is never overwritten by an edit, even when the incoming entity carries a different, or unset, key, so locating a row by a natural key stays safe |
| Testability | The primitives are covered directly by unit tests, independently of any repository |
| Ownership | No new external dependency and no declarative engine; the toolkit depends only on the internal ISharedReferenceEntity marker, and the logic stays explicit and inspectable |
Risks and Tradeoffs
| Risk | Mitigation Strategy |
|---|---|
The generic resolver depends on an entity keyed by Name and translated by EF Core |
SharedReferenceResolver is generic over ISharedReferenceEntity and is exercised by both unit and integration tests, which prove the EF translation |
| A future concern is generalized before its shape is stable | The rule permits keeping a concern in the repository until it can actually be generalized, rather than extracting speculatively |
Behavior change from applying EditableValuesCopier to the seven repositories |
Covered by the DataAccess and Presentation.Api integration suites, which pass across the migrated repositories |
| The copier relies on Entity Framework metadata to find the primary key | Unit tests copy onto a tracked entity whose incoming key does not match, and assert that the stored identity and audit columns survive |
Alternatives Considered
1. Keep graph persistence duplicated in each repository
Leave the shared reference handling, collection reconciliation, and scalar copy implemented per repository.
Rejected: the duplication and the drift are the problem this decision addresses. Shared reference handling in particular has a single general shape, and repeating it per repository is what allows the shared-table and audit-column defects above to reappear.
2. Declarative aggregate persistence profiles
Introduce a generic persistence engine driven by a per-aggregate profile describing scalar copy behavior, child collections, and shared lookups, reducing repositories to load and apply.
Rejected: it is effectively a small in-house ORM, with functional and ownership costs disproportionate to the problem. The closed generic toolkit achieves the stated goal, keeping graph persistence explicit, without a new abstraction layer to own.
3. Model tags and genres as owned value objects
Stop modeling shared references as a shared table keyed by name, and store them per aggregate, removing the duplicate-key-in-graph class of bug at the source.
Rejected: it requires a database schema change and changes query behavior for shared references, which is out of scope. The shared tables are kept, and the concern is handled where it belongs, in the persistence toolkit.
Amendment: Set-Based Playlist Entry Operations (2026-10-20)
The playlist entries are mutated by set-based storage operations because a playlist can hold a whole library. The batched raw append and the ExecuteUpdateAsync and ExecuteDeleteAsync move and removal statements bypass the change tracker and therefore also bypass the auditing interceptor.
Those operations stamp UpdatedOnUtc and UpdatedBy on the playlist row themselves, stamp the creation or update audit columns of the entry rows they write, and increment the playlist concurrency token, in the same transaction. This is the only exception to the rule that the auditing interceptor is the only writer of the audit columns. Details edits still go through EditableValuesCopier and leave the audit columns to the interceptor. The exception is confined to PlaylistRepository and is documented in the class remarks.
Ordering is storage owned as well. The unique index on (PlaylistId, Position) is the enforced invariant, and the positions are sparse order keys rather than dense indices. A move normally changes one key to the midpoint between its new neighbors, and a removal deletes one row, so neither rewrites the following range. If repeated midpoint moves exhaust the numeric gap between two neighbors, a rare rebalance respaces the keys with a temporary table and two passes so the unique index is never violated. The domain only rejects duplicate positions on reconstitution, so a storage gap is readable instead of making the playlist impossible to load.
Amendment: Playlist Entry Count and Change Detection (2026-10-21)
The playlist row now carries a denormalized EntryCount, maintained by the set-based append and removal operations in the same statement that updates the playlist activity time and concurrency token. Window reads, moves and the single-add read-back use that column instead of counting the entries of the playlist, so none of them scan an index proportional to the playlist size.
Details edits still go through EditableValuesCopier, but the copier now compares the incoming value with the tracked value before assigning it and marks only an actual change as modified. PlaylistRepository.UpdateAsync also compares the tracked original values explicitly before it decides to increment the concurrency token, so a no-op save neither restamps the row nor bumps its version.
Amendment: Explicit Audit Identity for Application Initialization (2026-11-20)
The one-time application initialization is the only save whose audit identity is provided explicitly instead of being stamped by the auditing interceptor. The setup handler creates the original administrator account before any user exists, and the seed service creates the default permissions, roles, role-permission grants, user-role link and scheduled jobs in the same anonymous flow. Those rows therefore cannot derive an actor from ICurrentUserService.
The bootstrap code sets CreatedBy to the fixed SYSTEM audit identifier 11111111-1111-1111-1111-111111111111 and sets CreatedOnUtc from IDateTimeProvider, then saves through SaveChangesAsInitializationAsync. That method marks the save on the NemeraDbContext for its duration, and the interceptor skips its stamping only for that save. No other save path is affected.
The SYSTEM identity is never inferred from a missing authenticated user. Ordinary anonymous creation and modification remain unattributed with Guid.Empty, and the interceptor is still the sole writer for every ordinary save. The initialization exception exists because the app has no user account to attribute the bootstrap rows to, and it is confined to the setup and seed code paths.