Skip to content

ADR 0015 — One transactional audit trail, delivered through the outbox ​

  • Status: Accepted in part (see Delivery status)
  • Date: 2026-10-30, delivery recorded 2026-11-01
  • Baseline inspected: develop, 39e1fa4a, plus the open PRs #200, #202, #203 and #204
  • Related: ADR 0011, ADR 0012
  • Requests answered: product requests for an audit trail of control acts, and for an outbox with platform scope

The full design is breaking, so it ships in steps. The sections below keep the target; Delivery status says what exists today.

Delivery status ​

Delivered in 11.1.0, without a breaking change or a migration:

DecisionWhat exists
1IAuditTrail<TUnitOfWork>.Stage(AuditEntry) and IPlatformAuditTrail<TUnitOfWork>, on the wire contract AuditRecord (audit.record v1)
3One AuditRecordConsumer<TContext>, with AddAuditSource and AddPlatformAuditSource
1, 3GrydFiles and the GrydAuth membership trail stage through this path
5, in partOutboxEnvelope.Unordered in the Core

Differences from the text below, decided at delivery:

  • Stage takes the existing AuditEntry, so a caller has one shape to build. AuditRecord is only what travels. There is no second public model.
  • The consumer is a template with two destinations. AuditLogRecordConsumer writes the row in the receipt's transaction in AuditDbContext. AuditStoreRecordConsumer writes through IAuditStore, at least once, and relies on the store being idempotent by AuditEntry.Id. GrydFiles uses the store, so a host with its own store keeps working and the module has no GrydAudit reference.
  • IAuditTrail is generic on the unit of work. A host has several contexts, and the application layer names a marker, not an EF context.

Kept for compatibility, removed in the next major:

  • The consumers of files.audit-trail, files.platform-audit-trail and auth.tenant-membership.*. They deliver messages staged before the upgrade. Removing them in a minor would lose those lines.
  • A new Auth membership act stages the public fact and the record. Both resolve to one row, because the entry id is the fact's SourceEventId and the write skips an id that exists. Two concurrent deliveries are settled by the primary key: the loser fails its save, and the outbox retries it and finds the row.

Not delivered, because they break a contract or need a schema change: decisions 2, 4, 6, 7, 8 and 9, the rest of 5, and the proofs for them. The post-commit paths of the interceptor and PostCommitAuditFlusher still exist, so an act through those paths can still stand without a record (D11). GrydAuth.Infrastructure still references GrydAudit's infrastructure.

Reading today. IAuditLogRepository searches under the tenant filter by entity type and id. A record reaches it after delivery, so a screen that shows history must tolerate a short delay.

Context ​

An audited act needs one rule: no record, no act. The platform does not offer it generally.

Four write paths exist with different guarantees:

PathWhen it writesOn failure
AuditSaveChangesInterceptorAfter the commit, in AuditDbContextLog and metric; the act stands (D11)
PostCommitAuditFlusher (Auth)After the commitLog and metric; the act stands (D11)
PlatformRoleAuditorBefore the commit, in another contextThe act fails; a later commit failure leaves a record of an act that did not happen (D12)
Files and Auth membership outboxIntent in the act's transactionNothing is lost; delivery retries

The outbox path is the only one that gives the required guarantee, and two modules built it separately. FileAuditTrailConsumer writes through IAuditStore, outside the receipt's transaction. AuthMembershipAuditConsumer writes to AuditDbContext inside it, which is why GrydAuth.Infrastructure depends on GrydAudit's infrastructure. That dependency, through the GrydAudit meta project, also brings GrydAudit.API controllers into every Auth host.

Other gaps confirmed in the code:

  • A message with no route is frozen with an empty plan, dead-lettered as OUTBOX_NO_CONSUMERS and blocks its stream. A product cannot publish a fact before its subscribers exist.
  • AuditLogCriteria filters by one entity. There is no aggregate-level history.
  • No public read port is meant for a product endpoint with its own permission.
  • AuditLog has no database immutability. The seal updates rows and retention deletes them.
  • Retention is one number of days for the whole host.
  • EntityChangeType.Accessed exists, but no mechanism records a sensitive read.
  • Product handlers can subscribe to Auth domain events inside its transaction, so a failing product handler can undo an Auth act.

Some requested items are already delivered or in review, and are not redesigned here:

  • Tenant isolation of reads and read:audit-logs on the routes are on develop.
  • Idempotent EfCoreAuditStore writes are on develop (d2856957).
  • Explicit platform scope and Files adoption are in PRs #200 and #202.
  • Authorized retry, empty-plan recovery, discard and payload retention are in PR #203.
  • The durable membership-removal fact is in PR #204.

Options considered for the write ​

OptionAssessment
A. Map AuditLog into every act's contextAtomic and immediately readable, but splits the trail by schema. One chain, one retention pass and one reader stop being possible. Rejected.
B. Enlist AuditDbContext with UseTransactionAtomic, with one table, but requires the same database and connection. The framework supports a separate audit database. Rejected.
C. Stage an intent in the act's transaction and deliver it to GrydAuditAtomic in any topology and survives a crash after commit. Reuses ADR 0012. Reads lag behind the act. Chosen.
D. Choose A/B or C by topologyAvoids lag where possible, at the cost of two semantics and two failure sets. Rejected.

