↑↓ to navigate Enter to open "…" all these words ANDOR to combine

Architecture Decision Record

ADR-073: Multi-Tenancy (Shared-Schema Query Filter plus DB-per-Tenant Routing)

Status

Accepted (2026-08-13). The implementation lands in the MMCA.Common enterprise capability wave release, alongside the scheduler, audit trail, DSAR export, and CSV export work. It is opt-in: AddMultiTenancy(configuration) binds the settings section, and with no host calling it the mechanism is inert (Tenancy:Enabled false, no tenant resolved), so the framework release is non-breaking. Revised 2026-08-14: re-anchored the ApplicationDbContext, middleware, repository, and outbox citations to current source, and corrected the repository's named-filter exclusion (five call sites through one shared field, not four inline arrays). Revised 2026-08-18: that exclusion now runs at six call sites in EFReadRepository, and the field and every call site were re-anchored again. The count has moved four to five to six across three revisions, which is the point: the shared field is the invariant, the number of read paths using it is not. Revised 2026-08-23: re-anchored the middleware citations after the edge pipeline moved into a named-step registry (MiddlewarePipelineBuilder plus MiddlewarePipelineStepNames, the order frozen by the MiddlewarePipelineOrderTestsBase fitness function rather than by inline calls); corrected the write-side guard, which is not a no-op when no tenant is resolved (an insert of an untenanted ITenantEntity from an untenanted scope throws); restated why DesignTimeDbContextHelper registers that interceptor, since OnConfiguring now resolves it with GetService and its absence no longer breaks dotnet ef; and replaced the claimed adoption-sweep grep with what is verifiable, namely zero parameterless IgnoreQueryFilters() call sites in MMCA.Common/Source today and no automated gate against a future one. Revised 2026-08-31: the named-filter exclusion now runs at eight call sites in EFReadRepository (four to five to six to eight across four revisions, the shared field still the invariant), and the ApplicationDbContext filter and interceptor anchors, the interceptor registrations in DependencyInjection and DesignTimeDbContextHelper, and the outbox per-tenant scope and claim-lease anchors were all re-anchored to current source.

Revised 2026-09-11: the tenant now crosses the broker. This record never listed the gap, but a consumer service could not resolve the tenant of an integration event: the outbox row and the broker message both arrived untenanted, so the delivery ran in the system context. The row now stores the tenant it was written under and the consumer restores MMCA-Tenant-Id before anything reads the scope; see the Revision (2026-09-11) at the end. Revised 2026-10-01 (the Decision no longer claims the outbox row has no tenant column, and the tenant-unaware factory is now PhysicalDbContextFactory; see Revision below). Revised 2026-10-06: the background-work targets come from TenantDataSourceTargets.Expand (not ExpandRelational), and the DB-per-tenant section now names the second context guard and the per-row outbox scope. Revised 2026-10-07: anchors refreshed after the v1.233.0 release. Revised 2026-10-21: the default resolution order is the claim only since v1.243.0; header resolution is an explicit opt-in (claim-before-header is a recommended order checked only by an optional conformance base), Helpdesk opts in, and the unresolved-tenant 400 still names the header; anchors refreshed. Revised 2026-10-26: the Decision now names all three facts of the optional TenantResolutionTestsBase (header opt-in through AllowsHeaderResolution, claim before header, health endpoints excluded), not only the claim-before-header one; anchors refreshed. Revised 2026-10-28: anchors refreshed after the releases since v1.243.0 moved its CHANGELOG.md entry. Revised 2026-11-07: the forgotten-marker trade-off is now caught by TenantScopeConventionTestsBase in a tenancy host that subclasses it (every module entity tenant-scoped or declared global); see Revision (2026-11-07). Revised 2026-11-23: MMCA.Common/Source now carries one parameterless IgnoreQueryFilters() call site (the feature-flag override store, on a non-tenant entity, so it drops only soft-delete), not zero, and still no automated gate against one; anchors refreshed. Revised 2026-11-30 (v1.324.0): the tenant read filter fails closed. A scope that resolved no tenant reads no tenant-owned rows; seeing every tenant takes an explicit ITenantContext.SetAllTenants(), exposed as IsAllTenants. The Header strategy is honoured only with Tenancy:TrustTenantHeader true, listing it without that fails startup, and TenantResolutionStrategy.Host is removed. The null-tenant-sees-all statements below are marked superseded in place; see the Revision (2026-11-30) at the end.

Context

MMCA.Common already partitions data along two axes and neither of them is a tenant. ADR-006 partitions by source name (every entity resolves to a DataSourceKey(Engine, Name), each module or service owning its own database) and ADR-018 partitions by engine. A third axis, "which customer does this row belong to", had no recorded answer, which meant every consumer that ever needed one would invent it: a TenantId column here, a Where clause in each handler there, and one forgotten handler is a customer data leak.

The framework does have the machinery this needs, built for a different reason. ApplySoftDeleteFilters (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:602, called from OnModelCreating (:530) at :554) proves that a global predicate applied by expression tree to every matching entity type makes an invariant unforgettable, and EF10's named query filters (modelBuilder.Entity(clrType).HasQueryFilter(SoftDeleteFilterName, filter), :614, the name itself a constant at :623) mean a second filter can be added beside the first rather than replacing it. The interceptor pipeline resolved in OnConfiguring (declared at :378, the interceptor block at :385-410) proves that a write-side rule can be enforced once for every context.

That left a specific set of open questions: whether a tenant is a row discriminator or a database, what happens when no tenant is resolved, where the tenant comes from on an inbound request, whether the outbox and the migration runner (which have no request and therefore no claims) can reach tenant data at all, and whether one cached EF model serves many tenants or each tenant compiles its own.

Decision

Ship shared-schema tenancy as a second named query filter, with per-tenant database routing as a configuration override on the same source key, both opt-in and both inert until a host asks for them.

The tenant filter is a second named filter, composed with soft-delete

ApplicationDbContext gains ApplyTenantFilters, applied beside ApplySoftDeleteFilters in OnModelCreating. Named filters compose with AND automatically, so an entity that is both IAuditableEntity and ITenantEntity carries both predicates and neither knows about the other. The tenant predicate is e => CurrentTenantId == null || e.TenantId == CurrentTenantId, built as an expression tree that embeds Expression.Constant(this): EF rewrites a context-typed constant inside a filter to the executing context instance at query-compile time, so one cached model per source serves every tenant and the tenant value arrives as a SQL parameter rather than as a literal baked into a per-tenant model. A dedicated two-tenants-one-cached-model Sqlite test locks that in, because it is a property of EF's filter rewriting rather than of code this repo owns.

A null tenant is the system context and sees everything: background services, the migration runner, and admin flows run without a resolved tenant by construction. (Superseded by the Revision (2026-11-30): a null tenant now reads no tenant-owned rows, and only a scope that called SetAllTenants() sees every tenant.) CosmosDbContext.OnModelCreating calls ApplyTenantFilters too, because it builds its filters independently rather than inheriting them.

ITenantEntity carries a plain string

ITenantEntity (Domain, Source/Core/MMCA.Common.Domain/Interfaces/ITenantEntity.cs) declares string TenantId { get; }: max 64 characters, no public setter. The interceptor stamps it through entry.Property(...).CurrentValue, so an entity cannot set its own tenant and a handler cannot move a row between tenants by assignment. The type is string deliberately, and this is where the record departs from ADR-048: a tenant identifier arrives from a JWT claim, an HTTP header, or a configuration key, all three of which are text, so a TenantIdentifierType alias would add a conversion at every one of those boundaries and buy nothing. A tenant is never a key this system generates the way an entity identifier is.

ITenantContext mirrors ICorrelationContext, one scope means one tenant

ITenantContext (Application) exposes TenantId, IsResolved, and SetTenant, mirroring ICorrelationContext in shape and lifetime. The scoped TenantContext implementation makes SetTenant idempotent for the same value and throws on a different value: a scope that has already answered queries for tenant A must not start answering them for tenant B, so the invariant is enforced, not advised.

Resolution is claim-only by default, header by opt-in, and fails closed

TenancySettings binds section Tenancy through the ADR-070 chain: Enabled (false), ResolutionOrder (empty, read through EffectiveResolutionOrder, which falls back to [Claim] alone, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:61-62, :82-83), ClaimType (tenant_id), HeaderName (X-Tenant-Id), RequireTenant (true), ExcludedPathPrefixes (health, alive, .well-known), and a Tenants:{id}:DataSources:{sourceName} map of per-tenant connection strings. Header resolution is never part of the default order: a caller-supplied header lets any caller name any tenant, so a host that accepts it (service-to-service calls behind a trusted gateway) lists Header in Tenancy:ResolutionOrder explicitly, and resolution reads HeaderName only when Header is listed (TenancySettings.cs:15-21, :74-79, :91-95; MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/TenantResolutionMiddleware.cs:108-116). Listing Claim before Header is the recommended order rather than a startup rule: options validation rejects only Host (superseded by the Revision (2026-11-30): Host no longer exists, and validation now rejects an unknown strategy name and Header without Tenancy:TrustTenantHeader) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettingsValidator.cs:55-63), and the claim-before-header check lives in the optional conformance base TenantResolutionTestsBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/TenantResolutionTestsBase.cs:66-81), which a host subclasses to enforce it. That base holds three facts, not one: header resolution must be an explicit opt-in (:46-61, gated by the virtual AllowsHeaderResolution, default false, at :40), the claim must be tried before the header (:66-81), and the health endpoints must stay excluded (:87-100). With tenancy enabled, a host that lists Header and subclasses the base therefore also overrides AllowsHeaderResolution (the opt-in fact returns early when tenancy is disabled, :50-53). Helpdesk opts in, listing the claim first, without subclassing that base (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/appsettings.json:35). The fail-closed 400 names HeaderName beside ClaimType whatever the order lists, so a claim-only host still tells the caller it may supply the header (TenantResolutionMiddleware.cs:146-150, ClaimType at :147, HeaderName at :149). Host-based resolution (tenant from subdomain) is deferred: it needs a hostname-to-tenant map and certificate handling that no consumer needs today.

TenantResolutionMiddleware (Source/Presentation/MMCA.Common.API/Middleware/TenantResolutionMiddleware.cs) mirrors CorrelationIdMiddleware, which is a named step of the same edge pipeline (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:40, its name a constant at MiddlewarePipelineStepNames.cs:20). Tenant resolution is its own step (MiddlewarePipelineBuilder.cs:107-113), placed immediately after the Authentication step (:103-105), because a claim-first resolution order requires that HttpContext.User already be populated. UseCommonMiddlewarePipeline (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:49, with a configure overload at :61) applies the steps through ApplyPipeline (:171), which seeds MiddlewarePipelineBuilder.CreateDefault() (MiddlewarePipelineBuilder.cs:31): the order is data, frozen by the MiddlewarePipelineOrderTestsBase fitness function rather than by a sequence of inline Use* calls. Like the SoftDeletedUserFilter step (MiddlewarePipelineBuilder.cs:123-125, its name at MiddlewarePipelineStepNames.cs:59) the tenant step is registered unconditionally and inert by default, keeping the pipeline one shape across every host. When RequireTenant is true and nothing resolves on a non-excluded path, it returns 400 with a ProblemDetails body.

Writes are guarded by their own interceptor

TenantSaveChangesInterceptor is a separate interceptor from the audit one (one concern per interceptor, matching how audit stamping and domain-event capture are already split at :385-386, where it is registered between the two at :395). It stamps TenantId on Added entries and throws CrossTenantWriteException on any Added, Modified, or Deleted entry whose tenant differs from the resolved one. It is always registered (TryAddSingleton<TenantSaveChangesInterceptor>, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:71), and with no tenant resolved it is inert for updates, deletes, and every entity that does not carry ITenantEntity: the system context is unrestricted on the write side exactly as it is on the read side. Inserts are the one exception. StampOrVerifyInsert throws CrossTenantWriteException.ForUnresolvedTenant when an Added ITenantEntity declares no tenant of its own and the scope resolved none (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/TenantSaveChangesInterceptor.cs:107-110), because a row that no tenant can ever read is a worse outcome than a failed save; a system scope that names the tenant explicitly (a seeder, a per-tenant job) still writes. DesignTimeDbContextHelper registers it too (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:156), so dotnet ef scaffolds against exactly the runtime interceptor pipeline for consumers with and without tenancy. Its absence is survivable rather than fatal: OnConfiguring resolves the tenant interceptor with GetService (ApplicationDbContext.cs:393) and falls back to the two-interceptor chain (:397-400), so a directly-constructed test or design-time context that never registered it still builds.

The tenant is read live, not copied at context creation

ApplicationDbContext gains internal Func<string?>? TenantIdAccessor and CurrentTenantId => TenantIdAccessor?.Invoke() (ApplicationDbContext.cs:235, :242). The scoped context factory assigns () => tenantContext.TenantId when it creates a context, inside AttachScopeAccessors (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:147-164, the assignment at :152), and the value is read at query-compile time rather than captured at construction. Copying at creation would make correctness depend on the middleware having run before the first context in the scope existed, a hazard no test catches and a reordered pipeline reintroduces silently.

DB-per-tenant is a connection-string override behind the same key

When TenancySettings.Tenants[tenant].DataSources[key.Name] has an entry, the scoped DbContextFactory clones the resolver's PhysicalDataSource (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/PhysicalDataSource.cs:21) with the override connection string (and the override Cosmos database name, when one is set) and the same DataSourceKey (ResolveTenantOverride, DbContextFactory.cs:172-197, the clone at :189-196), so EF's model cache key is unchanged and one model still serves every tenant. Creation goes through a new IPhysicalDbContextFactory.Create(key, physical) overload (:37) beside the original single member (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/IPhysicalDbContextFactory.cs:22). That overload is deliberately not a default interface member: it is additive-breaking for any consumer with a custom implementation, and hiding that behind a default body would turn a compile error into a runtime routing surprise, so it goes in the CHANGELOG as breaking-for-implementors. The tenant is not part of the per-scope context cache key (still keyed by DataSourceKey alone, DbContextFactory.cs:103, :110); instead two guards run when a cached context is handed back (:125, :129). GuardRoutedTenantUnchanged (:205) throws if the scope's tenant changes after an overridden context exists, and GuardSharedContextNotRoutable (:230) throws if a context created against the shared database before the tenant resolved is requested for a tenant that turns out to override that source. Both restate the one-scope-one-tenant invariant where it would otherwise break.

ignoreQueryFilters stops meaning "ignore everything"

EFReadRepository names the one filter it means to drop instead of dropping every filter. A single shared field carries the name, private static readonly string[] SoftDeleteFilterOnly = [DbContexts.ApplicationDbContext.SoftDeleteFilterName] (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:41), and it is passed to IgnoreQueryFilters at all eight call sites (:58, :87, :108, :203, :393, :469, :483, :580): one field rather than eight inline arrays, so the set of filters a soft-delete-inclusive read drops cannot diverge between two of them. The repository's ignoreQueryFilters: true parameter has always meant "include soft-deleted rows", and naming the filter keeps that meaning exactly while making it impossible for a soft-delete-inclusive read to cross tenants.

Background work drains and migrates per tenant

OutboxProcessor and OutboxCleanupService enumerate (source, tenant?) pairs from TenancySettings (TenantDataSourceTargets.Expand, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:52, reached through FrameworkTableTargets.Relational (FrameworkTableTargets.cs:44, :63), which OutboxProcessor.GetOutboxTargets (OutboxProcessor.cs:160-161) and OutboxCleanupService.GetRelationalTargets (OutboxCleanupService.cs:208-209) call: one shared target per source plus one target per tenant that overrides that source) and call ITenantContext.SetTenant inside the per-target scope before obtaining the context, through the shared CreateTenantScope helper (TenantDataSourceTargets.cs:100-119, which sets the tenant under AmbientOrigin.Suppress at :105; called at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:200 and MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxCleanupService.cs:99), so the factory routes to the tenant's database and the claim-lease update (OutboxProcessor.cs:376-377, the ExecuteUpdateAsync at :376 that sets LockedUntil and LockToken at :377) runs against the right rows. The processor also opens a fresh tenant scope per dispatched row through the same helper (OutboxProcessor.cs:561), on which the row's stored origin, its tenant included, is restored before dispatch (AmbientOrigin.Restore, :568-575, the tenant passed at :573). Routing does not depend on a tenant column, but the row does carry one: OutboxMessage.TenantId (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/OutboxMessage.cs:95, assigned from the origin at :153) is a nullable string mapped with a 64-character, non-Unicode limit (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:830, inside the OutboxMessage mapping at :811, the length from TenantIdMaxLength at :632), and it records the tenant the row was written under so delivery can restore it (see the Revision (2026-09-11)).

