Repository navigation
Partition cache framework with first cache consumers - #6097
apurvabhaleMS wants to merge 7 commits into
Conversation
Adds PartitionCache<T>, ScopedCache<T>, CacheInitializer and AddPartitionCache in Core, and SqlPartitionCache<T> in SqlServer, per ADR 2611. Custom query procedures move from the static CustomQueries to CustomQueryCache, which loads sys.objects from each partition's database instead of the default database. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
CacheSlot<T> holds the load lock, expiry and refresh-failure handling for both cache kinds. AddGlobalCache registers app-wide caches, which CacheInitializer preloads once before the partition caches. SqlPartitionCache<T> becomes internal. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- RoleCache (GlobalCache) loads and validates roles.json; RoleLoader still fails startup on invalid roles. - DatabaseParameters/DatabaseParameterCache replace CachedParameter and the static flags in SqlServerSearchService and SqlServerFhirDataStore. - CacheInitializer preloads on IHostApplicationLifetime.ApplicationStarted (the web host never calls IHostedLifecycleService). - Parameter IDs match case-insensitively, ignoring trailing spaces, like the SQL lookup they replace. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
A critical cache-loading race lets a rejected load overwrite a later successful value, alongside case-sensitive procedure matching and Azure SQL cleanup regressions.
3 open issues
What changed in this PR
Implements phase 1a of the partition-cache design for Microsoft FHIR Server, building on partition-aware database routing. It introduces shared cache infrastructure and migrates the first SQL and authorization consumers.
Changes:
- Adds global, partition, and request-scoped caches with expiry, coordinated loading, and background startup preload.
- Migrates custom query procedures, search and merge parameters, and roles to the new framework.
- Adds cache tests, replaces timing-based cache checks, and updates the staged rollout documentation.
| File | Description |
|---|---|
| test/Microsoft.Health.Fhir.Shared.Tests.Integration/Persistence/SqlServerPartitionCacheTests.cs | Adds database-backed partition isolation tests. |
| test/Microsoft.Health.Fhir.Shared.Tests.Integration/Persistence/SqlServerFhirStorageTestsFixture.cs | Supplies scoped caches and a controllable clock. |
| test/Microsoft.Health.Fhir.Shared.Tests.Integration/Persistence/SqlServerCreateStatsTestsCollection.cs | Clarifies the serialization comment. |
| test/Microsoft.Health.Fhir.Shared.Tests.Integration/Persistence/SqlServerCreateStatsTests.cs | Expires parameter values through the test clock. |
| test/Microsoft.Health.Fhir.Shared.Tests.Integration/Persistence/SqlComplexQueryTests.cs | Replaces timed polling with controlled cache expiry. |
| test/Microsoft.Health.Fhir.Shared.Tests.Integration/Persistence/FhirStorageTestsFixture.cs | Exposes custom query caches and the test clock. |
| test/Microsoft.Health.Fhir.Shared.Tests.Integration/Microsoft.Health.Fhir.Shared.Tests.Integration.projitems | Includes the new integration tests. |
| src/Microsoft.Health.Fhir.Tests.Common/Categories.cs | Adds the caching test category. |
| src/Microsoft.Health.Fhir.SqlServer/Registration/FhirServerBuilderSqlServerRegistrationExtensions.cs | Registers SQL partition caches. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Storage/SqlServerFhirDataStore.cs | Reads merge flags through scoped parameters. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Storage/DatabaseParameters.cs | Adds immutable numeric parameter lookups. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Storage/DatabaseParameterCache.cs | Loads numeric settings per partition. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Storage/CachedParameter.cs | Removes the previous per-setting cache. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Search/SqlServerSearchService.cs | Uses scoped procedure and parameter caches. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Search/CustomQueryProcedures.cs | Adds immutable procedure lookup by query hash. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Search/CustomQueryCache.cs | Loads procedures from each partition database. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Search/CustomQueries.cs | Removes the static procedure cache. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Partitions/SqlPartitionManager.cs | Enumerates configured partitions for preload. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Partitions/PartitionInfoExtensions.cs | Resolves database names from partition information. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Partitions/FhirRequestContextExtensions.cs | Reuses the partition database helper. |
| src/Microsoft.Health.Fhir.SqlServer/Features/Caching/SqlPartitionCache.cs | Provides partition-specific SQL connections. |
| src/Microsoft.Health.Fhir.SqlServer.UnitTests/Features/Storage/SqlServerFhirDataStoreUnitTests.cs | Supplies parameter caches to data-store tests. |
| src/Microsoft.Health.Fhir.SqlServer.UnitTests/Features/Storage/PartitionConfigurationTests.cs | Tests configured partition enumeration. |
| src/Microsoft.Health.Fhir.SqlServer.UnitTests/Features/Storage/DatabaseParametersTests.cs | Tests values, defaults, and normalized IDs. |
| src/Microsoft.Health.Fhir.SqlServer.UnitTests/Features/Search/SqlServerSearchServiceTests.cs | Supplies scoped caches to search tests. |
| src/Microsoft.Health.Fhir.SqlServer.UnitTests/Features/Search/SqlServerSearchServiceQueryStoreTests.cs | Removes obsolete parameter-cache tests. |
| src/Microsoft.Health.Fhir.SqlServer.UnitTests/Features/Search/CustomQueryProceduresTests.cs | Tests procedure-name parsing and lookup. |
| src/Microsoft.Health.Fhir.SqlServer.UnitTests/Features/Search/CustomQueriesUnitTests.cs | Removes static-cache timing tests. |
| src/Microsoft.Health.Fhir.Shared.Api.UnitTests/Features/SMART/SmartClinicalScopesMiddlewareTests.cs | Updates role-loading setup to use RoleCache. |
| src/Microsoft.Health.Fhir.CosmosDb/Features/Storage/CosmosPartitionManager.cs | Returns an empty partition enumeration. |
| src/Microsoft.Health.Fhir.Core/Registration/CacheRegistrationExtensions.cs | Adds cache registration and preload wiring. |
| src/Microsoft.Health.Fhir.Core/Features/Security/RoleSet.cs | Wraps the cached role collection. |
| src/Microsoft.Health.Fhir.Core/Features/Security/RoleLoader.cs | Loads cached roles while retaining startup validation. |
| src/Microsoft.Health.Fhir.Core/Features/Security/RoleCache.cs | Moves role parsing and validation into a global cache. |
| src/Microsoft.Health.Fhir.Core/Features/Partitions/IPartitionManager.cs | Adds the partition enumeration contract. |
| src/Microsoft.Health.Fhir.Core/Features/Caching/ValueTaskExtensions.cs | Checks synchronous task completion. |
| src/Microsoft.Health.Fhir.Core/Features/Caching/ScopedCache.cs | Selects cache values using request context. |
| src/Microsoft.Health.Fhir.Core/Features/Caching/PartitionCache.cs | Maintains cache slots by partition ID. |
| src/Microsoft.Health.Fhir.Core/Features/Caching/GlobalCache.cs | Provides a process-wide cache value. |
| src/Microsoft.Health.Fhir.Core/Features/Caching/CacheSlot.cs | Coordinates loading, expiry, and refresh failure handling. |
| src/Microsoft.Health.Fhir.Core/Features/Caching/CachePreload.cs | Describes registered preload operations. |
| src/Microsoft.Health.Fhir.Core/Features/Caching/CacheInitializer.cs | Preloads caches after application startup. |
| src/Microsoft.Health.Fhir.Core.UnitTests/Features/Security/RoleLoaderTests.cs | Updates validation tests to use RoleCache. |
| src/Microsoft.Health.Fhir.Core.UnitTests/Features/Security/DefaultRolesTests.cs | Updates default-role test setup. |
| src/Microsoft.Health.Fhir.Core.UnitTests/Features/Caching/TestPartitionCache.cs | Adds a reusable configurable test cache. |
| src/Microsoft.Health.Fhir.Core.UnitTests/Features/Caching/ScopedCacheTests.cs | Tests request partition selection. |
| src/Microsoft.Health.Fhir.Core.UnitTests/Features/Caching/PartitionCacheTests.cs | Tests isolation, expiry, failures, and concurrent loading. |
| src/Microsoft.Health.Fhir.Core.UnitTests/Features/Caching/GlobalCacheTests.cs | Tests value reuse and expiry. |
| src/Microsoft.Health.Fhir.Core.UnitTests/Features/Caching/CacheInitializerTests.cs | Tests preload timing, partition coverage, and registration. |
| src/Microsoft.Health.Fhir.Api/Modules/SecurityModule.cs | Registers the global role cache. |
| docs/arch/multitenancy-cache-catalogue.md | Records migrated consumers and splits phase 1. |
| docs/arch/adr-2611-partition-cache-management.md | Updates cache contracts and preload design. |
Review effort: Balanced
- Loaders and PartitionCache take a partition ID (item 3); SqlPartitionCache resolves it to the database through IPartitionManager. - CacheInitializer preloads each partition in its own DI scope with a background request context for that partition, through ScopedCache<T>.GetAsync() (item 4). - A failed refresh returns the previous value and the next read retries, as custom queries did before (item 6). - ADR clarifications updated to match. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- CacheSlot: a synchronous load that returns an incomplete task is rejected without awaiting it, so it can't publish a value later. - CustomQueryProcedures: match the CustomQuery_ prefix case-insensitively, as before. - SqlServerFhirDataStore: load dbo.Parameters once per merge/import with GetAsync and pass it down. - Partition cache integration test: drop databases in standalone batches (Azure SQL); ReturnsNull in ScopedCacheTests. - ADR/catalogue: clarify refresh-failure handling and background jobs, drop the Azure SQL three-part-name claim, note roles readers move to RoleCache in 1b. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## feature/multitenancy #6097 +/- ##
=======================================================
Coverage ? 81.03%
=======================================================
Files ? 1008
Lines ? 38316
Branches ? 6102
=======================================================
Hits ? 31050
Misses ? 5779
Partials ? 1487 🚀 New features to boost your workflow:
|
| { | ||
| string database = GetDatabase(partitionId); | ||
| SqlConnection connection = async | ||
| ? await _connectionBuilder.GetSqlConnectionAsync(database, cancellationToken: cancellationToken) |
There was a problem hiding this comment.
Instead of relying on changing the initial catalog, should our queries instead target the database in question via the object identifiers <database>.<schema>.<object> to reuse the same connection string pool?
There was a problem hiding this comment.
Good call, thanks! Switched to database-qualified names: SqlPartitionCache now runs every cache query on the shared connection string (one pool for all partitions) and qualifies object names with the partition's database through SqlObjectNameFormatter, the same way partition routing does (e.g. [FhirDB_A].dbo.Parameters). Updated ADR item 2 to match.
…eSlot cleanup - SqlPartitionCache runs each cache's query on the shared connection string, qualifying object names with the partition's database through SqlObjectNameFormatter, and disposes the connection itself (QueryAsync). - CacheSlot: GetOrUpdate/GetOrUpdateAsync; loader and refresh-failure callback passed to the constructor. - Log messages rely on the logger category for the cache name. - CacheInitializer: no request-context save/restore (AsyncLocal reverts on return); concrete preload array; uses GetPartitions().Count. - IPartitionManager.GetPartitions returns IReadOnlyCollection; SqlPartitionManager builds it once. - ValueTaskExtensions moved to Microsoft.Health.Fhir.Core.Extensions. - Partition cache integration tests skip when the server doesn't allow cross-database queries. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>


Description
First step of ADR 2611 (phase 1a): the cache framework, implemented as the ADR describes, plus a few real consumers. The remaining caches will move in separate, smaller PRs once the approach is agreed.
Framework (Core)
GlobalCache<T>: one value per process (built-in / FHIR-service data).PartitionCache<T>: one value per partition, keyed by partition ID (nullwhen partitioning is off).ScopedCache<T>: scoped view that reads the partition fromRequestContext, so callers don't pass it.GetRemoteDataAsync(partitionId, bool async, ct), behindGet()andGetAsync()(Azure SDK pattern). The sync path never blocks on a task; a loader that returns an incomplete task withasync: falsethrows, and that task can never publish a value.TimeProvider; concurrent loads are collapsed; a failed refresh returns the last value and the next read retries (as custom queries do today); a failed first load isn't cached.AddGlobalCache<TCache, T>()/AddPartitionCache<TCache, T>()register a cache and add it to the startup preload.CacheInitializerpreloads global caches once, then for each partition opens a DI scope, sets a background request context with that partition and calls eachScopedCache<T>.GetAsync(). It starts in the background onApplicationStarted(after schema init). Failures are logged and the cache loads on first use.SQL
SqlPartitionCache<T>: base class that runs each cache's query on the shared connection string (one connection pool for all partitions), qualifying object names with the partition's database throughSqlObjectNameFormatter(e.g.[FhirDB_A].dbo.Parameters), like the rest of partition routing. It opens and disposes the connection itself, so a cache supplies only its SQL and how to read a row.IPartitionManager.GetPartitions()added (IReadOnlyCollection), used by the preload.Consumers
CustomQueryCachereplaces the staticCustomQueries. This also fixes a bug: the old code readsys.objectsfrom the default database rather than the partition's. TheCustomQuery_prefix still matches case-insensitively, as before.dbo.Parameters:DatabaseParameterCachereplacesCachedParameterand the static flags inSqlServerSearchServiceandSqlServerFhirDataStore. Search and merge/import load the values once withGetAsync()and pass them down. IDs match case-insensitively, ignoring trailing spaces, as the old SQL lookup did.SqlRetryServicesettings move in 1b.RoleCache(GlobalCache) loads and validatesroles.json;RoleLoaderstill fails startup on an invalid file. For nowRoleLoadercopies the roles intoAuthorizationConfiguration.Roles, so the authorization code is unchanged. In 1b,RoleBasedFhirAuthorizationServicereadsRoleCachedirectly and the copy is removed.The ADR decisions are unchanged; items 2, 3, 4, 6 and 8 gain clarifications, and item 9 and the catalogue rollout table record that phase 1 is split into 1a and 1b.
Related issues
Addresses AB#211098 (cache management), follows AB#210971 (cache catalogue, #6028) and builds on #6017.
Testing
Latest commit:
--filter-namespace ...Features.Caching --filter-namespace ...Features.Security: passed (52/52).dotnet test --project src\Microsoft.Health.Fhir.SqlServer.UnitTests\...: passed (1326/1326).--filter-class *PartitionRequestRoutingTests *SmartClinicalScopesMiddlewareTests *FhirRequestContextMiddlewareTests: passed (341/341).--filter-class *SqlServerPartitionCacheTests *SqlComplexQueryTests *SqlServerCreateStatsTests *SqlServerPartitionRoutingTests: 11 passed, 2 skipped (the existing cross-database routing tests).SqlServerPartitionCacheTestsran cross-database against two partition databases on local SQL Server; it skips itself when the server doesn't allow cross-database queries.Earlier commits:
--filter-class *SqlServerPartitionCacheTests *SqlServerCreateStatsTests *FhirStorageTests *SqlServerFhirDataStoreTests: 64 passed, 2 skipped.*RoleBased*, 22/22) passed.--filter-not-trait DataStore=CosmosDb --filter-not-class *CosmosDb*): 543 passed, 2 failed, 8 skipped. The 2 failures (SqlServerSearchParameterInitializationTests,SqlServerWatchdogTests.DefragBlocking) also fail on the base branch (c8cb885).a.a's database./partition/a/Patientwork; an unknown partition returns 404.FHIR Team Checklist
Semver Change (docs)
Skip (targets
feature/multitenancy)