Architecture Decision Record
ADR-075: Audit Trail (Same-Transaction Field-Level Change History)
Status
Accepted (2026-08-13; corrected 2026-08-14: the adoption sweep and the ApplicationDbContext line
citations). The implementation lands in the MMCA.Common "enterprise capability wave" release
and is opt-in at three gates: AddAuditTrail(configuration) registers the interceptor, the settings, the
reader and the retention job, AuditTrail:Enabled (default false) maps the table and turns capture on, and
an entity is audited only when it carries the IAuditedEntity marker. Absent registration the interceptor
is not resolved and the whole feature is a no-op.
Revised 2026-09-07 (Store pins the reverse [Pii] convention with a fitness test, and deployed SQL
auditing backstops the in-database trail).
Revised 2026-09-25 (both apps' SQL auditing now records UPDATE and DELETE statements against the trail
table, by different means, and the code anchors are refreshed).
Revised 2026-10-01 (retention has no fallback: without the scheduler nothing is purged; see Revision below).
Revised 2026-10-06: inserts and deletes write one summary row, a store-generated key is fixed up by an UPDATE after the save, and ADC's trail-DML auditing therefore fires on routine inserts too.
Revised 2026-10-07: the key fix-up issues one filtered UPDATE per pending row rather than one statement covering all of them, AuditTrailSettings also carries DataSource (the engine the reader queries), and anchors are refreshed after the v1.233.0 release.
Revised 2026-10-21: redaction also covers [Sensitive] properties, IAuthUser credentials and encrypted columns, the reverse [Pii] rule lives in the shared PiiConventionTestsBase that Store, ADC and Helpdesk subclass, a fixed-up key equal to the captured one skips its UPDATE, and anchors are refreshed.
Revised 2026-10-26: the key fix-up writes the resolved key to the tracked trail row after each UPDATE and syncs its snapshot so that write is not saved again, and the reader and interceptor anchors are refreshed.
Revised 2026-10-28: anchors refreshed after later ADC and Store infra/main.bicep changes moved the SQL-auditing anchors, and ADC's User [IdValueGenerated] anchor moved one line.
Revised 2026-11-12: the framework ships an opt-in viewer (the AuditHistoryControllerBase endpoint, the audit:view permission and the AuditHistoryPanel), the read DTO moved to Shared as AuditHistoryEntryDTO, and the earlier "no controller and no UI" position is recorded under Alternatives rejected as revisited.
Revised 2026-11-23: redaction also covers every column of an owned value object behind a [Pii] navigation and the ITwoFactorUserState credentials (with IsTwoFactorEnabled kept readable), ADC's audited Ticket also takes the store-generated-key UPDATE, and anchors are refreshed after the later Common, Store and ADC releases.
Context
The framework already answers "who touched this row last". Every AuditableBaseEntity carries
CreatedOn/By and LastModifiedOn/By, stamped by AuditSaveChangesInterceptor on the way into
SaveChangesAsync. What it cannot answer is "what changed". The stamps are a single overwrite: the
current value of LastModifiedBy erases the previous one, so a row that has been edited nine times
carries the ninth editor and nothing else. Soft-delete (ADR-005) preserves the row, not its history.
That gap becomes concrete the moment a regulated or contested question arrives: which administrator moved this ticket's priority, what the price was before yesterday's edit, whether a role assignment predates or postdates an incident. Every consumer in the workspace has the same gap and none of them has built the same answer, which is exactly the shape of a framework concern rather than an application one.
Several questions had no recorded answer:
- Where does the capture run? A repository decorator sees intent but not the change tracker's diff. An application-layer handler sees the command, not the properties EF actually marked modified. A database trigger sees the diff and nothing else: no user, no correlation id, no PII knowledge.
- Does the trail commit with the data or beside it? A trail written after the commit can be lost by a crash in the window; a trail written to a different database cannot share the transaction at all.
- What happens to personal data? A change trail is precisely the store that outlives the erasure of the row it describes, so a naive old-value capture would recreate the personal data that ADR-005 exists to remove.
- What stops it from swamping the database? Auditing every entity in a shipped framework would put every consumer's write path on a multiplier they never asked for.
Decision
A fourth SaveChangesInterceptor, resolved optionally, running last
AuditTrailSaveChangesInterceptor (Infrastructure Persistence/AuditTrail/) joins the interceptors
ApplicationDbContext.OnConfiguring already passes to optionsBuilder.AddInterceptors
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:385-409,
where AuditSaveChangesInterceptor and DomainEventSaveChangesInterceptor are resolved with
GetRequiredService (:385-386) and the tenant and audit-trail interceptors with GetService (:393,
:407)). The new one is resolved with GetService, not GetRequiredService (:407, added on its own at
:409): a host that never calls AddAuditTrail
resolves null, nothing is added to the pipeline, and the feature costs nothing.
Registration order is execution order and it is load-bearing. After the wave the sequence is
AuditSaveChangesInterceptor (stamps CreatedBy/On and LastModifiedBy/On), then
TenantSaveChangesInterceptor (ADR-073, stamps TenantId), then DomainEventSaveChangesInterceptor
(writes the outbox rows), then AuditTrailSaveChangesInterceptor last, so the diff it captures sees the
final stamped values rather than a half-populated entity. The audit-trail rows it adds are themselves
never audited. DesignTimeDbContextHelper registers all four
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:149-150,
:156, :168). Only the two GetRequiredService interceptors are hard requirements for dotnet ef; the
context resolves the tenant and audit-trail ones with GetService (.../ApplicationDbContext.cs:393,
:407), so omitting either would still work (the helper's own comment says so for the audit-trail one,
DesignTimeDbContextHelper.cs:163-165).
AuditTrailEntry is deliberately not an auditable entity
The entity (Infrastructure Persistence/AuditTrail/AuditTrailEntry.cs) does not implement
IAuditableEntity, mirroring OutboxMessage. It therefore has no audit stamps of its own and no
soft-delete query filter. Its columns are Id (Guid), EntityType, EntityKey, PropertyName,
OldValue and NewValue (string, nullable), Operation (Added / Modified / Deleted), ChangedBy,
ChangedOn, CorrelationId, and a nullable TenantId populated when tenancy is active.
Capture is a change-tracker diff committed in the caller's transaction
SavingChangesAsync walks ChangeTracker.Entries() and keeps the entities carrying the marker
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:210,
:230, :259-262). For a Modified entity it compares OriginalValue against CurrentValue for each
modified property and adds one row per property whose value actually changed, skipping concurrency tokens
and properties flagged modified but holding an equal value (:335-364, skips at :337 and :344); a
changed owned value object is captured as navigation.property rows, including on an owner left
Unchanged (:268, :289-293, :440). Clearing an optional owned reference to null leaves no owned
entry and is not recorded (:375-376). An Added or Deleted entity writes a single summary row with a
null PropertyName (:296-305; .../AuditTrail/AuditTrailEntry.cs:18-22). Every row goes through
context.Set<AuditTrailEntry>().Add(...) (:492) into the same SaveChanges call as the data, so it
commits or rolls back with it: the outbox mechanic of ADR-003, applied to a different payload. One
exception: an inserted entity with a store-generated key has only a temporary key at capture, so after
the save the interceptor rewrites that row's EntityKey (:311-313): it loops over the pending rows and
issues one UPDATE per row, filtered by that row's Id, as ExecuteUpdateAsync on the async save path
(:544-559, :553-556) and ExecuteUpdate on the sync one (:587-589). A row whose resolved key
already equals the captured one is skipped (:546-550, :580-584), so an audited save inserting N such
entities adds at most N UPDATE statements. Each of those statements joins the ambient transaction
when one is open;
without one it commits after the data save, so a crash in that window leaves the row holding the
temporary key. After each UPDATE the interceptor writes the resolved key to the tracked
AuditTrailEntry, so the in-memory instance matches the stored row, and sets that property's original
value and clears its modified flag, so the in-memory write is not itself saved again by a later save on
the same context (SyncTrackedKey, called at :558 and :591, method :602, the write and snapshot
at :605-607).
Two mechanics are copied verbatim from DomainEventSaveChangesInterceptor:
- A
DiscardAbandonedCaptureequivalent.EnableRetryOnFailurere-runsSavingChangesagainst a change tracker that still holds the previous attempt's Added rows, so without an explicit discard one transient SQL fault writes the trail twice. - Mutation through
Addonly. The save runs underDetectChangesOncewith automatic change detection off, so anything that relies on a later detection pass to be noticed is not noticed.
PII is redacted at capture, never at read
A redacted property records PiiRedactor.RedactedToken
(MMCA.Common/Source/Core/MMCA.Common.Domain/Privacy/PiiRedactor.cs:27, the class at :24) for both the
old and the new value. Four things are redacted (AuditTrailSaveChangesInterceptor.cs:659-662, the same
check on the scalar and the owned path, :349 and :434): a property carrying [Pii], a property
carrying [Sensitive], the credential members of an entity implementing IAuthUser or
ITwoFactorUserState, found through the interface map with no marker needed (:138, :697-724,
except IsTwoFactorEnabled, which stays readable as account state, :731-732), and any column mapped
through EncryptedStringConverter, which reaches the interceptor as decrypted plaintext and is redacted
with no attribute needed (:662; class doc :49-61). On the owned path a fifth condition applies:
when the owner's navigation itself carries [Pii], every value column of the owned entry is redacted
whether or not the owned type marks its own members (:434, :405-409; class doc :43-47). The trail
stores the fact that a personal or secret field changed, and never its contents.
Redacting on the way out instead would leave clear-text personal data at rest in a store that by
construction survives the erasure of the row it describes.
Opt-in is a marker interface, plus a settings section
IAuditedEntity (Domain) is an empty marker. An entity is audited because someone wrote the interface on
it, which is what keeps volume a deliberate decision rather than a framework-imposed tax.
AuditTrailSettings binds section AuditTrail (Enabled default false, RetentionDays default 90 and
bounded [Range(1, 3650)], and DataSource default SQLServer, the engine whose Default database
the reader queries;
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSettings.cs:26,
:37-38, :46; captured at AuditTrailReader.cs:45 and consumed at :67) through the ADR-070 fail-fast chain, which runs
ValidateDataAnnotations plus ValidateOnStart (DependencyInjection.Jobs.cs:110-113). Cosmos is
documented as unsupported for DataSource (AuditTrailSettings.cs:44) but not validated: the property
carries no validation attribute (:46). AddAuditTrail(configuration)
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:108) registers the
interceptor and the settings together, plus IAuditTrailReader (:119) and AuditTrailCleanupJob (:124).
The table lives in every relational source that adopts it
ApplicationDbContext.OnModelCreating (.../ApplicationDbContext.cs:530) calls
ConfigureAuditTrail(modelBuilder) (:571, the method itself at :1003), gated on the settings flag
resolved from the root provider the way the interceptors are (:420, checked at :1005), creating a
dbo.AuditTrailEntries table (:1012) with two indexes: IX_AuditTrailEntries_Entity on
(EntityType, EntityKey, ChangedOn) for the read path (:1023-1024) and IX_AuditTrailEntries_ChangedOn
for the retention sweep (:1029-1030). A same-transaction write requires the table in the same database as
the data, which is the outbox precedent (ADR-006) and the reason the trail is not one central store.
Cosmos skips it: the CosmosDbContext OnModelCreating override
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/CosmosDbContext.cs:119) does
not call the base, so it never reaches ConfigureAuditTrail, and the audit trail is among the
relational-only tables it leaves out (:139-140). The interceptor's model check then makes capture a
no-op there too (AuditTrailSaveChangesInterceptor.cs:215-218).
Retention is the framework's first scheduled job
AuditTrailCleanupJob ships as the first IScheduledJob (ADR-074), purging rows older than
RetentionDays. The framework dogfoods its own scheduler rather than shipping a second periodic
mechanism. There is no fallback: the job runs only when the host also calls AddScheduledJobs and sets
Scheduler:Enabled, and without that the trail still records but nothing is purged, RetentionDays is
inert and pruning is the operator's job
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:97-101).
The read surface is one interface, exposed by an opt-in endpoint and panel
IAuditTrailReader (Application) with an Infrastructure implementation querying by
(EntityType, EntityKey), which is exactly the index. It returns one page of AuditHistoryEntryDTO,
newest first, with page 1-based and pageSize clamped to 1..500
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/IAuditTrailReader.cs:17, :33-37, :40).
The DTO lives in Shared (MMCA.Common/Source/Core/MMCA.Common.Shared/Auditing/AuditHistoryEntryDTO.cs:1,
:12), the same type the UI panel renders
(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auditing/AuditHistoryPanel.razor.cs:5, :24),
and carries the trail row's columns except TenantId (AuditHistoryEntryDTO.cs:15-48). It replaces
MMCA.Common.Application.Auditing.AuditTrailEntryDTO, a Breaking entry (MMCA.Common/CHANGELOG.md:515, under 1.289.0)
with its mechanical fix in MMCA.Common/UPGRADING.md:293-303.
Exposure is opt-in in three further pieces, each of which a host can leave out:
- Endpoint.
AuditHistoryControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/AuditHistoryControllerBase.cs:48) servesGET {prefix}/{entity}/{key}?page=&pageSize=, whereentityis the entity's simple type name, case-insensitive, and the 200 body is a bare array with no total (:29-32,:93);pageis at least 1 andpageSize1 to 500, default 50 (:102-103). A host derives it in one line, supplying the route, the API version and the entity types it serves (:19-27, constructor:69). Only audited entities can be served: a type that does not implementIAuditedEntity, or two types sharing a simple name, throwsArgumentExceptionat construction (:142-146). A request naming an entity the controller does not serve answers 404AuditHistory.UnknownEntity, and a blank key 400AuditHistory.KeyRequired, neither reaching the reader (:51,:54,:106-122). The class carries[HasPermission(AdministrationPermissions.ViewAuditTrail)](:47), so every derived controller inherits the gate. The reader reads the host's Default database, so each database-per-service host mounts its own controller for the entities it owns (:41-44). - Permission.
audit:viewis a framework permission (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/AdministrationPermissions.cs:46) that a host grants the way it grants its own, throughPermissionRegistryBuilder.Grantor a stored grant row (:3-7); a host that mounts the endpoint but grants the permission to no role serves an endpoint that denies everyone (:10-13). - Panel.
AuditHistoryPanel(AuditHistoryPanel.razor.cs:22) renders the entries as a table over a requiredFetchPagedelegate, 20 rows a page with "Load more" (:11-20,:40-45). It checks no permission itself: its contract is that the page places it inside an authorization check on the audit permission (:12-13).AddAuditHistoryUI()registers its client,IAuditHistoryUIService(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:397-399;MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auditing/IAuditHistoryUIService.cs:11,:24), and nothing else in the framework calls it (DependencyInjection.cs:392-393).
A host that adopts none of the three exposes no audit endpoint and renders no history; the reader stays
an injectable read a consumer may wrap in its own query instead (IAuditTrailReader.cs:11-14).
Adoption in the consumer sweep is seven relational sources, each with its own migration: ADC's Identity,
Conference and Engagement services (its Notification service does not call AddAuditTrail and has no
trail migration), Store's Catalog, Sales and Identity services (Store is database-per-service, so each
adopts separately rather than sharing one database), and Helpdesk's Tickets.
The viewer is adopted in all three consumers:
- Store mounts one
AuditHistoryControllerper service: Catalog servesProductandProductReview(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/Controllers/AuditHistoryController.cs:18,:21), SalesOrderandShoppingCart(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/AuditHistoryController.cs:18,:21) and IdentityUserandCustomer(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/AuditHistoryController.cs:18,:21). It grantsaudit:viewto Admin only (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Shared/Authorization/CatalogPermissionGrants.cs:31,MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Shared/Authorization/SalesPermissionGrants.cs:31,MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Shared/Authorization/IdentityPermissionGrants.cs:35-37; pinned, Admin yes and Customer no, byMMCA.Store/Tests/Architecture/MMCA.Store.Architecture.Tests/Api/AuditHistoryPermissionTests.cs:30,:35) and renders the panel on the product and order detail pages behind a permission-claim check (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.UI/Pages/Products/ProductDetail.razor:209, checkProductDetail.razor.cs:129;MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.UI/Pages/Orders/OrderDetail.razor:122, checkOrderDetail.razor.cs:142). - ADC mounts one per service: Identity serves
User(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuditHistory/AuditHistoryController.cs:17,:20), ConferenceEvent,SessionandSpeaker(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/AuditHistory/AuditHistoryController.cs:19,:22) and EngagementCheckIn,PointsEntryandTicket(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/AuditHistoryController.cs:19,:22). It grantsaudit:viewto Organizer only, never ContentEditor, once, in the map the token-minting host reads (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/IdentityPermissionGrants.cs:33-35,:42-50; the test pins that Organizer holds it and Attendee does not, and has no fact for ContentEditor,MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Api/AuditViewGrantTests.cs:20-36), and renders the panel on the event and session detail pages (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventDetail.razor:209-212,MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Sessions/SessionDetail.razor:205-208). - Helpdesk mounts the endpoint only, for
Ticket(MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.API/Controllers/AuditHistoryController.cs:22,:29-30). The seed ships without an identity issuer, so the controller is[AllowAnonymous]until one is added, since the inherited gate would otherwise deny every caller (:24-28), and its UI renders no panel.
Rationale
IAuditableEntityis a statement about a business row, and an audit row is not one. The interface means "this row stamps who created and last modified it and participates in soft-delete". An audit row has no author beyond the write that produced it, so the stamps would be noise; it must never be soft-deleted, because a soft-deleted audit row is a rewritten history that a query filter quietly hides; and it would recurse if the stamping interceptor touched it, since stamping is itself a change.OutboxMessagemade the same call for the same three reasons, and matching it keeps one rule for infrastructure rows rather than two.- The change tracker is the only place the diff actually exists. EF has already resolved which
properties changed and holds both values; a decorator above it would have to re-read the row to
reconstruct what EF discarded, and a database trigger would have the values but none of the identity,
correlation or
[Pii]context that makes the row useful. - Same-transaction is the difference between a trail and a hint. A trail written after the commit is lost by a crash in the window, and a trail that can be lost is one nobody can rely on in the argument it exists to settle. The outbox has run this exact mechanic in production for the whole life of the framework, so this is a proven path rather than a new one.
- Running last is what makes the captured values final. Capturing before the stamp interceptor
would record a stale
LastModifiedByon rows the same save is about to correct (the trail's ownTenantIdcomes from the context's current tenant, so it does not depend on order), which is worse than not capturing at all: a wrong history reads exactly like a right one. - Redacting at capture is the only version that survives erasure. ADR-005 anonymizes a row in place on a data-subject request. If the trail held the old clear-text value, erasure would delete the data from the row and leave it in the history, so the compliance path would be defeated by the audit path.
- Opt-in per entity keeps the cost proportional to the value. A framework that audited everything would multiply every consumer's write volume for rows nobody will ever ask about. The marker makes the cost a per-entity decision made by the team that knows which rows get argued over.
- Reusing the scheduler proves the scheduler. Retention is a real recurring job with a real failure
mode, so making it the first
IScheduledJobexercises ADR-074 in the framework's own code rather than waiting for a consumer to be the first to find out.
Trade-offs
- Write amplification is real and it is on the caller's latency path. An update that changes twenty properties writes twenty rows inside the caller's transaction (an insert or a delete writes one summary row), so an audited save is slower than an unaudited one, and the trail is not a beside-the-request concern the way a background publish is.
- A per-source table makes cross-database history a fan-out. "What happened to this user across the whole system" is a query against ADC's three audited databases, and the framework does not ship that query.
- Values are strings, so a reader gets a rendering rather than a value. A decimal, an enum and a date all arrive as text formatted at capture time, and a large column is stored at whatever length it had.
- Redact-at-capture is irreversible, which is the point and also a limit. A redacted field's old
value (
[Pii],[Sensitive], anIAuthUserorITwoFactorUserStatecredential or an encrypted column) is gone from the trail forever, so the trail can never answer "what was this email address before it changed". - The marker is per entity, not per property. Opting an entity in captures every changed property it has except its concurrency token, including the ones nobody wanted a history of; a redacted property still gets a row, with the redacted token in both value columns.
- Nothing enforces the interceptor ordering. It is registration order held by review, with no fitness test asserting it, and a fifth interceptor inserted in the wrong position silently changes what the trail sees rather than failing anything.
- Retention is a purge, not an archive. Rows past
RetentionDaysare deleted with no cold-storage path in v1, so the answer to a question older than the window is that there is no answer. - Cosmos-backed sources get no trail at all. The engine that cannot join the transaction is simply skipped, so a consumer's audit coverage is decided by ADR-018 placement rather than by intent.
- An opt-in viewer means the capability is invisible until a host adopts it. Rows accumulate from the
day
AddAuditTrailis called; nobody sees them until the host derives anAuditHistoryControllerBasecontroller, grantsaudit:viewto a role and rendersAuditHistoryPanelon a page, or writes its own surface overIAuditTrailReader. - The panel leaves authorization to its page. It checks no permission itself
(
AuditHistoryPanel.razor.cs:12-13), so a page that renders it unguarded shows an empty, failing panel to a user the endpoint refuses; the endpoint's class-level gate (AuditHistoryControllerBase.cs:47), not the panel, is what protects the data.
Alternatives rejected
- Ship no controller and no UI, leaving the read surface to each consumer (the original position: a
change history carries real authorization and presentation opinions, and consumers hold those
opinions). Revisited on 2026-11-12: every consumer that wanted to see the trail would write the same
read-only, paged, permission-gated endpoint over the same reader, so the framework now ships that
endpoint, its permission and a panel, each opt-in (see the Decision). The authorization opinion stays
with the consumer: the framework names one permission and the host decides which roles hold it, or
none (
AdministrationPermissions.cs:9-13).
Revision (2026-09-07)
Two additions from the 2026-09-07 security review.
- The
[Pii]convention is now checked in both directions (SEC-Store-19 / SEC-Store-24). The shared base already obliged a[Pii]property's entity to be anonymizable. Store adds the reverse assertion: whateverAnonymize()actually overwrites must carry[Pii](MMCA.Store/Tests/Architecture/MMCA.Store.Architecture.Tests/Governance/PiiConventionTests.cs:76), with a companion test that every anonymizable domain entity is covered by a sample so the first test cannot pass vacuously (:55). This catches the failure mode the forward rule cannot: a field the erasure path overwrites but the attribute does not cover keeps its pre-erasure value in the audit trail'sOldValuefor the full retention window (:106), which is an erasure promise broken by the record that exists to prove erasure happened. - The trail is backstopped by database-level auditing (SEC-Store-21). The application owns its
own trail table, so an actor with write access to the database can edit the evidence. Both apps
deploy SQL auditing to the Log Analytics workspace, and both record
UPDATEandDELETEstatements against the trail table there, outside the application's reach, by different means (see the 2026-09-25 revision below). That makes the trail tamper-evident, not tamper-proof: the same credential can still rewrite the table, but a rewrite leaves a trace somewhere that credential cannot reach.
Revision (2026-09-25): both apps record trail DML, by different means
Revision item 2 above previously held for Store only: ADC's server-level audit carried no statement
auditing, so a rewrite of dbo.AuditTrailEntries by the shared admin login left no record. Both apps
now record trail DML, each shaped by its own volume decision.
- Store: statement auditing at the server.
sqlAuditingSettings(MMCA.Store/infra/main.bicep:894) listsBATCH_COMPLETED_GROUPplus the two authentication groups (:875-878), routed through aSQLSecurityAuditEventsdiagnostic setting on the master database (:852). The rationale, including why the batch group is the only way to cover the trail table at server scope, is at:822-846. The batch group records every statement, so the workspace daily cap is sized for it (MMCA.Store/infra/foundation.bicep:57,dailyQuotaGb: 3). - ADC: object-scoped auditing per database. The server-level policy
sqlServerAuditing(MMCA.ADC/infra/main.bicep:872) stays authentication, principal, role, permission and schema-change groups only (:878-885), with no statement group, for volume (:863-869). A database-level policy,auditTrailDmlAuditing(:1026), addsUPDATE ON dbo.AuditTrailEntries BY publicandDELETE ON dbo.AuditTrailEntries BY public(:1034-1035) on the three databases that carry the trail (auditTrailDatabaseNames,:1004), each with its ownSQLSecurityAuditEventsdiagnostic setting (auditTrailDiagnostics,:968). The rationale is at:938-961. Because the trail is append-only in normal operation, these actions fire on tampering and on the retention purge only, and the daily cap is unchanged.SqlAuditConventionTests(MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Governance/SqlAuditConventionTests.cs:12) pins both actions inmain.bicep(:17) and the database list (:36).
Revision (2026-10-01): retention has no fallback, and the current-state text matches the code
- Retention runs on the scheduler or not at all. The Decision previously named a
PeriodicBackgroundServicesubclass as the fallback for a host without the scheduler. No such class exists:AddAuditTrailregistersAuditTrailCleanupJobas a scheduled job (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:124), and withoutAddScheduledJobsplusScheduler:Enablednothing is purged andRetentionDaysis inert (:97-101). - Opt-in is three gates, not two.
AuditTrail:Enableddefaults to false (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSettings.cs:26) and gates both the table (.../ApplicationDbContext.cs:333,:852) and capture, since the interceptor returns when the model has noAuditTrailEntry(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:183).AddAuditTrailalso registersIAuditTrailReader(DependencyInjection.Jobs.cs:119). - The table carries a second index,
IX_AuditTrailEntries_ChangedOn, for the retention sweep (.../ApplicationDbContext.cs:876-877). - The ordering rationale no longer claims a null
TenantId. The trail row'sTenantIdis read from the context's current tenant (AuditTrailSaveChangesInterceptor.cs:194), not from the stamped entity, so only the staleLastModifiedByhalf depends on running last. - A
[Pii]property is captured, redacted. The Trade-offs entry previously said only non-PII properties are captured; every changed property gets a row, a personal one with the redacted token on both sides (AuditTrailSaveChangesInterceptor.cs:303). - Anchors refreshed:
ApplicationDbContext.csinterceptor block:298-323,OnModelCreating:417,ConfigureAuditTrail:436/:850;CosmosDbContext.csSupportsOutbox:121;AddAuditTrailnow cited inDependencyInjection.Jobs.cs:108. The bicep anchors in the 2026-09-25 revision have since moved (StoreMMCA.Store/infra/main.bicep:885, ADCMMCA.ADC/infra/main.bicep:846and:1003) and are left as recorded there; the auditing content is unchanged.
Revision (2026-10-06): row shape, the key fix-up, and current anchors
- Only an update writes one row per changed property. An
AddedorDeletedentity writes a single summary row with a nullPropertyName(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:265-274), concurrency tokens and flagged-but-equal values are skipped (:305,:312), and owned value-object changes are captured asnavigation.propertyrows (:394). The Decision and Trade-offs now say so. - The trail is not strictly append-only. An inserted entity with a store-generated key gets its row's
EntityKeyrewritten by anExecuteUpdateafter the save (:276-282,:507-509), outside the transaction when none is open. ADC's auditedUser,Event,CheckInandPointsEntrycarry[IdValueGenerated](MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:33,.../Conference/MMCA.ADC.Conference.Domain/Events/Event.cs:23,.../Engagement/MMCA.ADC.Engagement.Domain/CheckIns/CheckIn.cs:27,.../Engagement/MMCA.ADC.Engagement.Domain/Points/PointsEntry.cs:30), which makes their keys store-generated on SQL Server (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SQLServerDataSourceEngine.cs:103-104). So the 2026-09-25 statement that ADC'sUPDATE ON dbo.AuditTrailEntries BY publicaction (MMCA.ADC/infra/main.bicep:1034) fires on tampering and the retention purge only no longer holds: it also fires on every insert of those entities. The actual audit volume was not measured. dotnet efneeds only the two required interceptors. The design-time helper registers all four, but omitting the tenant or audit-trail one would still work (DesignTimeDbContextHelper.cs:162-164).- Cosmos no longer cites
SupportsOutbox, which does not exist; the skip is theOnModelCreatingoverride that does not call the base (CosmosDbContext.cs:119,:139-140). - Current locations for anchors recorded in older revisions.
ApplicationDbContext.cs: interceptor block:297-322,OnModelCreating:416,ConfigureAuditTrailcall:435and method:847, flag:332checked at:849, indexes:867-868and:873-874.AuditTrailSaveChangesInterceptor.cs: the no-AuditTrailEntrygate:184,TenantIdfrom the context:195, both sides redacted at:324-325(scalar) and:395-396(owned). StoreMMCA.Store/infra/main.bicep:sqlAuditingSettings:885,BATCH_COMPLETED_GROUP:895, the two authentication groups:896-897,sqlAuditDiagnostics:871(category:878), rationale:841-865. ADCMMCA.ADC/infra/main.bicep:sqlServerAuditing:872, groups:879-885,auditTrailDiagnostics:1010, rationale:979-1003,auditTrailDatabaseNames:1004,auditTrailDmlAuditing:1026(the 2026-10-01 note's:846and:1003were wrong). - Every anchor in the live sections was re-verified against current source.
Revision (2026-10-07): per-row key fix-up, the reader's data source, and current anchors
Re-verified against current source. The capture mechanics, the row shape, the opt-in gates, the
redaction rule, the Cosmos skip and both apps' SQL-auditing content are unchanged; no fitness test
asserts interceptor ordering (none in MMCA.Common.Testing.Architecture references an interceptor) and
no controller or UI in ADC, Store or Helpdesk Source/ consumes IAuditTrailReader, so those Decision
and Trade-offs statements stand. What moved is one description, one omitted setting, the design-time
omission note and the anchors.
- The key fix-up is one statement per row, not one for all rows. The Decision previously described
a single set-based
ExecuteUpdate. The interceptor loops over the pending rows and issues oneUPDATEper row, filtered by that row'sId:ExecuteUpdateAsyncon the async path (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:498,:507-509) andExecuteUpdateon the sync path (:541-543). Each one is set-based in the sense the method's own doc comment uses (it bypasses the change tracker,:482-484). This matches ADC's bicep note of "one UPDATE per row" (MMCA.ADC/infra/main.bicep:1012-1016). AuditTrailSettingshas a third property.DataSource(defaultSQLServer) names the engine whoseDefaultdatabaseIAuditTrailReaderqueries (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSettings.cs:46, consumed atAuditTrailReader.cs:53). Cosmos is documented as unsupported (:44) but not validated, since the property has no validation attribute andAddAuditTrailruns onlyValidateDataAnnotationsplusValidateOnStart(DependencyInjection.Jobs.cs:110-113);RetentionDaysis bounded[Range(1, 3650)](:37). The Decision now lists all three.- The design-time omission note cites the context, not only the helper. The helper's comment covers
the audit-trail interceptor alone (
DesignTimeDbContextHelper.cs:162-164); the tenant interceptor's optional resolution isApplicationDbContext.cs:305. - Anchors re-verified against current source:
ApplicationDbContext.csinterceptor block:297-322(GetRequiredService:297-298,GetService:305and:319,AddInterceptors:321), flag:332,OnModelCreating:417,ConfigureAuditTrailcall:436and method:848, flag checked:850,ToTable:857,IX_AuditTrailEntries_Entity:868-869,IX_AuditTrailEntries_ChangedOn:874-875(the 2026-10-06 list's:416,:435,:847,:849,:867-868,:873-874were correct when recorded and moved down one line when Common #518 added a comment line at:391);AuditTrailEntry.csrow-shape paragraph:18-22; ADCMMCA.ADC/infra/main.bicep:sqlServerAuditing:888, groups:895-901, server volume rationale:879-887, trail-DML rationale:995-1023,auditTrailDatabaseNames:1024,auditTrailDiagnostics:1030,auditTrailDmlAuditing:1046,UPDATEandDELETEactions:1054-1055. The older anchors in the dated revisions above are left as recorded.
Revision (2026-10-21): wider redaction, the shared reverse [Pii] rule, and current anchors
Re-verified against current source. The interceptor ordering, the same-transaction capture, the row
shape, the per-row key fix-up, the opt-in gates, the Cosmos skip and both apps' SQL-auditing content are
unchanged. What moved is the redaction description, the home of the reverse [Pii] rule, two
capture-mechanics details, and the anchors.
- Redaction covers more than
[Pii].IsRedacted(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:636-639) also redacts[Sensitive]properties and theIAuthUsercredential members (:668-691), and any column mapped throughEncryptedStringConverterwith no attribute at all (:639). The Decision and the two Trade-offs entries that named[Pii]alone now list all four or refer to a redacted property generically. - The reverse
[Pii]rule is framework-wide, not Store-only. The 2026-09-07 revision describes a Store test. The rule now lives in the shared base (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Governance/PiiConventionTestsBase.cs:43,PropertiesOverwrittenByAnonymize_MustCarryPii, withEveryAnonymizableDomainEntity_IsCoveredBySampleat:37). Store'sTests/Architecture/MMCA.Store.Architecture.Tests/Privacy/PiiConventionTests.cs:25subclasses it and supplies only the samples (:33-48) plus a non-vacuity guard (:55), with theOldValueretention rationale in its class doc (:9-11). ADC (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Privacy/PiiConventionTests.cs) and Helpdesk (MMCA.Helpdesk/Tests/Architecture/MMCA.Helpdesk.Architecture.Tests/ArchitectureTests.cs) subclass the same base. - Two capture details are now stated. Clearing an optional owned reference to null is not recorded
(
AuditTrailSaveChangesInterceptor.cs:366-367), and the key fix-up skips a row whose resolved key already equals the captured one (:525-528,:559-562), so N audited inserts add at most NUPDATEstatements. - Anchors re-verified against current source:
ApplicationDbContext.csinterceptor block:297-322, flag:332,OnModelCreating:417,ConfigureAuditTrailcall:436and method:854, flag checked:856,ToTable:863,IX_AuditTrailEntries_Entity:874-875,IX_AuditTrailEntries_ChangedOn:880-881;AuditTrailSaveChangesInterceptor.csCaptureChanges:201, model gate:206-209,DiscardAbandonedCapturecall:211(method:481), filter:221withShouldAudit:250-253,Unchangedowner:259routed at:280-283, summary row:287-296, pending key:302-304, modified loop:326-355,navigation.propertyname:418,Add:470,ResolveGeneratedKeysAsyncloop:522-537withExecuteUpdateAsync:531-533,ExecuteUpdate:565-567;PiiRedactor.csclass:24, token:27. The bicep anchors in the dated revisions above are left as recorded.
Revision (2026-10-26): the tracked key sync, and current anchors
Re-verified against current source. The interceptor ordering, the same-transaction capture, the row shape, the per-row key fix-up and its skip rule, the redaction rule, the opt-in gates, the Cosmos skip and both apps' SQL-auditing content are unchanged. What moved is one omitted capture detail and the anchors.
- The key fix-up also syncs the tracked trail row. After each per-row
UPDATE,SyncTrackedKey(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:580, doc:574-579, called at:537and:570) writes the resolved key to the trackedAuditTrailEntry(:583), so the in-memory instance matches the stored row, then sets its original value and clearsIsModified(:584-585), so that write is not itself saved again by a later save on the same context. The Decision now says so. - Anchors re-verified against current source:
AuditTrailSaveChangesInterceptor.csIsRedacted:637-640(called at:340scalar and:412owned),EncryptedStringConvertercheck:640,CredentialPropertyNames:669-692, class doc:49-59,ResolveGeneratedKeysAsyncloop:523-538with theExecuteUpdateAsyncstatement:532-535, the syncExecuteUpdatestatement:566-568, key-skip:525-529and:559-563(the 2026-10-21 list's:522-537,:565-567,:636-639and:668-691moved down one line; itsExecuteUpdateAsync:531-533moved down one line and now also spans the.ConfigureAwait(false)line:535; its key-skip:525-528and:559-562cited only theifblocks, now at:526-529and:560-563, and the new ranges also take in theresolvedKeyline:525and:559that the comparison reads);AuditTrailReader.cssettings captured:45,DataSourceconsumed:67(the earlier:53is a method parameter). The anchors in the dated revisions above, including the bicep ones, are left as recorded.
Revision (2026-10-28): current SQL-auditing and store-generated-key anchors
Re-verified against current source. The capture mechanics, the row shape, the per-row key fix-up, the
redaction rule, the opt-in gates, the Cosmos skip and both apps' SQL-auditing content are unchanged:
Store still audits statements at the server through the batch group, and ADC still pairs an
authentication-and-privilege server policy with object-scoped UPDATE and DELETE actions on the trail
table in its three trail-carrying databases. Only anchors moved, and no earlier revision records the
current bicep ones.
- Anchors re-verified against current source: ADC
MMCA.ADC/infra/main.bicep:sqlServerAuditing:1070, groups:1076-1084(entries:1077-1083, no statement group), server volume rationale:1061-1069, trail-DML rationale:1180-1207(the "one UPDATE per row" note and when each action fires at:1199-1200),auditTrailDatabaseNames:1208(ADC_Identity,ADC_Conference,ADC_Engagementat:1209-1211),auditTrailDiagnostics:1214(category:1222),auditTrailDmlAuditing:1230,UPDATEandDELETE ON dbo.AuditTrailEntries BY public:1238-1239. StoreMMCA.Store/infra/main.bicep:sqlAuditingSettings:968, groups:977-981(BATCH_COMPLETED_GROUP:978, the two authentication groups:979-980, inline comment:974-976),sqlAuditDiagnostics:954(categorySQLSecurityAuditEvents:961), rationale:917-948with the batch-group and no-per-table-filter cost note at:942-948;MMCA.Store/infra/foundation.bicep:57(dailyQuotaGb: 3) is unchanged. ADC[IdValueGenerated]:MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:34(the 2026-10-06 revision's:33moved down one line);Event.cs:23,CheckIn.cs:27andPointsEntry.cs:30are unchanged. The anchors in the dated revisions above, including the 2026-09-07 StoreGovernance/PiiConventionTests.csones superseded by the 2026-10-21 revision, are left as recorded.
Revision (2026-11-23): fuller redaction rule, Ticket's key fix-up, and current anchors
Re-verified against current source. The interceptor ordering, the same-transaction capture, the row shape, the per-row key fix-up and its skip rule, the tracked key sync, the opt-in gates, the Cosmos skip, the opt-in viewer and both apps' SQL-auditing content are unchanged. What moved is the redaction description, one omitted adopter of the key fix-up, and the anchors.
- Redaction has a fifth condition and a second credential interface. On the owned path, a
[Pii]navigation on the owner redacts every value column of the owned entry (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:434, remark:405-409, class doc:43-47). The credential set is resolved through bothIAuthUserandITwoFactorUserState(:138,:697-724), withIsTwoFactorEnableddeliberately kept readable as account state (:731-732), and[Sensitive]properties are folded into the same set (:719-721). The Decision and the irreversibility Trade-off now say so. - ADC's
Ticketalso takes the key fix-up.Ticketis audited and carries[IdValueGenerated](MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Domain/Tickets/Ticket.cs:29-30) and is served by Engagement's audit-history endpoint (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/AuditHistoryController.cs:22), so ADC's trail-tableUPDATEaction fires on its inserts as well as on those ofUser,Event,CheckInandPointsEntry, which the 2026-10-06 revision lists. - Anchors re-verified against current source:
ApplicationDbContext.csinterceptor block:385-409(GetRequiredService:385-386, tenantGetService:393withAddInterceptors:395and:399, audit-trailGetService:407,AddInterceptors:409), flag:420,OnModelCreating:530,ConfigureAuditTrailcall:571and method:1003, flag checked:1005,ToTable:1012,IX_AuditTrailEntries_Entity:1023-1024,IX_AuditTrailEntries_ChangedOn:1029-1030;DesignTimeDbContextHelper.csregistrations:149-150,:156,:168, omission comment:163-165;AuditTrailSaveChangesInterceptor.csCaptureChanges:210, model gate:215-218,DiscardAbandonedCapturecall:220(method:502), filter:230withShouldAudit:259-262,Unchangedowner:268routed at:289-293, summary row:296-305, pending key:311-313, modified loop:335-364(skips:337,:344), owned-null remark:375-376,navigation.propertyname:440,Add:492, async fix-up loop:544-559(skip:546-550,ExecuteUpdateAsync:553-556,SyncTrackedKeycall:558), sync loop:578-592(skip:580-584,ExecuteUpdate:587-589, call:591),SyncTrackedKey:602-608(write and snapshot:605-607),IsRedacted:659-662(called:349scalar,:434owned; converter check:662), class doc:49-61;MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.csAddAuditHistoryUI:397-399, nothing-else note:392-393;MMCA.Common/CHANGELOG.md:515(1.289.0) andMMCA.Common/UPGRADING.md:293-303; StoreProductDetail.razor:209(guard:206, checkProductDetail.razor.cs:129) andOrderDetail.razor:122(guard:119, checkOrderDetail.razor.cs:142and:176); StoreMMCA.Store/infra/main.bicep:sqlAuditingSettings:1174,BATCH_COMPLETED_GROUP:1184, the two authentication groups:1185-1186, inline comment:1180-1182,sqlAuditDiagnostics:1160(category:1167), rationale:1124-1154with the cost note at:1148-1154, andMMCA.Store/infra/foundation.bicep:57(dailyQuotaGb: 3) unchanged; ADCMMCA.ADC/infra/main.bicep:sqlServerAuditing:1227, groups:1233-1241(no statement group), server volume rationale:1218-1226, trail-DML rationale:1339-1364(the "one UPDATE per row" note:1356),auditTrailDatabaseNames:1365(:1366-1368),auditTrailDiagnostics:1371(category:1379),auditTrailDmlAuditing:1387,UPDATEandDELETEactions:1395-1396; ADC[IdValueGenerated]onUser.cs:37, withEvent.cs:23,CheckIn.cs:27andPointsEntry.cs:30unchanged. The anchors in the dated revisions above are left as recorded.
Related
ADR-003 (the same-transaction write this copies wholesale, including the
retry-discard and the Add-only mutation rule),
ADR-005 (soft-delete, [Pii] and erasure: why the trail redacts at
capture and why its rows are purged rather than soft-deleted),
ADR-073 (the interceptor that runs immediately before this one, and the
source of the nullable TenantId column), ADR-074 (the scheduler that
runs the retention purge, and its first consumer),
ADR-070 (the validating chain AuditTrailSettings binds
through), ADR-006 (why the table is created per relational source rather
than once), ADR-018 (the engine axis, and why a Cosmos-backed source opts
out), ADR-035 (the RowVersion token that makes a diffed update
deterministic: without it two concurrent writers can produce a history that never happened).