The default worker poll interval is one second, so the expected lag is on the order of seconds. This is an estimate from configuration, not a measurement. It has not been measured yet.

Option C meets the behavior requested by Product: a failed staging undoes the act and a rollback leaves nothing. It does not meet the literal wording "the record row is in the same connection". The intent is what shares the transaction. Hence P4 criterion 6 is answered as: the outbox row is sufficient.

ADR 0012 already rejected adding a broker or messaging framework. This ADR does not reopen that.

Decision ​

1. One write path, bound to the unit of work ​

IAuditTrail.Stage(AuditRecord) joins the current unit of work. It never saves, commits or opens a transaction. AuditRecord is a closed, versioned contract: action, entity, author, instant, reason, per-field changes, subject and product-defined metadata.

  • Masking and exclusion rules run before staging. Personal data in clear never enters the outbox.
  • A failure to stage fails the act.
  • A bulk operation stages one record at the triggering node, with data such as affectedCount in the metadata. This covers ExecuteUpdate and raw SQL, which the interceptor cannot see.
  • Records have no ordering among themselves: one stream per message, as Files does today. The envelope factory for this case moves to the Core as OutboxEnvelope.Unordered.
  • The writer validates the record's operation tenant. A platform operator acting on an organization must have an explicit, tested path; a read-only group scope remains refused.

There is one exception, stated by rule: an event with no act's transaction uses IAuditStore directly. These are refused attempts, failed logins and sensitive reads. An architecture gate restricts that port to this list.

2. The interceptor stages in the same save ​

The interceptor collects in SavingChanges and adds the intent to that same SaveChanges. Commit and rollback then need no handling at all. These go away: AuditUnitOfWork, the interceptor's transaction hooks, IPostCommitAuditBuffer, PostCommitAuditFlusher and decisions D11 and D12.

One envelope per save carries that save's records, bounded by size, to limit write amplification.

An audited entity needs a client-generated key, because the assembler can no longer read a key after the save. Startup validation refuses a store-generated key on an audited entity. This depends on a prototype proving EF includes rows added in SavingChanges in every path used, including Auth's event loop.

3. One delivery consumer, owned by GrydAudit ​

A single ILocalOutboxConsumer<AuditDbContext, AuditRecordBatch> writes the rows in the same transaction as the receipt, so a redelivery has one effect. FileAuditTrailConsumer, AuthMembershipAuditConsumer and their contracts are removed. Producers register with one call, for example outbox.AddAuditSource("nexio-main"), with both tenant and platform routes.

4. Explicit composition and clean references ​

Dependencies point inward:

PieceLives inDepends on
IAuditTrail, AuditRecord, IAuditStoreGryd.ObservabilityApplication abstractions
Staging writer and interceptorNew Gryd.Observability.EntityFrameworkCoreGryd.Infrastructure, Gryd.Observability
Destination, consumer, retention, chainGrydAudit.InfrastructureThe above
ControllersGrydAudit.API, only through AddGrydAuditApi()GrydAudit.Application

A new project is required because Gryd.Infrastructure and Gryd.Observability do not reference each other today.

GrydAuth.Infrastructure and other modules reference no GrydAudit project. Each module's host chooses .WithAuditTrail(...) or .WithoutAuditTrail(). Choosing neither fails startup, and so does a registered producer whose context lacks the interceptor. Nothing is silently unaudited. A test host that references only GrydAuth.Infrastructure has zero GrydAudit endpoints.

5. Outbox: publication is separate from subscription ​

Amends ADR 0012, section 4.

  • Declared events. DeclareEvent(kind, version) states that a contract exists. With no route, the message completes with no delivery and stays available until retention. An undeclared kind without a route is still a visible failure, which keeps protection against mistyped kinds.
  • Late subscribers. Plans remain frozen. A new subscriber receives past messages only by an authorized replay built on the administration in PR #203, with durable attribution. Replay is per consumer and never repeats confirmed receipts.
  • External effects. A separate IExternalOutboxConsumer route supports at-least-once delivery, idempotency by MessageId and a stored ExternalRef. Local consumers still must not call out. Broker adapters are later, optional packages.
  • One writer port. IOutboxWriter<TUnitOfWork>, keyed by an Application-layer marker, replaces IFileAuditOutbox-style wrappers. A generic drain context replaces AuthOutboxDrainContext and FilesOutboxDrainContext.

Stream guidance. A stream is the unit whose order a consumer needs, and its sequence is protected by that unit's concurrency token. For the Product example, establishment.deactivated uses one stream per establishment with that establishment's version. company.headquarters-changed uses the company's stream. One failure then does not stop every branch.

