Skip to content

Commit 438fa7f

Browse files
Aniruddh25Copilotsouvikghosh04Copilot
authored
Fix source-specific response cache eligibility (#3923)
## Why make this change? - Response-cache eligibility checked the default data source's session-context setting instead of the queried source. In multi-source configurations, a child SQL source using session-context row-level security could consequently reuse another caller's cached response. ## What is this change? - Add source-aware cache eligibility while retaining the default-source API. - Bypass response-cache reads and writes for queried MSSQL/DWSQL sources with `set-session-context` enabled, including stored procedures and cache-control paths. - Pass the actual source name through SQL and Cosmos query engines, preserving caching for eligible child sources. - Compute effective runtime cache telemetry across loaded sources and effective entity cache telemetry using each entity's source. - Add regression tests and update [query-caching documentation](https://github.com/Azure/data-api-builder/blob/177eca3e899f6f8ffc28f4fbcab9093c08145b9d/docs/design/query-caching.md) and [cache telemetry documentation](https://github.com/Azure/data-api-builder/blob/177eca3e899f6f8ffc28f4fbcab9093c08145b9d/docs/testing-guide/engine-telemetry.md). ## How was this tested? - [ ] Integration Tests - [x] Unit Tests - Targeted suite: **154 passed, 0 failed, 0 skipped** across `SourceAwareCacheTests`, `DabCacheServiceIntegrationTests`, `RuntimeConfigHelperTests`, and `EngineTelemetrySnapshotTests`. - Regression cases exercise the public SQL query-engine APIs with real FusionCache and synthetic database responses: a preexisting cached response is bypassed after enabling session context, Bob/anonymous receive their own synthetic results, and protected-source reads do not overwrite the old cache entry. - Cover MSSQL/DWSQL, stored procedures, default reads, `no-store`, `no-cache`, `only-if-cached`, source-option updates, global cache disablement, eligible child caching, and source-aware telemetry. - Focused `dotnet format --verify-no-changes` and `git diff --check` passed. ## Sample Request(s) For an authorized read against an entity on a child MSSQL/DWSQL source with `set-session-context: true`: ```http GET /api/Notes ``` The request must reach the database for each caller rather than reuse another caller's cached result. The same source-specific bypass applies to the cache-control variants, for example: ```http GET /api/Notes Cache-Control: no-store ``` Caching remains available for an eligible child source even when session context is enabled on the default source. No CLI changes. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Souvik Ghosh <souvikofficial04@gmail.com> Co-authored-by: souvikghosh04 <210500244+souvikghosh04@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent 3243510 commit 438fa7f

12 files changed

Lines changed: 351 additions & 21 deletions

‎docs/design/query-caching.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
## Why cache?
32

43
Reduce the number of round-trip requests between Data API builder (DAB) and the configured back-end database. Reducing the number of round-trip requests results in the end-user experiencing quicker response times.
@@ -96,6 +95,14 @@ __Data returned by the database is received over the same TLS connection establi
9695

9796
### Access token metadata usage
9897

98+
Response caching is disabled for an MSSQL or DWSQL data source when its
99+
`set-session-context` option is enabled. This check uses the data source being
100+
queried, including sources loaded through `data-source-files`, not the default
101+
source's options. Both cache reads and writes are bypassed, including
102+
cache-control paths and stored-procedure reads, so database row-level security
103+
evaluates each caller's session context. Other eligible data sources can still
104+
use caching.
105+
99106
__Cache entries will not be created for database query text generated from database policies.__ This is because database policies directly affect values set within SQL Server's `-set-session-context` variables and is an implementation detail of database specific query executors. The caching service will be implemented independent of and before execution of query executor code.
100107

101108
Access tokens directly influence how database policies are resolved. Access tokens are also short lived and token contents used to generate a SQL query may change from token to token. This adds an additional burden to the developer to remember to configure their cache entry `ttl` to properly align with access token expiration. We can't know how frequently token contents may change. Cache entries created from token contents are specific to individual users. We should aim to prevent the cache from favoring specific users because we can then avoid have individual users flood the cache for themselves.

‎docs/testing-guide/engine-telemetry.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,12 @@ Configuration events contain `dab_snapshot_schema=configuration-v1`, `dab_config
142142

143143
Where applicable, `.configured` and `.effective` are separate. States are `enabled`, `disabled`, `missing`, `unsupported`, `unknown` and `not_applicable`. Original-input presence is captured as fixed-size, value-free metadata only during loads authorized by an enabled engine session, including nested source files. Ambient test mode alone does not enable capture in a CLI or disabled embedded host. Lost provenance is not reconstructed by serializing defaults. No customer entity/role names or values are retained in that metadata. Unsupported capabilities remain unsupported even when there are zero entities.
144144

145+
Cache `.effective` states account for source-specific eligibility. Runtime cache
146+
is effective when at least one loaded data source permits response caching; entity
147+
cache is effective only when caching is enabled for that entity and its own data
148+
source permits caching. An MSSQL or DWSQL source with `set-session-context` enabled
149+
does not permit response-cache reads or writes.
150+
145151
## Events and usage
146152

147153
Events are `dab/engine.process_started`, `ready`, `startup_failed`, `configuration_changed`, `configuration_change_failed`, `first_request_served`, `first_successful_request`, `heartbeat`, `usage_summary` and `stopped`, all under the `dab/engine.` prefix.

‎src/Config/ObjectModel/RuntimeConfig.cs‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -677,14 +677,25 @@ public virtual int GlobalCacheEntryTtl()
677677
}
678678

679679
/// <summary>
680-
/// Whether the caching service should be used for a given operation. This is determined by
681-
/// - whether caching is enabled globally
682-
/// - whether the datasource is SQL and session context is disabled.
680+
/// Whether response caching is allowed for the default data source.
683681
/// </summary>
684682
/// <returns>Whether cache operations should proceed.</returns>
685683
public virtual bool CanUseCache()
686684
{
687-
bool setSessionContextEnabled = DataSource?.GetTypedOptions<MsSqlOptions>()?.SetSessionContext ?? true;
685+
return DataSource is not null && CanUseCache(DefaultDataSourceName);
686+
}
687+
688+
/// <summary>
689+
/// Whether response caching is allowed for the queried data source.
690+
/// Session-context queries must reach the database so row-level security runs for each caller.
691+
/// </summary>
692+
/// <param name="dataSourceName">Name of the data source being queried.</param>
693+
/// <returns>Whether cache reads and writes are allowed.</returns>
694+
public virtual bool CanUseCache(string dataSourceName)
695+
{
696+
DataSource dataSource = GetDataSourceFromDataSourceName(dataSourceName);
697+
bool setSessionContextEnabled = dataSource.DatabaseType is DatabaseType.MSSQL or DatabaseType.DWSQL
698+
&& dataSource.GetTypedOptions<MsSqlOptions>()?.SetSessionContext is true;
688699
return IsCachingEnabled && !setSessionContextEnabled;
689700
}
690701

‎src/Core/Resolvers/CosmosQueryEngine.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ public async Task<Tuple<JsonDocument, IMetadata>> ExecuteAsync(
9292

9393
JObject executeQueryResult = null;
9494

95-
if (runtimeConfig.CanUseCache() && runtimeConfig.IsEntityCachingEnabled(structure.EntityName))
95+
if (runtimeConfig.CanUseCache(dataSourceName) && runtimeConfig.IsEntityCachingEnabled(structure.EntityName))
9696
{
9797
StringBuilder dataSourceKey = new(dataSourceName);
9898

‎src/Core/Resolvers/SqlQueryEngine.cs‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -325,8 +325,7 @@ public object ResolveList(JsonElement array, ObjectField fieldSchema, ref IMetad
325325
queryString = queryBuilder.Build(structure);
326326
}
327327

328-
// Global Cache enablement check
329-
if (runtimeConfig.CanUseCache())
328+
if (runtimeConfig.CanUseCache(dataSourceName))
330329
{
331330
// Entity level cache behavior checks
332331
bool dbPolicyConfigured = !string.IsNullOrEmpty(structure.DbPolicyPredicatesForOperations[EntityActionOperation.Read]);
@@ -468,10 +467,7 @@ public object ResolveList(JsonElement array, ObjectField fieldSchema, ref IMetad
468467
IQueryExecutor queryExecutor = _queryFactory.GetQueryExecutor(databaseType);
469468
string queryString = queryBuilder.Build(structure);
470469

471-
// Only proceed to use caching code when
472-
// RuntimeConfig.Cache.Enabled is true
473-
// RuntimeConfig.DataSource.Options.SetSessionContext is false
474-
if (runtimeConfig.CanUseCache())
470+
if (runtimeConfig.CanUseCache(dataSourceName))
475471
{
476472
// Entity level cache behavior checks
477473
bool entityCacheEnabled = runtimeConfig.IsEntityCachingEnabled(structure.EntityName);

‎src/Core/Telemetry/Product/CliTelemetryConfigurationSnapshot.cs‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Diagnostics.CodeAnalysis;
66
using System.Text.Json;
77
using Azure.DataApiBuilder.Config.ObjectModel;
8+
using Azure.DataApiBuilder.Service.Exceptions;
89

910
namespace Azure.DataApiBuilder.Core.Telemetry.Product
1011
{
@@ -229,11 +230,21 @@ internal Prepared Prepare(RuntimeConfig original, int depth)
229230

230231
Dictionary<string, Entity> originalEntities = new(StringComparer.Ordinal);
231232
Dictionary<string, Entity> entities = new(StringComparer.Ordinal);
233+
Dictionary<string, string> entityToDataSource = new(StringComparer.Ordinal);
232234
foreach ((string name, Entity entity) in original.Entities)
233235
{
234236
Consume(ref _modelNodes);
235237
Require(entity is not null && entity.Source is not null);
236238
originalEntities.Add(name, entity);
239+
try
240+
{
241+
entityToDataSource.Add(name, original.GetDataSourceNameFromEntityName(name));
242+
}
243+
catch (DataApiBuilderException)
244+
{
245+
// Source mapping is optional when effective caching is unavailable.
246+
}
247+
237248
entities.Add(name, new Entity(
238249
new EntitySource(string.Empty, entity.Source.Type, null, null),
239250
new EntityGraphQLOptions(string.Empty, string.Empty, entity.IsGraphQLEnabled), null,
@@ -256,7 +267,7 @@ internal Prepared Prepare(RuntimeConfig original, int depth)
256267
DataSourceFiles? files = original.DataSourceFiles is null ? null
257268
: new(original.DataSourceFiles.SourceFiles is null ? null : children.Select(child => child.FileName).ToArray());
258269
RuntimeConfig bounded = new(string.Empty, source!, original.Runtime!, boundedEntities, defaultName,
259-
sources, new Dictionary<string, string>(), files, original.AzureKeyVault, new RuntimeAutoentities(autoentities))
270+
sources, entityToDataSource, files, original.AzureKeyVault, new RuntimeAutoentities(autoentities))
260271
{
261272
TelemetryPresence = original.TelemetryPresence,
262273
IsChildConfig = original.IsChildConfig

‎src/Core/Telemetry/Product/EngineTelemetryConfigurationSnapshot.cs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ public static ImmutableDictionary<string, string> Create(RuntimeConfig config, J
5050
RuntimeOptions? runtime = config.Runtime;
5151
RuntimeCacheOptions? cache = runtime?.Cache;
5252
EmbeddingsOptions? embeddings = runtime?.Embeddings;
53-
bool canUseCache = config.CanUseCache();
53+
bool canUseCache = config.GetDataSourceNamesToDataSourcesIterator()
54+
.Any(source => config.CanUseCache(source.Key));
5455

5556
result.Add("snapshot_schema", "configuration-v1");
5657
Add(result, "runtime.rest",
@@ -71,7 +72,7 @@ public static ImmutableDictionary<string, string> Create(RuntimeConfig config, J
7172
State(canUseCache));
7273

7374
// Startup installs L2 only under the runtime cache gate; query engines additionally
74-
// require CanUseCache(), including its session-context rule. No Redis probe is made.
75+
// require source-specific cache eligibility. No Redis probe is made.
7576
Add(result, "runtime.cache.l2",
7677
Configured(runtimeInput.Child("cache").Child("level-2").Child("enabled"),
7778
State(cache?.Level2?.Enabled), NullableSetting(cache?.Level2?.Enabled)),
@@ -268,7 +269,8 @@ private static void AddEntities(ImmutableDictionary<string, string>.Builder resu
268269
[
269270
("entities.any.cache", EntityFeature.Cache,
270271
(_, entity, raw) => Configured(raw.Child("cache").Child("enabled"), State(entity.Cache?.Enabled), Provided(entity.Cache?.Enabled, entity.Cache?.UserProvidedEnabledOptions == true)),
271-
(name, _) => State(canUseCache && config.IsEntityCachingEnabled(name))),
272+
(name, _) => State(canUseCache && config.IsEntityCachingEnabled(name)
273+
&& config.CanUseCache(config.GetDataSourceNameFromEntityName(name)))),
272274
("entities.any.rest", EntityFeature.Rest,
273275
(_, entity, raw) => Configured(raw.Child("rest").Enablement(allowString: true), State(entity.IsRestEnabled), UNKNOWN),
274276
(_, entity) => State(config.IsRestEnabled && entity.IsRestEnabled)),

‎src/Service.Tests/Caching/DabCacheServiceIntegrationTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,7 @@ private static Mock<RuntimeConfigProvider> CreateMockRuntimeConfigProvider(strin
788788
.Setup(c => c.Entities)
789789
.Returns(entities);
790790
mockRuntimeConfig
791-
.Setup(c => c.CanUseCache())
791+
.Setup(c => c.CanUseCache(It.IsAny<string>()))
792792
.Returns(true);
793793
mockRuntimeConfig
794794
.Setup(c => c.GetEntityCacheEntryTtl(It.IsAny<string>()))

0 commit comments

Comments
 (0)