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

Architecture Decision Record

ADR-148: Model Contributors for Optional Framework Tables (the Base Context Stays Closed)

Status

Accepted (2026-11-30). Released in MMCA.Common v1.324.0 (MMCA.Common/CHANGELOG.md:7, the entry at :31); the generated EF model of every framework table is unchanged by it, so no consumer needed a migration for this change. Builds on ADR-006 (one sealed context class per engine, one instance per database) and ADR-018 (relational engines beside Cosmos DB).

Context

Nine framework features own an optional table: the job store, the change trail, refresh sessions, stored permission grants, view-as grants, feature-flag overrides, passkeys, machine clients and webhook subscriptions. Each table must appear only in the model of the database its feature names, and only when the host turned the feature on, so that every other database's model and migrations stay byte-identical.

Up to MMCA.Common v1.323.0 each of them was wired into ApplicationDbContext by hand. The context held one _xxxTableEnabled field per feature, resolved in OnConfiguring through one Resolve*Gate method per feature (six of them, at ApplicationDbContext.cs:1075-1147 in that release, called at :431-441), one if (_xxxTableEnabled) Configure*(modelBuilder) branch per feature in OnModelCreating, and a nine-bit ModelGateMask that the model cache key read so that differently opted-in hosts in one process did not share a cached model (:198-207). DesignTimeDbContextHelper repeated the same per-feature wiring for dotnet ef. The file was 1222 lines at v1.323.0. Every new optional table therefore edited the base context in four places and the design-time helper in a fifth, and a missed bit in the mask would hand one host another host's model without any test failing.

The question this record answers is how an optional table joins the model of the one context class per engine without that class knowing the feature exists.

Decision

An optional table is an IModelContributor registered by its feature's own AddX call. The base context runs whatever contributors apply to its physical source and knows none of them by name.

The extension point

IModelContributor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/IModelContributor.cs:40) has three members:

  • Phase (:46), a ModelContributorPhase (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ModelContributorPhase.cs:8): BeforeEntityPasses (:16) runs beside the module entity configurations, so the soft-delete filter, the tenant filter and the concurrency-token passes see the contributed entity (the phase for an auditable or tenant-owned table); AfterEntityPasses (:23) runs after those passes and after the outbox, inbox and internal-command tables, so no pass touches it. Contributors sharing a phase run in registration order (IModelContributor.cs:43-44).
  • AppliesTo(PhysicalDataSource) (:56): whether the contribution belongs in this context's model, typically "the feature is enabled and this is the database its settings name". It is the gate the old Resolve*Gate methods were.
  • Configure(ModelBuilder, DataSource) (:67): adds the mapping. It must be a pure function of the contributor's type and the engine it is handed (:58-60): anything a host's settings change belongs in AppliesTo or in a distinct contributor type (:27-33).

ApplicationDbContext.OnConfiguring resolves every registered contributor from the root provider, keeps the ones whose AppliesTo accepts the context's physical source, and orders them by phase with a stable sort (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:332-336, held in _modelContributors at :83). OnModelCreating (:426) runs the BeforeEntityPasses set (:431), the three entity passes (:433-435), the outbox, inbox and internal-command tables (:438-444), then the AfterEntityPasses set (:448), through one loop (ApplyModelContributors, :457-464). The context is 890 lines after the change.

Which feature registers which contributor

Each contributor is registered as a singleton by the call that turns its feature on, so the registration is the opt-in:

Table Contributor phase Registered by
Stored permission grants After (.../Persistence/Auth/PermissionGrantModelBuilderExtensions.cs:87) AddStoredPermissionGrants (.../DependencyInjection.Auth.cs:176, registration at :185)
Feature-flag overrides Before (.../Persistence/FeatureFlags/FeatureFlagOverrideModelBuilderExtensions.cs:89) AddReloadableFeatureFlags (.../DependencyInjection.FeatureFlags.cs:49, at :73)
Job store After (.../Scheduling/ScheduledJobModelContributor.cs:22) AddScheduledJobs (.../DependencyInjection.Jobs.cs:37, at :52)
Change trail After (.../Persistence/AuditTrail/AuditTrailModelContributor.cs:20) AddAuditTrail (.../DependencyInjection.Jobs.cs:112, at :125)
Machine clients Before (.../Persistence/MachineClients/MachineClientModelBuilderExtensions.cs:74) AddMachineClients (.../DependencyInjection.MachineClients.cs:38, at :50)
Webhook subscriptions Before (.../Persistence/Webhooks/WebhookSubscriptionModelBuilderExtensions.cs:77) AddWebhooks (.../Webhooks/WebhookServiceCollectionExtensions.cs:68, at :79)
Refresh sessions After (.../Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:124) AddInfrastructure (.../DependencyInjection.cs:59, at :180)
View-as grants After (.../Persistence/Auth/ViewAsGrantModelBuilderExtensions.cs:76) AddInfrastructure (at :207)
Passkeys After (.../Persistence/Auth/PasskeyCredentialModelBuilderExtensions.cs:75) AddInfrastructure (at :218)

All paths are under MMCA.Common/Source/Core/MMCA.Common.Infrastructure/. The three AddInfrastructure contributors are registered unconditionally and decide in AppliesTo from their settings (for example RefreshSessions:Enabled and RefreshSessions:DataSourceName, .../DependencyInjection.cs:177). TryAddEnumerable keeps a repeated AddX from registering a contributor twice; the feature-flag call uses its contributor's descriptor as its own "already registered" marker (.../DependencyInjection.FeatureFlags.cs:59-65).

The model cache key carries the contributor types