InitializeDatabaseAsync gains a per-tenant pass: a fresh scope per tenant, SetTenant, then the same DatabaseInitStrategy semantics and migrations assembly per overridden source. Module seeding stays default-scope-only in v1, documented as such rather than half-implemented.

Cache isolation lives in the decorators

ICacheService is a singleton and cannot observe scoped state, so tenant awareness goes one layer up: CachingQueryDecorator and CachingCommandDecorator take ITenantContext and prefix the cache key, the invalidation prefix, and the stripe lock with t:{tenantId}: when a tenant is resolved. Doing it in both decorators is what makes read isolation and invalidation isolation symmetric; doing it in one would let tenant A's write evict tenant B's entry or fail to evict its own. Direct ICacheService consumers (login counters, OAuth state, idempotency records) are keyed by subject already and are unchanged. AddMultiTenancy(configuration) additionally validates on start that every override names a source that exists, so a typo fails the host rather than silently routing a tenant to the default database.

Adoption: Helpdesk demonstrates it, ADC and Store do not adopt it

MMCA.ADC and MMCA.Store are single-tenant production applications, so adding a tenant filter and a TenantId column to their aggregates is scope creep with real deploy risk (two production deployments, migrations on every source) for a capability neither product sells. MMCA.Helpdesk is the reference demo: its Tickets entities implement ITenantEntity, it is configured with two tenants, and one of them gets a per-tenant database override, so the runnable seed exercises both halves of this record.

Rationale

  • A query filter is the only place the rule cannot be forgotten. Per-handler Where clauses are correct until the tenth handler, and the tenth handler is a data leak rather than a bug report. The soft-delete filter has proven the mechanism across three applications.
  • Named filters are why this is additive at all. Before EF10, a second global filter would have replaced the soft-delete one, forcing both predicates into one hand-composed expression. Naming them keeps IgnoreQueryFilters(["SoftDelete"]) expressible, so the repository's contract survives unchanged.
  • Embedding the context constant is what keeps one model. Closing over the tenant string at model-build time, the obvious implementation, produces a distinct compiled model per tenant and turns the model cache into a memory leak proportional to tenant count, buying nothing a SQL parameter does not.
  • Null-tenant-sees-all keeps background work simple. The alternative, a system context that enumerates tenants to see everything, pushes tenancy into the outbox loop, the cleanup service, and the migration runner as a control-flow concern rather than as a routing detail. (Superseded by the Revision (2026-11-30): an unresolved tenant could be an anonymous request rather than a system scope, so the system context is now an explicit SetAllTenants() call and null reads nothing.)
  • Fail-closed is the only defensible default for isolation. RequireTenant defaults to true because the failure mode of the other default is serving one customer's data to another, silently, with a 200. A 400 is loud, immediate, and visible in the first smoke test.
  • Same DataSourceKey, different connection string, is the smallest possible DB-per-tenant. An override changes where a source points, not what a source is, so the entity registry, the model cache, the migrations assembly, and the per-source outbox all keep working unchanged.
  • A live accessor removes an ordering hazard rather than documenting it.
  • The decorator is where the cache knows about scope. Pushing tenancy into ICacheService would mean a singleton reaching for scoped state, which is exactly the shape that produces cross-request bleed.

Trade-offs

  • Reads are on discipline where writes are on an invariant. A consumer calling EF's own parameterless IgnoreQueryFilters() on a raw Table surface drops the tenant filter along with soft-delete. Writes remain guarded by TenantSaveChangesInterceptor. MMCA.Common/Source carries one parameterless IgnoreQueryFilters() call site today, in EFFeatureFlagOverrideStore.SetAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/EFFeatureFlagOverrideStore.cs:68), and it crosses no tenant only because its entity, FeatureFlagOverride, is not an ITenantEntity (MMCA.Common/Source/Core/MMCA.Common.Domain/FeatureFlags/FeatureFlagOverride.cs:24), so the call drops the soft-delete filter alone. The other mentions are the doc comments at EFReadRepository.cs:38 and TenantSaveChangesInterceptor.cs:32 explaining why the named form is used. No automated gate holds that: no architecture rule, fitness test, or CI step checks for the parameterless form, so nothing fails a build if a call site appears against a tenant entity. ADR-055's ApplicationLayer_DoesNotUseRawQueryableSurfaces is partial cover only: it does not reach Infrastructure.
  • The singleton physical factory is tenant-unaware by design. PhysicalDbContextFactory.Create (both overloads, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/PhysicalDbContextFactory.cs:25 and :28) has no scope and therefore no tenant: only the scoped DbContextFactory assigns TenantIdAccessor (DbContextFactory.cs:152), so a context obtained straight from the physical factory sees every tenant's rows. (Superseded by the Revision (2026-11-30): with no accessor such a context is neither tenanted nor an all-tenants scope, so it now reads no tenant-owned rows.)
  • Fail-closed means a misconfigured claim takes the whole surface down. A deployment whose identity provider stops emitting tenant_id returns 400 on every non-excluded route rather than degrading to a reduced view. That is the intended trade, and it is still an outage.
  • Shared-schema turns one bad filter into a data leak rather than an error, and a missing ITenantEntity marker on a new entity silently includes that entity's rows in every tenant's queries. A tenancy host that subclasses TenantScopeConventionTestsBase fails its build on that omission (see the Revision (2026-11-07)); a host that does not subclass it is still unguarded.
  • The system context is a privileged mode with no second gate. Any code path that runs without a resolved tenant reads across all tenants, and nothing distinguishes "deliberately system" from "middleware did not run here". (Superseded by the Revision (2026-11-30): "deliberately system" is now the explicit SetAllTenants() call, and "middleware did not run here" reads nothing.)
  • DB-per-tenant multiplies operational surface. Each override adds a migration pass at startup and its own connection pool, so both scale with tenant count, and the per-tenant connection strings live in configuration, making the tenant roster a deployment artifact rather than data.
  • Cache isolation stops at the decorator. Code resolving ICacheService directly gets no tenant prefix. Today's direct consumers are subject-scoped (login counters, OAuth state, idempotency records) so they are safe by accident of their key shape, not by a rule that would catch the next one.
  • Module seeding is default-scope-only in v1. A per-tenant database gets migrations but not seed data.