6. Reads ​

  • IAuditTrailReader is a public port with no permission of its own, still restricted by the tenant filter. A product endpoint calls it under its own permission, such as read:supplier-audit.
  • GrydAudit.API routes keep requiring read:audit-logs.
  • Aggregate history is first class: SubjectType and SubjectId columns with an index led by the tenant, set on AuditRecord or declared on the entity. There is no search inside metadata.

7. Immutability, retention and erasure ​

Append-only is one Core piece: .IsAppendOnly() in the model, a save interceptor, and a migration operation that creates the trigger. a product's repeated pairs can move to it. The same piece protects AuditLog and AuditLogDetail.

  • The seal may fill only the chain columns, and only once.
  • Each row gets RetainUntil at write time, from rules by category, entity or action. A tenant can only extend it.
  • The trigger refuses a DELETE before RetainUntil or under legal hold. No session variable can bypass it.
  • A correction is a new row.
  • Erasure is an explicit operation that replaces a value and records its own audit row.

What this does not defend against. The trigger stops application errors and direct SQL by ordinary roles. A database owner can disable it. That threat needs role separation and the externally anchored chain.

Chain changes this forces:

  • Today the retention cut removes a prefix by Timestamp, and a sequence gap counts as tampering. Per-category retention would open gaps, so each chain becomes per (tenant, retention class).
  • A late delivery can make Timestamp and Sequence disagree, so the cut moves to Sequence.
  • Today the hash covers detail values, so erasure would break it. A new CanonicalVersion hashes a salted commitment of each value. The row keeps the commitment when the value is erased.

8. Sensitive reads ​

Lists return masked values and revealing a value is an explicit query implementing ISensitiveDataRead, which declares the subject and field names. A pipeline behavior records author, instant, subject and field names, never the value, after the handler and before the response. If the record fails, the value is not returned. These rows use their own retention class.

9. Auth ​

  • RolePermission*, UserRole*, UserPermission* and PlatformRole* events stage their record from inside the existing transactional loop. A rollback leaves no record, event or copy.
  • All Auth auditors move to IAuditTrail for applied acts and IAuditStore for refusals.
  • Products react to Auth only through public integration contracts delivered after the commit. A consumer failure cannot undo the act, and a rollback delivers nothing.
  • The transactional dispatcher stops accepting handlers from outside the module. This closes the class of bug behind a product's UserRemovalTransactionInterceptor. It is a breaking change for any product handler, which must move to a public contract.
  • TokenVersion and other invariants stay in the transaction (ADR 0012, section 1).

Consequences ​

  • Gained: one guarantee everywhere, less code in Auth and Files, no accidental audit routes, and a mechanism products can reuse instead of building their own tables.
  • Lost: a record is not readable immediately after the act. A screen that shows history must tolerate that.
  • Required to run: every producer maps the outbox tables and some host runs the worker. Without a worker, acts still succeed and intents accumulate, so backlog age needs an alert.
  • Cost: more rows per audited save. High-volume entities must justify being audited.
  • Migration: every producer schema and AuditLogs change. Existing rows keep their CanonicalVersion; the chain's new shape needs a defined cut for old rows.
  • Not provided: exactly-once delivery, broker adapters, database per module, or the retention periods themselves, which remain each product's legal decision.

Proofs required before Accepted ​

ProofWhy
EF prototype of staging in SavingChangesDecision 2 depends on it, including Auth's loop
Inventory of store-generated keys on audited entitiesSizes the impact of the new validation
Measured delivery lag and write amplificationReplaces the estimate above
Chain per class and commitment against the current verifierDecision 7 changes verified data
Operation-tenant staging for a platform operatorThe current writer compares the session's tenant
Inventory of external handlers on Auth eventsSizes the breaking change in decision 9

Acceptance map ​

RequestDecisionKey acceptance test
Product 1, gap 1, GrydFiles trail1, 2, 3Failed staging undoes the act; rollback leaves nothing; a crash after commit still delivers; redelivery leaves one row
Product 2Already deliveredTenant B reads nothing of tenant A by any route
Product 3, gap 2, gap 36403 without permission; a product route works without read:audit-logs; aggregate history includes child entities
Product 4, gap 57UPDATE and DELETE refused by SaveChanges and by direct SQL; the seal changes only chain columns
Gap 47Different periods by category; a tenant cannot shorten; a hold blocks deletion; the chain still verifies
Product 51One record for a bulk act, queryable by node; written with no tracked entity
Product 68A sensitive read records author and instant, with no value; a failed record refuses the read
Product 79Granting approve:supplier-banks stages in its transaction; a rollback leaves nothing
Product 89A throwing consumer does not undo the removal; the consumer sees it committed; a rollback delivers nothing
Product 9, outbox 1–55A declared event with no subscriber completes without blocking; a replay reaches a late subscriber once
Outbox 65Documented stream guidance, with a test of independent streams
Product 104A host referencing only Auth has zero GrydAudit endpoints
GrydFiles §1–5PRs #200, #202Their tests, then this ADR's consumer replaces the Files one

Updated at:

Released under the MIT License.