DataSourceModelCacheKeyFactory.Create keys EF's process-wide model cache on the context type, the source name, ModelContributorKey, the strongly typed identifier key and the design-time flag (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/DataSourceModelCacheKeyFactory.cs:26-33). ModelContributorKey is the assembly-qualified type names of the applying contributors in application order (ApplicationDbContext.cs:107-108), which replaces the nine-bit gate mask. Types, never instance state, which is sound only because Configure may depend on nothing but its type and the engine (ApplicationDbContext.cs:99-104): every model difference a setting makes shows up as a type joining or leaving the key. ModelCacheKeyGateTests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/ModelCacheKeyGateTests.cs:50) proves the key moves with every framework contributor.

Design time

DesignTimeDbContextHelper registers the framework's contributors from the existing Enable* flags of DesignTimeDbContextOptions (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:192-209, through AddContributorWhen at :237), then a host's own contributors after them (:211-215). A host adds its own through DesignTimeDbContextOptions.ModelContributors and AddModelContributor(...) (.../Design/DesignTimeDbContextOptions.cs:264, :269), constructed over the same settings it binds at runtime, because a contributor registered at runtime but missing at design time makes the scaffolded migrations and the running model disagree (:257-263). No consumer registers a contributor of its own today.

Relational engines only

Cosmos DB never runs the base model pipeline, so OnConfiguring resolves no contributors there and the Cosmos cache key is never split by them (ApplicationDbContext.cs:329-336; IModelContributor.cs:36-37).

The gate: the model is proved unchanged, not argued

FrameworkModelSnapshotTests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/ModelSnapshots/FrameworkModelSnapshotTests.cs:35) serializes the design-time model of the framework tables, with every annotation, for SQL Server, PostgreSQL and SQLite in three configurations each (no optional table, every optional table on the Default source, every optional table on a named source; :41-51, :54-69) and compares it with a committed golden per runtime: eighteen golden files beside the test, regenerated only deliberately with MMCA_UPDATE_MODEL_SNAPSHOTS=1 (:26). The goldens were generated before the refactor and are byte-identical after it (MMCA.Common/CHANGELOG.md:31). Three guard facts sit beside them: the every-table configuration really maps all nine tables (:80-96), the job table stays out of a named source (:98-109), and registering the contributors in reverse produces the same golden, so a host's AddX order cannot change its model (:111-122).

Rationale

  • The base context is closed to new optional tables. A tenth table is a new contributor and a registration in its feature's AddX; ApplicationDbContext, the cache key factory and the design-time helper's loop need no edit.
  • The gate lives with the feature. Which database a table belongs to is the feature's setting, and AppliesTo sits beside the mapping it gates, instead of a Resolve*Gate method in a file that has to know every feature's settings type.
  • The cache key cannot fall out of step. The mask was a second list of the same nine features that had to be kept in sync by hand; the type list is derived from the contributors that actually applied.
  • One context per engine is untouched. Contributors change how the one model is assembled, not how many context classes exist or which database a context targets, so ADR-006 holds as written.

Trade-offs

  • One more indirection when reading the model. The tables a source maps are no longer visible in OnModelCreating; a reader follows the registrations in the table above, or runs the snapshot test.
  • Runtime and design time are two registration paths. A host contributor added at runtime but not through AddModelContributor produces migrations that miss its table. The framework's own are kept in step by the Enable* flags and the goldens; a host's are kept in step only by its own pending-model-changes check.
  • A hand-assembled service provider maps less. A context built from a provider that registered a feature's settings but not its contributor no longer maps that table (MMCA.Common/UPGRADING.md, [1.324.0] section). That is the intended semantics (the registration is the opt-in) but it broke one consumer test that copied settings alone.
  • Configure must stay pure. A contributor that read a setting inside Configure would let a second, differently configured host in the same process receive the first host's cached model. Only the interface remarks state the rule; no analyzer enforces it.

Alternatives rejected

  • A context class per feature (weighed 2026-11-30). Each optional table in its own context would keep the base class small, but it breaks ADR-006's one sealed context class per engine and one instance per database: a single database would be written through several contexts, the outbox and the unit of work would no longer share a transaction with the feature's writes, and migrations would split per feature. Revisit only if ADR-006 itself changes.
  • Partial classes of ApplicationDbContext (weighed 2026-11-30). Moving each feature's field, gate and configure call into its own partial file tidies the file but still edits the base type for every new table, still needs the shared cache-key mask, and cannot be extended by a host from another assembly. Revisit never: it changes file layout, not the dependency.
  • EF IEntityTypeConfiguration assembly scanning (weighed 2026-11-30). Scanning would find the mappings without a registration, but a configuration class cannot express the per-source gate (the table belongs in one database and only when the feature is enabled), cannot choose a phase relative to the soft-delete and tenant passes, and would put every scanned table into every source's model. Revisit if EF adds a per-model gate to configuration discovery.

Consequences

  • Consumers needed no migration for this change; the consumer upgrade notes cover only a test or tool that builds a context from a hand-assembled provider (MMCA.Common/UPGRADING.md, [1.324.0] section).
  • The next optional framework table follows the table above: a contributor class beside its mapping, a TryAddEnumerable registration in its AddX, an Enable* flag and an AddContributorWhen line in the design-time helper, and a regenerated, reviewed golden.

ADR-006 (one context class per engine, which this record keeps), ADR-018 (why Cosmos DB is out of scope), ADR-073 (the tenant pass a BeforeEntityPasses contributor's entity joins), ADR-116, ADR-137, ADR-139, ADR-140 and ADR-142 (features whose tables are contributors).