Appearance
ADR 0013 — Auth token generation and the transactional save protocol
- Status: Accepted design; implementation and validation tracked in the planning ledger
- Date: 2026-10-22
- Baseline:
develop,24af51bcb45b449cb2b1514723fe0387caab4974 - Related: ADR 0012, platform pending list
Context
Auth changes authorization inside its save loop. A membership or role event reaches the real AuthorizationAffectingEventHandler, which advances the affected users' TokenVersion; the loop persists those changes before confirming the transaction. Durable integration reactions must not replace that transactional invariant.
Two independent writers could both load generation N and commit N+1. A token issued between those commits would not distinguish the second revocation. The column was indexed but had no optimistic concurrency precondition. An index does not prevent a lost increment.
The public bool overloads of SaveChanges also called EF directly. They could commit membership and profile changes without dispatching the authorization marker. PostgreSQL regressions written before the correction reproduced both defects with real contexts, repositories, resolver, mediator and marker handler. Cache effects alone were recording doubles; they were not used as SQL proof.
Decision
Generation belongs to the tracked write snapshot
User.TokenVersion remains an integer initialized to 1. InvalidateAllTokens validates its reason and computes the next value in a checked expression before changing the counter, audit state or events. Exhaustion throws; it does not wrap, reset, saturate or silently repair historical data. Two successful invalidations on the same aggregate can advance N to N+2 before a save.
Rotating an existing password checks that capacity before changing the credential. A caller that catches an overflow must not be left with a replacement password staged without its revocation. This precheck covers token-generation exhaustion; it is not a new claim that every invalid input to every compound domain operation is free of in-memory mutation.
The EF property is a concurrency token. Updates to an existing User compare the original generation loaded by that context. A competing revocation that committed first causes DbUpdateConcurrencyException; the losing unit must roll back all its SQL changes. A subsequent business attempt reloads and reconstructs its intent in a new context. It does not overwrite the original value, reload a poisoned tracker or replay the old callback automatically.
This is an EF write precondition, not a database trigger. Every writer must adopt the mapping and protocol. An old binary or raw SQL can bypass it. The counter is also not a general profile row version: two profile edits that do not advance it can still share the same generation.
Mutation loaders and repository updates preserve the original value
UserRepository.UpdateAsync accepts the same tracked, non-deleted instance, including an Added instance. It preserves the current tracking state, original values and property modifications. It rejects Detached and Deleted instances. It does not attach a mutated copy, merge CurrentValues, merge events from another instance or mark the entire root Modified.
A save guard rejects decreasing an existing User's current generation below its original value. It executes inside the existing transactional failure frame before each SQL batch. It does not repair values or claim to protect arbitrary manipulation of OriginalValues by trusted host code.
Mutation loaders explicitly use tracking even when a host selects NoTracking as its read default. The new GetByEmailForUpdateAsync and GetUserByExternalIdentityForUpdateAsync keep the existing matching, identity normalization and query filters while loading the relationships needed by their mutation paths. Existing read lookups remain untracked. ForUpdate denotes a tracked mutation snapshot; these methods do not acquire a PostgreSQL FOR UPDATE lock.
AccountLinker uses these loaders in its three formerly detached mutation paths. A known identity's LastUsedAt and a newly linked identity must persist as tracked children; merely attaching the root or returning a successful mock is insufficient evidence.
Every supported save entry point executes the same protocol
SaveChanges() delegates to SaveChanges(true), and SaveChangesAsync(ct) delegates to SaveChangesAsync(true, ct). Both bool=true variants run the full Auth event loop, with the same transaction ownership, execution-strategy boundary, audit handling and write-failed protection.
Each internal persistence iteration calls base.SaveChanges(true) or base.SaveChangesAsync(true, ct) directly. Calling the base overload without bool would dispatch virtually back into the public bool override and could recurse. There is no general bypass flag that a reentrant callback could reuse to avoid the protocol.
acceptAllChangesOnSuccess=false is explicitly unsupported and throws NotSupportedException before audit-field preparation, SQL or dispatch. The event loop must accept each persisted batch before saving mutations generated by its handlers. Silently accepting batches would violate false; not accepting them would leave inserts and original values pending for the next iteration. Supporting a genuine false contract would require a separate tracker-snapshot design.
The Auth composition assigns the marker one dispatch route
The save loop publishes each concrete event through MediatR and then invokes its IAuthorizationAffectingEvent handlers explicitly. The Auth application scan must therefore register AuthorizationAffectingEventHandler only under INotificationHandler<IAuthorizationAffectingEvent>. MediatR's scan can otherwise also bind that handler to concrete authorization events that have their own consumers, causing one event to advance the same user's generation twice.
Both public Auth application compositions remove only non-keyed, concrete notification descriptors whose implementation type is exactly that marker handler. The marker-interface registration and its lifetime remain intact, as do the concrete platform-role audit and tenant-cache consumers. The shared Core scanner, event loop and transaction protocol do not change. Repeating the supported Auth/Core composition does not reintroduce those derived registrations.
This is registration ownership, not runtime deduplication: two distinct authorization events in one unit still produce two marker visits and two increments for a user affected by both. A manual host must register the marker only through its interface and retain the concrete consumers. A new raw MediatR scan or deliberate duplicate factory/instance registration after Auth composition remains the host's responsibility. This does not provide persistent exactly-once processing or outbox replay semantics, and it does not make external cache effects transactional.
Failure and transaction ownership remain explicit
The context rolls back a transaction it owns. When joining a managed external unit of work, it propagates failure and remains write-failed so that the unit cannot commit partial work even when a callback catches the original exception. A raw caller that catches an error and commits its manually owned transaction is outside that supported protocol.
A commit exception can mean an unknown outcome. Do not decrement the generation or automatically replay tracked changes. Verify the business state in a fresh context before a new attempt. A matching generation alone does not identify which operation committed.
When a concurrency exception reaches the existing HTTP exception boundary, its established 409/DB_CONCURRENCY_CONFLICT mapping remains available. This decision does not assert that every handler forwards every exception unchanged; existing command-specific error handling still applies.
Compatibility and rollout
Custom implementations of IUserRepository and IExternalIdentityRepository must implement the new mutation loaders. Consumers that passed detached User objects must load the aggregate for mutation before applying their intent. Consumers of the bool=false save overload must use the supported Auth protocol or design a separate persistence boundary; false no longer bypasses invariants.
The migration records concurrency metadata in the model snapshot. It does not introduce a new column, rewrite Users, reset generations or create a trigger. Follow the host's normal migration and deployment procedure, and update all writers before relying on the concurrency guarantee. Mixed old and new writers are not a substitute for a database-enforced policy.
Validation contract
The original failing regressions remain unchanged in their behavioral assertions: two membership revocations from the same User snapshot require one winner and rollback of the losing membership; public sync and async bool=true saves must execute the real marker exactly once. Positive controls prove that the fixture could dispatch through the ordinary save path before the correction.
Additional PostgreSQL tests cover stale profile writes, detached copies versus the canonical tracked instance, original generation preservation, host NoTracking defaults, child persistence, supported and refused save entry points, transaction rollback and failure protection. Domain tests cover successive generations, invalid reasons and overflow before mutation. Actual executed results and merge status belong to the planning ledger, not to the presence of this test list.
Limits and subsequent work
This decision does not change TokenVersionResolver, Redis/L1 authority, the authorization marker's blacklist calls, refresh/global token formats, issuance, logout, JTI reuse or MFA. Existing external cache effects before SQL commit can still survive rollback. SQL concurrency alone does not close CA-22/23/24, P16 or P1.
Before moving those effects out of the transaction, a separate stage must prove committed authority and generation binding for access, refresh, grace, global selection and emission, including legacy tokens and cached grants. It must not stamp a new generation onto authentication or permissions validated under an older one. The later Auth outbox adoption follows that proof; a worker must never become the authority that decides whether a revoked session can still authorize an act.