ADR-006 (the source-name axis this composes with: an override re-points a DataSourceKey without changing it, and the per-source outbox this record drains once per tenant), ADR-005 (the filter this one sits beside and composes with by name, and whose IgnoreQueryFilters contract narrows to ["SoftDelete"]), ADR-018 (the engine axis; CosmosDbContext applies the tenant filters independently because it builds its own), ADR-026 and ADR-014 (the caching decorators that gain the t:{tenantId}: prefix on key, invalidation prefix, and stripe lock), ADR-048 (why TenantId is a plain string and not an identifier alias), ADR-055 (the raw-queryable rule that partially covers the read-side bypass), ADR-030 (who applies migrations, now once per tenant per overridden source), ADR-070 (the validating settings chain TenancySettings binds through, extended with a check that every override names a known source).

Revision (2026-09-11)

The gap this closes was never written down here. Everything above is about the tenant inside a request: the middleware resolves it, the named filter composes on it, the write interceptor stamps and refuses on it, the outbox is drained once per source and tenant pair, and the caching decorators prefix on it. What no section covered is an event leaving one service and arriving in another. The outbox row carried no tenant and the broker message carried no tenant, so the delivery ran in the system context, which this record's own Trade-offs already name as "a privileged mode with no second gate": on a shared-schema host that delivery read across tenants, and on a database-per-tenant host it had no way to pick a database at all.

The tenant is now part of both hops, through one helper. On the producer side the scoped context factory captures ITenantContext.TenantId into the row's origin (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:149-:153), OutboxMessage.TenantId stores it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/OutboxMessage.cs:93, mapped as varchar(64) at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:652), and the processor restores it before the row is dispatched (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:607-:613). Across the broker, BrokerMessageBus stamps MMCA-Tenant-Id (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerMessageBus.cs:94, the constant at MMCA.Common/Source/Core/MMCA.Common.Shared/Messaging/MessageHeaders.cs:25) and the consuming side reads it back (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/ConsumerOriginRestore.cs:53) before the inbox is touched (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumer.cs:62-:64), which matters here specifically: under database-per-tenant the inbox store resolves its context through the same scope, so restoring the tenant afterwards would put the dedup row in the wrong database (ADR-021).

The restore respects the one-scope-one-tenant rule this record set. AmbientOrigin.Restore sets the tenant only when the scope has not already resolved a different one (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/AmbientOrigin.cs:137-:143), and it is restored first, before any repository or context is resolved on that scope, because the tenant routes the context factory and every query filter afterwards reads from it (:135-:136). A host running database per tenant is unaffected by the guard, since its work is already one scope per tenant.

What is still on discipline. A message published by a service that has not upgraded carries no tenant header, and a row written before the migration reads back as null, so those deliveries run untenanted in the system context, exactly as every delivery did before. Nothing fails a build or a startup to say that one publisher in the mesh is still behind: the signal is an absent tenant, which looks the same as a legitimately system-raised event. Adoption is also unchanged, and it is why this closes a hole rather than fixing an outage: ADC and Store are single-tenant, and Helpdesk remains the reference adopter.

Revision (2026-10-01)

The body now agrees with the column the 2026-09-11 Revision added. "Background work drains and migrates per tenant" still stated that there was deliberately no OutboxMessage schema change, and the Rationale still credited the absent column with keeping the upgrade free. Both were wrong after 2026-09-11: OutboxMessage.TenantId exists (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/OutboxMessage.cs:93), nullable and mapped at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:684. The Decision now says so and the Rationale clause is dropped. Database routing for background work is unchanged in substance: the targets come from TenantDataSourceTargets.ExpandRelational and the tenant is set through the shared CreateTenantScope helper (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:134-145). That file's remarks (TenantDataSourceTargets.cs:32-33) still say the outbox has no tenant column; the source comment is stale, not the column.

The tenant-unaware factory named in Trade-offs no longer exists. DefaultSqlServerDbContextFactory and its siblings are gone from MMCA.Common/Source; the remaining runtime path with no tenant is the singleton PhysicalDbContextFactory.Create (both overloads, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/PhysicalDbContextFactory.cs:37 and :40), and at design time DesignTimeDbContextHelper constructs contexts directly without one (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:56, :78, :99), since only the scoped factory assigns TenantIdAccessor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:151, without a null-conditional). The trade itself is unchanged.

Anchors refreshed. The ApplicationDbContext filter, OnConfiguring and interceptor anchors, the middleware step and ApplyPipeline anchors, the interceptor registrations in DependencyInjection and DesignTimeDbContextHelper, PhysicalDataSource, the eight EFReadRepository call sites (still eight), and the outbox scope and claim-lease anchors were re-anchored to current source. The anchors inside the Revision (2026-09-11) are left as that record wrote them.

