Skip to content

Partition cache framework with first cache consumers - #6097

Open
apurvabhaleMS wants to merge 7 commits into
feature/multitenancyfrom
personal/apurvabhale/partition-cache
Open

apurvabhaleMS wants to merge 7 commits into
feature/multitenancyfrom
personal/apurvabhale/partition-cache

Conversation

@apurvabhaleMS

@apurvabhaleMS apurvabhaleMS commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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 (null when partitioning is off).
  • ScopedCache<T>: scoped view that reads the partition from RequestContext, so callers don't pass it.
  • Both caches share one loader, GetRemoteDataAsync(partitionId, bool async, ct), behind Get() and GetAsync() (Azure SDK pattern). The sync path never blocks on a task; a loader that returns an incomplete task with async: false throws, and that task can never publish a value.
  • Behavior: expiry via 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.
  • CacheInitializer preloads global caches once, then for each partition opens a DI scope, sets a background request context with that partition and calls each ScopedCache<T>.GetAsync(). It starts in the background on ApplicationStarted (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 through SqlObjectNameFormatter (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

  • Create deployment template with instructions #13 custom query procedures: CustomQueryCache replaces the static CustomQueries. This also fixes a bug: the old code read sys.objects from the default database rather than the partition's. The CustomQuery_ prefix still matches case-insensitively, as before.
  • Naming of Authorization Parameters. #15 dbo.Parameters: DatabaseParameterCache replaces CachedParameter and the static flags in SqlServerSearchService and SqlServerFhirDataStore. Search and merge/import load the values once with GetAsync() and pass them down. IDs match case-insensitively, ignoring trailing spaces, as the old SQL lookup did. SqlRetryService settings move in 1b.
  • Changes Func<IDocumentClient> to IScoped<IDocumentClient> #3 roles: RoleCache (GlobalCache) loads and validates roles.json; RoleLoader still fails startup on an invalid file. For now RoleLoader copies the roles into AuthorizationConfiguration.Roles, so the authorization code is unchanged. In 1b, RoleBasedFhirAuthorizationService reads RoleCache directly 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:

  • Core unit tests, --filter-namespace ...Features.Caching --filter-namespace ...Features.Security: passed (52/52).
  • dotnet test --project src\Microsoft.Health.Fhir.SqlServer.UnitTests\...: passed (1326/1326).
  • R4 Api unit tests, --filter-class *PartitionRequestRoutingTests *SmartClinicalScopesMiddlewareTests *FhirRequestContextMiddlewareTests: passed (341/341).
  • R4 SQL integration, --filter-class *SqlServerPartitionCacheTests *SqlComplexQueryTests *SqlServerCreateStatsTests *SqlServerPartitionRoutingTests: 11 passed, 2 skipped (the existing cross-database routing tests). SqlServerPartitionCacheTests ran cross-database against two partition databases on local SQL Server; it skips itself when the server doesn't allow cross-database queries.

Earlier commits:

  • e1a9bc3: R4 SQL integration, --filter-class *SqlServerPartitionCacheTests *SqlServerCreateStatsTests *FhirStorageTests *SqlServerFhirDataStoreTests: 64 passed, 2 skipped.
  • 3d2a357: R4 Core unit tests (*RoleBased*, 22/22) passed.
  • 3d2a357: Full R4 SQL integration (Release, --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).
  • 3d2a357: Manual run of the R4 web server over https with partition a.
    • Before any request, SQL query stats show both preload queries ran against partition a's database.
    • Create and search on /partition/a/Patient work; an unknown partition returns 404.

FHIR Team Checklist

  • Update the title of the PR to be succinct and less than 65 characters
  • Add a milestone to the PR for the sprint that it is merged (i.e. add S47)
  • Tag the PR with the type of update: Bug, Build, Dependencies, Enhancement, New-Feature or Documentation
  • Tag the PR with Open source, Azure API for FHIR (CosmosDB or common code) or Azure Healthcare APIs (SQL or common code) to specify where this change is intended to be released.
  • Tag the PR with Schema Version backward compatible or Schema Version backward incompatible or Schema Version unchanged if this adds or updates Sql script which is/is not backward compatible with the code.
  • When changing or adding behavior, if your code modifies the system design or changes design assumptions, please create and include an ADR.
  • CI is green before merge Build Status
  • Review squash-merge requirements

Semver Change (docs)

Skip (targets feature/multitenancy)

apurvabhaleMS and others added 3 commits November 24, 2026 09:45
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>
@apurvabhaleMS apurvabhaleMS added Enhancement Enhancement on existing functionality. Azure Healthcare APIs Label denotes that the issue or PR is relevant to the FHIR service in the Azure Healthcare APIs Schema Version unchanged ADR-Included ADR Included in the PR labels Nov 24, 2026
@apurvabhaleMS
apurvabhaleMS requested a balanced review from Copilot November 24, 2026 19:55

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

apurvabhaleMS and others added 2 commits November 24, 2026 12:25
- 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-commenter

Codecov Comments Bot (codecov-commenter) commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (feature/multitenancy@c8cb885). Learn more about missing BASE report.

Additional details and impacted files

Impacted file tree graph

@@                   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:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

{
string database = GetDatabase(partitionId);
SqlConnection connection = async
? await _connectionBuilder.GetSqlConnectionAsync(database, cancellationToken: cancellationToken)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@apurvabhaleMS
apurvabhaleMS marked this pull request as ready for review November 25, 2026 07:03
@apurvabhaleMS
apurvabhaleMS requested a review from a team as a code owner November 25, 2026 07:03
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ADR-Included ADR Included in the PR Azure Healthcare APIs Label denotes that the issue or PR is relevant to the FHIR service in the Azure Healthcare APIs Enhancement Enhancement on existing functionality. Schema Version unchanged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants