diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md
new file mode 100644
index 00000000..46b8df6e
--- /dev/null
+++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md
@@ -0,0 +1,84 @@
+# 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.
+
+1. **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 private `ReconcileTagsAndGenresAsync` method in `BookRepository`, `AlbumRepository`, and `TrackRepository`.
+
+2. **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).
+
+3. **Scalar copy on edit**: `EditableValuesCopier` applies 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 with `CurrentValues.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: `UserRepository` locates 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.
+
+`Lumina.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 `Lumina.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
+
+- `EditableValuesCopier` is generic over `IAuditableEntity`. It reads the primary key from the Entity Framework metadata, so it enforces the key-matching contract for any entity without per-entity code.
+- `CollectionReconciler` is generic over existing item, incoming item, and key type.
+- `SharedReferenceResolver` is generic over `ISharedReferenceEntity`, 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 `CollectionReconciler` by 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 Mitigations
+
+| 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.
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Common/GenreEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/GenreEntity.cs
index 019ecd4a..5c1befd0 100644
--- a/src/Lumina.Application/Common/DataAccess/Entities/Common/GenreEntity.cs
+++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/GenreEntity.cs
@@ -11,4 +11,4 @@ namespace Lumina.Application.Common.DataAccess.Entities.Common;
[DebuggerDisplay("Name: {Name}")]
public record GenreEntity(
string? Name
-);
+) : ISharedReferenceEntity;
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Common/ISharedReferenceEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/ISharedReferenceEntity.cs
new file mode 100644
index 00000000..99d3b4b3
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/ISharedReferenceEntity.cs
@@ -0,0 +1,12 @@
+namespace Lumina.Application.Common.DataAccess.Entities.Common;
+
+///
+/// Interface for a shared reference entity, whose identity is its name and whose rows are shared across the whole storage medium instead of being owned by a single parent.
+///
+public interface ISharedReferenceEntity
+{
+ ///
+ /// Gets the name that identifies the shared reference.
+ ///
+ string? Name { get; }
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Common/TagEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/TagEntity.cs
index f020608f..21536ad8 100644
--- a/src/Lumina.Application/Common/DataAccess/Entities/Common/TagEntity.cs
+++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/TagEntity.cs
@@ -11,4 +11,4 @@ namespace Lumina.Application.Common.DataAccess.Entities.Common;
[DebuggerDisplay("Name: {Name}")]
public record TagEntity(
string? Name
-);
+) : ISharedReferenceEntity;
diff --git a/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs b/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs
index 40c99b54..3fa99b6b 100644
--- a/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs
+++ b/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs
@@ -60,12 +60,20 @@ internal static class CollectionReconciler
{
if (shouldReplace(matchedItem, incomingItem))
{
+ TExisting replacementItem = createNew(incomingItem);
existingItems.Remove(matchedItem);
- existingItems.Add(createNew(incomingItem));
+ existingItems.Add(replacementItem);
+ existingByKey[incomingKey] = replacementItem;
}
}
- else // The desired child has no tracked counterpart, so it is added as a new child.
- existingItems.Add(createNew(incomingItem));
+ else
+ {
+ // The desired child has no tracked counterpart, so it is added as a new child and indexed, so that a later desired child
+ // that reuses the same key is matched against it instead of adding a second row that would break the unique index.
+ TExisting addedItem = createNew(incomingItem);
+ existingItems.Add(addedItem);
+ existingByKey[incomingKey] = addedItem;
+ }
}
}
}
diff --git a/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs b/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs
index 003da754..915e921b 100644
--- a/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs
+++ b/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs
@@ -2,22 +2,26 @@
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
-using System;
+using Microsoft.EntityFrameworkCore.ChangeTracking;
+using Microsoft.EntityFrameworkCore.Metadata;
+using System.Collections.Generic;
+using System.Linq;
#endregion
namespace Lumina.DataAccess.Common.Persistence;
///
-/// Copies the editable scalar values of a mapped repository entity onto its tracked counterpart, while leaving the audit columns under the sole ownership of the auditing interceptor.
+/// Copies the editable scalar values of a mapped repository entity onto its tracked counterpart, while leaving the primary key and the audit columns under the sole ownership of the persistence medium.
///
internal static class EditableValuesCopier
{
///
- /// Copies the scalar values of onto the tracked entity, restoring the identity and audit columns afterwards,
- /// so that the tracked row is only considered modified when an editable value actually changed.
+ /// Copies the scalar values of onto the tracked entity, except for its primary key and its audit columns,
+ /// so that the tracked row is only considered modified when an editable value actually changed, and its stored identity is never reassigned.
///
///
- /// The audit interceptor stamps the modification columns of the rows that are actually modified. Copying the audit columns from the mapped entity would mark untouched
+ /// The primary key is not copied, so that a mapped entity carrying a different, or unset, key can never retarget the tracked row. The audit interceptor stamps the
+ /// modification columns of the rows that are actually modified, so the audit columns are not copied either: copying them from the mapped entity would mark untouched
/// rows as modified, which would then be stamped with a change that the user never made.
///
/// The type of the tracked and mapped repository entity.
@@ -26,14 +30,24 @@ internal static class EditableValuesCopier
/// The mapped entity carrying the desired values.
public static void CopyEditableValues(LuminaDbContext context, TEntity tracked, TEntity incoming) where TEntity : class, IAuditableEntity
{
- DateTime createdOnUtc = tracked.CreatedOnUtc;
- Guid createdBy = tracked.CreatedBy;
- DateTime? updatedOnUtc = tracked.UpdatedOnUtc;
- Guid? updatedBy = tracked.UpdatedBy;
- context.Entry(tracked).CurrentValues.SetValues(incoming);
- tracked.CreatedOnUtc = createdOnUtc;
- tracked.CreatedBy = createdBy;
- tracked.UpdatedOnUtc = updatedOnUtc;
- tracked.UpdatedBy = updatedBy;
+ EntityEntry trackedEntry = context.Entry(tracked);
+ EntityEntry incomingEntry = context.Entry(incoming);
+
+ // The primary key and the audit columns are owned by the persistence medium, so they are never copied from the mapped entity.
+ HashSet excludedProperties =
+ [
+ .. (trackedEntry.Metadata.FindPrimaryKey()?.Properties.Select(property => property.Name) ?? []),
+ nameof(IAuditableEntity.CreatedOnUtc),
+ nameof(IAuditableEntity.CreatedBy),
+ nameof(IAuditableEntity.UpdatedOnUtc),
+ nameof(IAuditableEntity.UpdatedBy)
+ ];
+
+ foreach (IProperty property in trackedEntry.Metadata.GetProperties())
+ {
+ if (excludedProperties.Contains(property.Name))
+ continue;
+ trackedEntry.Property(property.Name).CurrentValue = incomingEntry.Property(property.Name).CurrentValue;
+ }
}
}
diff --git a/src/Lumina.DataAccess/Common/Persistence/SharedReferenceResolver.cs b/src/Lumina.DataAccess/Common/Persistence/SharedReferenceResolver.cs
new file mode 100644
index 00000000..55d60ffa
--- /dev/null
+++ b/src/Lumina.DataAccess/Common/Persistence/SharedReferenceResolver.cs
@@ -0,0 +1,132 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.Common.Primitives;
+using Microsoft.EntityFrameworkCore;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.DataAccess.Common.Persistence;
+
+///
+/// Resolves shared reference rows, whose identity is their name, so that each distinct name is represented by a single tracked instance.
+///
+///
+/// This is the toolkit's only concern expressed over a family of entity shapes, through the marker interface:
+/// a shared reference is resolved by its name, the stored row wins over the incoming instance, and within-request duplicates are collapsed to one instance.
+/// No per-entity method is ever needed, so a new shared reference type adds no new persistence type. A shared reference whose name is null or whitespace
+/// cannot be keyed and would be lost silently, so it fails the resolution with the caller-provided error instead of being dropped.
+///
+internal static class SharedReferenceResolver
+{
+ ///
+ /// Resolves the single instance that represents each distinct name carried by .
+ ///
+ ///
+ /// The stored row wins over the incoming instance, so that a shared reference that is already persisted is reused instead of inserted again. The
+ /// instances are also collapsed by name, so that a name shared by several parents of the same request is only ever tracked once.
+ ///
+ /// The type of the shared reference entity.
+ /// The Entity Framework context the stored rows are read through.
+ /// The shared references carried by the entity that is about to be persisted.
+ /// The error returned when a shared reference carries a name that is null or whitespace.
+ /// Cancellation token that can be used to stop the execution.
+ /// A result containing either a dictionary that maps each distinct name to the single instance that represents it, or an error.
+ internal static async Task>> ResolveAsync(LuminaDbContext context, IEnumerable incomingEntities, Error invalidNameError, CancellationToken cancellationToken)
+ where TEntity : class, ISharedReferenceEntity
+ {
+ // A shared reference whose name is null or whitespace cannot be keyed, and the database requires the name to be present, so the whole resolution
+ // fails instead of silently dropping the reference.
+ Dictionary resolvedByName = new(StringComparer.Ordinal);
+ foreach (TEntity incomingEntity in incomingEntities)
+ {
+ string? name = incomingEntity.Name;
+ if (string.IsNullOrWhiteSpace(name))
+ return invalidNameError;
+ resolvedByName.TryAdd(name, incomingEntity);
+ }
+
+ if (resolvedByName.Count == 0)
+ return resolvedByName;
+
+ // Prefer the instances that the context already tracks, so that a reference resolved earlier in the same request does not trigger another query.
+ HashSet namesResolvedFromTrackedEntities = [];
+ foreach (TEntity trackedEntity in context.Set().Local)
+ {
+ string? trackedName = trackedEntity.Name;
+ if (!string.IsNullOrWhiteSpace(trackedName) && resolvedByName.ContainsKey(trackedName))
+ {
+ resolvedByName[trackedName] = trackedEntity;
+ namesResolvedFromTrackedEntities.Add(trackedName);
+ }
+ }
+
+ // Only the names that are not already tracked are read from the storage medium.
+ List unresolvedNames = [.. resolvedByName.Keys.Where(name => !namesResolvedFromTrackedEntities.Contains(name))];
+ if (unresolvedNames.Count > 0)
+ {
+ List storedEntities = await context.Set()
+ .Where(entity => unresolvedNames.Contains(EF.Property(entity, nameof(ISharedReferenceEntity.Name))))
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+
+ foreach (TEntity storedEntity in storedEntities)
+ resolvedByName[storedEntity.Name!] = storedEntity;
+ }
+
+ return resolvedByName;
+ }
+
+ ///
+ /// Maps to the single resolved instance that represents each of their names.
+ ///
+ /// The type of the shared reference entity.
+ /// The shared references that must be mapped to their resolved instances.
+ /// The resolved instances, as returned by .
+ /// The resolved instances, without any duplicate.
+ internal static IReadOnlyCollection Normalize(IEnumerable incomingEntities, IReadOnlyDictionary resolvedEntities)
+ where TEntity : class, ISharedReferenceEntity
+ {
+ HashSet normalizedEntities = [];
+ foreach (TEntity incomingEntity in incomingEntities)
+ {
+ string? name = incomingEntity.Name;
+ if (string.IsNullOrWhiteSpace(name))
+ continue;
+ if (resolvedEntities.TryGetValue(name, out TEntity? resolvedEntity) && resolvedEntity is not null)
+ normalizedEntities.Add(resolvedEntity);
+ }
+ return normalizedEntities;
+ }
+
+ ///
+ /// Reconciles the shared reference collection against , reusing the stored rows whose names already exist.
+ ///
+ /// The type of the shared reference entity.
+ /// The Entity Framework context the stored rows are read through.
+ /// The tracked collection that is reconciled in place.
+ /// The desired shared references.
+ /// The error returned when a shared reference carries a name that is null or whitespace.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ internal static async Task> ReconcileAsync(LuminaDbContext context, ICollection existingEntities, IEnumerable incomingEntities, Error invalidNameError, CancellationToken cancellationToken)
+ where TEntity : class, ISharedReferenceEntity
+ {
+ List incomingList = [.. incomingEntities];
+ Result> resolveResult = await ResolveAsync(context, incomingList, invalidNameError, cancellationToken).ConfigureAwait(false);
+ if (resolveResult.IsFailure)
+ return resolveResult.Errors;
+
+ CollectionReconciler.Reconcile(
+ existingEntities,
+ Normalize(incomingList, resolveResult.Value),
+ existingEntity => existingEntity.Name!,
+ incomingEntity => incomingEntity.Name!,
+ shouldReplace: (existingEntity, incomingEntity) => false,
+ createNew: incomingEntity => incomingEntity);
+ return Result.Updated;
+ }
+}
diff --git a/src/Lumina.sln b/src/Lumina.sln
index c7723dbb..7aedef91 100644
--- a/src/Lumina.sln
+++ b/src/Lumina.sln
@@ -161,6 +161,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log",
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0011.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0011.md
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0012.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0012.md
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0013.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0013.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0014.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0014.md
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "domain", "domain", "{3EE8EFDF-4D55-4EA3-BEE2-74D00CB50570}"