Revision (2026-10-06)

  • Background-work targets named correctly. TenantDataSourceTargets.ExpandRelational no longer exists; the targets come from TenantDataSourceTargets.Expand (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:51) through FrameworkTableTargets.Relational (FrameworkTableTargets.cs:44, :63), and CreateTenantScope (TenantDataSourceTargets.cs:99-118) now sets the tenant under AmbientOrigin.Suppress (:104).
  • The processor opens a tenant scope per row as well as per target (OutboxProcessor.cs:516), and the stored origin is restored on it (AmbientOrigin.Restore, OutboxProcessor.cs:522-528). The Decision now says so.
  • DB-per-tenant has two guards, not one. Besides GuardRoutedTenantUnchanged (DbContextFactory.cs:202), GuardSharedContextNotRoutable (:227) refuses a shared context created before the tenant resolved once that tenant turns out to override the source. The override clone also carries the tenant's Cosmos database name when one is set (:190-192).
  • Current locations for the Revision (2026-09-11) anchors, which that section keeps as written: origin capture DbContextFactory.cs:156-160; OutboxMessage.TenantId OutboxMessage.cs:95, mapped at ApplicationDbContext.cs:681; consumer header read ConsumerOriginRestore.cs:54, applied before the inbox at IntegrationEventConsumer.cs:64-66; AmbientOrigin.Restore declared at AmbientOrigin.cs:156, restoring the tenant first at :171 through RestoreTenant (:194-203). For the Revision (2026-10-01): PhysicalDbContextFactory.Create overloads at PhysicalDbContextFactory.cs:25 and :28, the sole TenantIdAccessor assignment at DbContextFactory.cs:152, the outbox mapping at ApplicationDbContext.cs:681, CreateTenantScope at TenantDataSourceTargets.cs:99-118.
  • Every path:line anchor in the live sections was re-verified against current source and re-anchored where it had moved.

Revision (2026-10-07)

Re-verified against current source. The decision is unchanged: the tenant filter still composes with soft-delete by name, background work still drains per (source, tenant?) target through TenantDataSourceTargets.Expand and CreateTenantScope, and the processor still restores each row's stored origin on a fresh per-row tenant scope. Only line numbers moved, plus one correction to a note in the Revision (2026-10-01).

  1. The TenantDataSourceTargets remarks are no longer stale. The Revision (2026-10-01) recorded that the file's remarks still said the outbox had no tenant column. They now say the outbox's TenantId column exists and does not partition the drain, because it records the raising scope's tenant and the processor restores it around each row's delivery (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:31-34). That section keeps its wording as written.
  2. Anchors re-verified against current source: ApplySoftDeleteFilters ApplicationDbContext.cs:454, OnModelCreating :417 calling it at :419 (and ApplyTenantFilters at :420), the named HasQueryFilter at :466, SoftDeleteFilterName at :475, the OutboxMessage.TenantId mapping at :682 with TenantIdMaxLength at :484; TenantDataSourceTargets.Expand TenantDataSourceTargets.cs:52, CreateTenantScope :100-119 with AmbientOrigin.Suppress at :105; OutboxProcessor.GetOutboxTargets OutboxProcessor.cs:144-145, the per-target CreateTenantScope call at :184, the claim-lease ExecuteUpdateAsync at :358-359 (LockedUntil and LockToken at :359), the per-row scope at :498 and AmbientOrigin.Restore at :505-511. For the dated revisions, which keep their anchors as written: OutboxMessage.TenantId is at OutboxMessage.cs:95 and mapped at ApplicationDbContext.cs:682; the processor restore is at OutboxProcessor.cs:505-511; CreateTenantScope is at TenantDataSourceTargets.cs:100-119.

Revision (2026-10-21)

Re-verified against current source. The isolation model is unchanged: the tenant filter still composes with soft-delete by name, writes are still guarded by TenantSaveChangesInterceptor, DB-per-tenant is still a connection-string override behind the same DataSourceKey, and background work still drains per (source, tenant?) target. One default moved, and line numbers moved.

  1. The default resolution order is the claim only. Since v1.243.0 (MMCA.Common/CHANGELOG.md:189, listed under Breaking) TenancySettings falls back to [Claim] when ResolutionOrder is empty (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:61-62, :82-83), not [Claim, Header]. Header resolution is an explicit opt-in, because a caller-supplied header lets any caller name any tenant (TenancySettings.cs:15-21, :74-79), and resolution reads HeaderName only when Header is listed (:91-95; TenantResolutionMiddleware.cs:108-116). Listing the claim first is recommended, not enforced at startup: TenancySettingsValidator.cs:55-63 rejects only Host, and the claim-before-header fact lives in the optional conformance base TenantResolutionTestsBase.cs:66-81. Helpdesk, the reference adopter, opts in with the claim first (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/appsettings.json:32) and does not subclass that base. The unresolved-tenant 400 still names HeaderName beside ClaimType in every response (TenantResolutionMiddleware.cs:143-147), header listed or not. The Decision heading and the settings paragraph now say so.
  2. Anchors re-verified against current source: AttachScopeAccessors DbContextFactory.cs:147-164 (the TenantIdAccessor assignment still at :152), ResolveTenantOverride :172-197 with the clone at :189-196, GuardRoutedTenantUnchanged :205, GuardSharedContextNotRoutable :230 (the cache key at :103/:110 and the guard calls at :125/:129 unchanged); the eight EFReadRepository call sites :58, :87, :108, :203, :393, :469, :483, :580 (still eight, the field still at :41); OutboxProcessor.GetOutboxTargets OutboxProcessor.cs:155-156, the per-target CreateTenantScope call at :195, the claim-lease ExecuteUpdateAsync at :371-372 (LockedUntil and LockToken at :372), the per-row scope at :556; the OutboxMessage.TenantId assignment from the origin at OutboxMessage.cs:153 (declared at :95).

Revision (2026-10-26)

Re-verified against current source. The isolation model and the resolution defaults are unchanged: claim-only by default, header by explicit opt-in, the unresolved-tenant 400 naming both ClaimType and HeaderName, and background work draining per (source, tenant?) target. One description was incomplete, and line numbers moved.

  1. The optional conformance base holds three facts, not one. The Decision named only the claim-before-header check. TenantResolutionTestsBase also asserts that header resolution is an explicit opt-in (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/TenantResolutionTestsBase.cs:46-61, gated by the virtual AllowsHeaderResolution at :40, default false) and that the health endpoints stay excluded (:87-100), beside the claim-before-header fact (:66-81). The v1.243.0 entry lists all three (MMCA.Common/CHANGELOG.md:385, the release heading at :380). With tenancy enabled, a host that lists Header, as Helpdesk does (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/appsettings.json:32), and subclasses the base also overrides AllowsHeaderResolution (the fact returns early when tenancy is disabled, :50-53). The resolution-order Decision paragraph now says so.
  2. Anchors re-verified against current source: UseCommonMiddlewarePipeline WebApplicationExtensions.cs:49 (the configure overload at :61, ApplyPipeline at :171); the unresolved-tenant 400 detail TenantResolutionMiddleware.cs:146-150 (ClaimType at :147, HeaderName at :149); OutboxProcessor.GetOutboxTargets OutboxProcessor.cs:157-158, the per-target CreateTenantScope call at :197, the claim-lease ExecuteUpdateAsync at :373 (LockedUntil and LockToken at :374), the per-row scope at :558 with AmbientOrigin.Restore at :565-572 (the tenant at :570); OutboxCleanupService.GetRelationalTargets OutboxCleanupService.cs:196-197 (its CreateTenantScope call still at :98). For the dated revisions, which keep their anchors as written: the v1.243.0 Breaking bullet the Revision (2026-10-21) cites is at MMCA.Common/CHANGELOG.md:404; AmbientOrigin.Restore is declared at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/AmbientOrigin.cs:254, calling RestoreTenant at :270 (declared at :294); the consumer tenant header read is at ConsumerOriginRestore.cs:55, applied before the inbox at IntegrationEventConsumer.cs:64-66; BrokerMessageBus stamps MessageHeaders.TenantId at BrokerMessageBus.cs:92 (the constant still at MessageHeaders.cs:25).

Revision (2026-10-28)

Re-verified against current source. The isolation model and the resolution defaults are unchanged: claim-only by default, header by explicit opt-in, and the optional TenantResolutionTestsBase holding its three facts. Only the CHANGELOG.md anchors the two previous revisions cite have moved, as later releases were prepended above the v1.243.0 entry.

  1. Anchors re-verified against current source. For the dated revisions, which keep their anchors as written: the v1.243.0 release heading is at MMCA.Common/CHANGELOG.md:423 (the Revision (2026-10-26) cites :380); the TenantResolutionTestsBase three-facts entry is at :428 (cited there as :385); the change both revisions call the Breaking bullet is a **Breaking:** bullet under ### Changed (:444) at :446, its sub-bullet "Tenant resolution reads only the claim unless configured otherwise." at :447 (cited as :189 by the Revision (2026-10-21) and as :404 by the Revision (2026-10-26)). It is a labeled bullet under Changed, not a separate Breaking section.

Revision (2026-11-07)

The forgotten-marker trade-off now has a gate a tenancy host can inherit. The isolation model, the resolution defaults and the filters are unchanged.

  1. TenantScopeConventionTestsBase ships in MMCA.Common.Testing.Architecture (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Domain/TenantScopeConventionTestsBase.cs:14) with two facts. EntitiesWithTenantId_ShouldImplement_ITenantEntity (:24-26) fails when any concrete Domain or Infrastructure entity, framework or module, declares or inherits a TenantId property without implementing ITenantEntity, the marker that applies the named Tenant filter and the save interceptor (.../Rules/Domain/ArchitectureRules.Tenancy.cs:8-16). ModuleEntities_ShouldBeTenantScoped_OrDeclaredGlobal (:28-30) fails when a concrete module entity is neither tenant-scoped nor named in the subclass's GlobalEntityTypes (:22), type full names or namespace prefixes matched ordinally (ArchitectureRules.Tenancy.cs:30-46). The second fact is the one that closes the trade-off: a new module entity without the marker now fails the build unless someone declares it global, and that declaration is a reviewed line in the test subclass rather than an absence. Framework entities are out of its scope, since whether a framework row is tenant-owned is the framework's decision (ArchitectureRules.Tenancy.cs:37-39).
  2. It is a host's opt-in, as the tenancy itself is. The base is subclassed only in a host that enables tenancy, with an empty GlobalEntityTypes by default, so every module entity must be scoped until the subclass lists the shared ones (TenantScopeConventionTestsBase.cs:7-12, :18-22). Common has no modules, so its own test calls only the first rule (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Domain/EntityModel/TenantEntityConventionTests.cs:29-39), and the second rule's fixture tests pin both outcomes (.../Domain/EntityModel/TenantScopeFitnessTests.cs:23, :32, :43). No consumer subclasses the base yet: Helpdesk, the reference tenancy adopter, is the planned first; ADC and Store stay single-tenant. Until a host subclasses it, the trade-off holds for that host as originally written.

Revision (2026-11-23)

Re-verified against current source. The isolation model is unchanged: the tenant filter still composes with soft-delete by name, writes are still guarded by TenantSaveChangesInterceptor registered between the audit and domain-event interceptors, and background work still drains per (source, tenant?) target. One count in Trade-offs was wrong, and line numbers moved.

  1. There is one parameterless IgnoreQueryFilters() call site in MMCA.Common/Source, not zero. EFFeatureFlagOverrideStore.SetAsync calls it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/EFFeatureFlagOverrideStore.cs:68) on FeatureFlagOverride, an AuditableBaseEntity<string> that is not an ITenantEntity (MMCA.Common/Source/Core/MMCA.Common.Domain/FeatureFlags/FeatureFlagOverride.cs:24), so it drops only the soft-delete filter and reads across no tenant. The doc comments at EFReadRepository.cs:38 and TenantSaveChangesInterceptor.cs:32 are still the only other mentions, and still nothing in MMCA.Common/Source/Hosting checks for the parameterless form. The Trade-offs bullet now says so; the Revised 2026-08-23 Status sentence keeps its "zero" as written.
  2. Anchors re-verified against current source: ApplySoftDeleteFilters ApplicationDbContext.cs:602, OnModelCreating :530 calling it at :554 (and ApplyTenantFilters at :555), the named HasQueryFilter at :614, SoftDeleteFilterName at :623, TenantIdMaxLength at :632; OnConfiguring :378 with the audit and domain-event interceptors resolved at :385-386, the tenant interceptor's GetService at :393, the three-interceptor chain at :395 and the two-interceptor fallback at :397-400; TenantIdAccessor :235 and CurrentTenantId :242 (the sole assignment still at DbContextFactory.cs:152); the OutboxMessage.TenantId mapping at :830 inside the OutboxMessage block at :811 (OutboxMessage.cs:95, assigned at :153); TryAddSingleton<TenantSaveChangesInterceptor> DependencyInjection.cs:71; the design-time registration DesignTimeDbContextHelper.cs:156; Helpdesk's ResolutionOrder appsettings.json:35; OutboxProcessor.GetOutboxTargets OutboxProcessor.cs:160-161, the per-target CreateTenantScope call at :200, the claim-lease ExecuteUpdateAsync at :376 (LockedUntil and LockToken at :377), the per-row scope at :561 with AmbientOrigin.Restore at :568-575 (the tenant at :573); OutboxCleanupService.GetRelationalTargets OutboxCleanupService.cs:208-209 (its CreateTenantScope call at :99). For the dated revisions, which keep their anchors as written: BrokerMessageBus stamps MessageHeaders.TenantId at BrokerMessageBus.cs:93, and the OutboxMessage.TenantId mapping they cite as ApplicationDbContext.cs:652, :681, :682 or :684 is at :830.

Revision (2026-11-30)

MMCA.Common v1.324.0 (MMCA.Common/CHANGELOG.md:11). The isolation model (two named filters composed by AND, one cached model per source, the write interceptor, DB-per-tenant routing) is unchanged; what an unresolved tenant reads, and which callers may name a tenant, changed.

  1. The read filter fails closed. The Tenant filter is now IsAllTenantsScope || TenantId == CurrentTenantId (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:548, :591-597, documented at :530-535). A required TenantId never equals null, so a scope that resolved no tenant reads no tenant-owned rows; before this release it read every tenant's rows. The write guard was already closed (an untenanted insert throws), so reads and writes now agree. Found because Helpdesk ran with RequireTenant: false, where an anonymous request that carried no tenant would have read every tenant's tickets.
  2. Seeing every tenant is an explicit call. ITenantContext gains IsAllTenants and SetAllTenants() (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ITenantContext.cs:40, :58). The scoped TenantContext keeps one answer per scope in both directions: SetAllTenants() throws once a tenant is set, and SetTenant throws once the scope is all-tenants (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/TenantContext.cs:32-44, :51-58). The context reads the flag live through AllTenantsAccessor, wired by DbContextFactory beside the tenant accessor (ApplicationDbContext.cs:152, :159; .../Persistence/DbContexts/Factory/DbContextFactory.cs:152-153), so one compiled model still serves every scope. No framework processor calls it: Common declares no ITenantEntity of its own (the outbox, inbox and internal-command tables are not tenant-owned, and the outbox restores each row's origin tenant per dispatch), so only a host with tenant entities adds the call to its seeders, sweeps and operator flows (MMCA.Common/UPGRADING.md, [1.324.0] section).
  3. The header is trusted only on request. TenancySettings.TrustTenantHeader (default false, .../Persistence/Tenancy/TenancySettings.cs:100-107) gates the Header strategy twice: the middleware ignores the header unless it is trusted (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/TenantResolutionMiddleware.cs:112-113), and startup validation fails when Tenancy:ResolutionOrder lists Header without it (.../Persistence/Tenancy/TenancySettingsValidator.cs:75-83). Set it only where every request reaches the host through a gateway or a server-side client that sets the header itself.
  4. TenantResolutionStrategy.Host is removed. It was defined and never implemented; the enum is Claim and Header (TenancySettings.cs:6-22). Because the configuration binder drops a list element it cannot convert, the raw ResolutionOrder values are checked at startup, so "Host" or a typo fails the boot instead of silently leaving the default order in force (TenancySettingsValidator.cs:58-63, registered at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:343-349; a numeric value is caught at TenancySettingsValidator.cs:85-91).
  5. RequireTenant: false keeps meaning "global endpoints still run". An unscoped request is not refused, but it now reaches only global data (TenancySettings.cs:95-98).
  6. Adoption. ADC and Store stay single-tenant and are unaffected. MMCA.Helpdesk adopts the change in its v1.324.0 upgrade (pull request #261, open when this revision was written): RequireTenant: true, TrustTenantHeader: true because its UI is the server-side caller that sets the header, claim before header (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/appsettings.json:38-40 on that branch).
  7. Superseded in place, marked rather than rewritten: the Decision's null-tenant paragraph, the "rejects only Host" sentence, the "Null-tenant-sees-all" Rationale bullet, and the physical-factory and "privileged mode" Trade-offs. The dated Revisions keep their wording.