Cosmos DB: `AnyAsync` throws `CosmosException`
Bug description
Cosmos DB: AsyncAny throws CosmosException.
Your code
using Microsoft.Azure.Cosmos;
using Microsoft.EntityFrameworkCore;
using static System.Console;
using var db = new BloggingContext();
try
{
// This line throws
await db.Blogs.AnyAsync();
}
catch (CosmosException ex)
{
WriteLine(ex);
}
class BloggingContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
var connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING");
options.UseCosmos(connectionString, "Test");
}
public DbSet<Blog> Blogs { get; set; }
}
class Blog
{
public int Id { get; set; }
}
Stack traces
Microsoft.Azure.Cosmos.CosmosException : Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: ; Reason: (Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: ; Reason: ({"errors":[{"severity":"Error","location":{"start":46,"end":50},"code":"SC2001","message":"Identifier 'root' could not be resolved."}]}););
---> Microsoft.Azure.Cosmos.Query.Core.Exceptions.ExpectedQueryPartitionProviderException: {"errors":[{"severity":"Error","location":{"start":46,"end":50},"code":"SC2001","message":"Identifier 'root' could not be resolved."}]}
---> System.Runtime.InteropServices.COMException (0x800A0B00): 0x800A0B00
2
--- End of inner exception stack trace ---
at Microsoft.Azure.Cosmos.Query.Core.QueryPlan.QueryPartitionProvider.TryGetPartitionedQueryExecutionInfo(String querySpecJsonString, PartitionKeyDefinition partitionKeyDefinition, VectorEmbeddingPolicy vectorEmbeddingPolicy, Boolean requireFormattableOrderByQuery, Boolean isContinuationExpected, Boolean allowNonValueAggregateQuery, Boolean hasLogicalPartitionKey, Boolean allowDCount, Boolean useSystemPrefix, Boolean hybridSearchSkipOrderByRewrite, GeospatialType geospatialType)
at Microsoft.Azure.Cosmos.CosmosQueryClientCore.TryGetPartitionedQueryExecutionInfoAsync(SqlQuerySpec sqlQuerySpec, ResourceType resourceType, PartitionKeyDefinition partitionKeyDefinition, VectorEmbeddingPolicy vectorEmbeddingPolicy, Boolean requireFormattableOrderByQuery, Boolean isContinuationExpected, Boolean allowNonValueAggregateQuery, Boolean hasLogicalPartitionKey, Boolean allowDCount, Boolean useSystemPrefix, Boolean isHybridSearchQueryPlanOptimizationDisabled, GeospatialType geospatialType, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Azure.Cosmos.CosmosQueryClientCore.TryGetPartitionedQueryExecutionInfoAsync(SqlQuerySpec sqlQuerySpec, ResourceType resourceType, PartitionKeyDefinition partitionKeyDefinition, VectorEmbeddingPolicy vectorEmbeddingPolicy, Boolean requireFormattableOrderByQuery, Boolean isContinuationExpected, Boolean allowNonValueAggregateQuery, Boolean hasLogicalPartitionKey, Boolean allowDCount, Boolean useSystemPrefix, Boolean isHybridSearchQueryPlanOptimizationDisabled, GeospatialType geospatialType, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.Query.Core.QueryPlan.QueryPlanHandler.TryGetQueryInfoAsync(SqlQuerySpec sqlQuerySpec, ResourceType resourceType, PartitionKeyDefinition partitionKeyDefinition, VectorEmbeddingPolicy vectorEmbeddingPolicy, Boolean hasLogicalPartitionKey, Boolean useSystemPrefix, Boolean isHybridSearchQueryPlanOptimizationDisabled, GeospatialType geospatialType, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.Query.Core.QueryPlan.QueryPlanHandler.TryGetQueryPlanAsync(SqlQuerySpec sqlQuerySpec, ResourceType resourceType, PartitionKeyDefinition partitionKeyDefinition, VectorEmbeddingPolicy vectorEmbeddingPolicy, Boolean hasLogicalPartitionKey, Boolean useSystemPrefix, Boolean isHybridSearchQueryPlanOptimizationDisabled, GeospatialType geospatialType, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Azure.Cosmos.Query.Core.QueryPlan.QueryPlanHandler.TryGetQueryPlanAsync(SqlQuerySpec sqlQuerySpec, ResourceType resourceType, PartitionKeyDefinition partitionKeyDefinition, VectorEmbeddingPolicy vectorEmbeddingPolicy, Boolean hasLogicalPartitionKey, Boolean useSystemPrefix, Boolean isHybridSearchQueryPlanOptimizationDisabled, GeospatialType geospatialType, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.Query.Core.QueryPlan.QueryPlanRetriever.GetQueryPlanWithServiceInteropAsync(CosmosQueryClient queryClient, SqlQuerySpec sqlQuerySpec, ResourceType resourceType, PartitionKeyDefinition partitionKeyDefinition, VectorEmbeddingPolicy vectorEmbeddingPolicy, Boolean hasLogicalPartitionKey, GeospatialType geospatialType, Boolean useSystemPrefix, Boolean isHybridSearchQueryPlanOptimizationDisabled, ITrace trace, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Azure.Cosmos.Query.Core.QueryPlan.QueryPlanRetriever.GetQueryPlanWithServiceInteropAsync(CosmosQueryClient queryClient, SqlQuerySpec sqlQuerySpec, ResourceType resourceType, PartitionKeyDefinition partitionKeyDefinition, VectorEmbeddingPolicy vectorEmbeddingPolicy, Boolean hasLogicalPartitionKey, GeospatialType geospatialType, Boolean useSystemPrefix, Boolean isHybridSearchQueryPlanOptimizationDisabled, ITrace trace, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.Query.Core.ExecutionContext.CosmosQueryExecutionContextFactory.GetPartitionedQueryExecutionInfoAsync(CosmosQueryContext cosmosQueryContext, InputParameters inputParameters, ContainerQueryProperties containerQueryProperties, ITrace trace, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Azure.Cosmos.Query.Core.ExecutionContext.CosmosQueryExecutionContextFactory.GetPartitionedQueryExecutionInfoAsync(CosmosQueryContext cosmosQueryContext, InputParameters inputParameters, ContainerQueryProperties containerQueryProperties, ITrace trace, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.Query.Core.ExecutionContext.CosmosQueryExecutionContextFactory.TryCreateCoreContextAsync(DocumentContainer documentContainer, CosmosQueryContext cosmosQueryContext, InputParameters inputParameters, ITrace trace, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.ExecutionContextCallback(Object s)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext(Thread threadPoolThread)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.<>c.<OutputWaitEtwEvents>b__12_0(Action innerContinuation, Task innerTask)
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(Action action, Boolean allowInlining)
at System.Threading.Tasks.Task.RunContinuations(Object continuationObject)
at System.Threading.Tasks.Task`1.TrySetResult(TResult result)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetExistingTaskResult(Task`1 task, TResult result)
at Microsoft.Azure.Cosmos.Query.Core.ExecutionContext.CosmosQueryExecutionContextFactory.TryGetTargetRangeOptimisticDirectExecutionAsync(InputParameters inputParameters, PartitionedQueryExecutionInfo partitionedQueryExecutionInfo, CosmosQueryContext cosmosQueryContext, ContainerQueryProperties containerQueryProperties, ITrace trace)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.ExecutionContextCallback(Object s)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext(Thread threadPoolThread)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.<>c.<OutputWaitEtwEvents>b__12_0(Action innerContinuation, Task innerTask)
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(Action action, Boolean allowInlining)
at System.Threading.Tasks.Task.RunContinuations(Object continuationObject)
at System.Threading.Tasks.Task`1.TrySetResult(TResult result)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetExistingTaskResult(Task`1 task, TResult result)
at Microsoft.Azure.Cosmos.CosmosQueryClientCore.GetClientDisableOptimisticDirectExecutionAsync()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.ExecutionContextCallback(Object s)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext(Thread threadPoolThread)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.<>c.<OutputWaitEtwEvents>b__12_0(Action innerContinuation, Task innerTask)
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(Action action, Boolean allowInlining)
at System.Threading.Tasks.Task.RunContinuations(Object continuationObject)
at System.Threading.Tasks.Task`1.TrySetResult(TResult result)
at System.Threading.Tasks.UnwrapPromise`1.TrySetFromTask(Task task, Boolean lookForOce)
at System.Threading.Tasks.UnwrapPromise`1.ProcessInnerTask(Task task)
at System.Threading.Tasks.Task.RunContinuations(Object continuationObject)
at System.Threading.Tasks.Task.FinishSlow(Boolean userDelegateExecute)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
at System.Threading.Thread.StartCallback()
Verbose output
EF Core version
10.0.7
Database provider
Microsoft.EntityFrameworkCore.Cosmos
Target framework
.NET 10.0
Operating system
Windows 11
IDE
No response
Can use (await db.Blogs.CountAsync()) > 0 as a workaround.
await db.Blogs.Select(x => true).FirstOrDefault() is the best workaround we found.
AI Triage
The below is an AI-generated analysis and may contain inaccuracies.
I can reproduce this against the Windows Cosmos Emulator on https://localhost:8081 with EF Core 10.0.7.
AnyAsync() is translated to:
SELECT VALUE EXISTS (
SELECT 1
FROM root c)
The Cosmos SDK then fails during query plan creation with the reported SC2001 error:
Identifier 'root' could not be resolved.
I also checked EF Core 10.0.6 and 9.0.10 with the same repro, and they fail the same way, so this does not appear to be a regression from 10.0.6 to 10.0.7. I also confirmed the two workarounds mentioned above: (await db.Blogs.CountAsync()) > 0 translates to SELECT VALUE COUNT(1) FROM root c, and await db.Blogs.Select(_ => true).FirstOrDefaultAsync() translates to SELECT VALUE true FROM root c OFFSET 0 LIMIT 1; both executed successfully in my repro.
This looks like a duplicate of https://github.com/dotnet/efcore/issues/33854, which tracks support for top-level Any() in the Cosmos provider and calls out the same invalid top-level EXISTS translation shape.
minimal repro
using Microsoft.Azure.Cosmos;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
await using var db = new BloggingContext();
await db.Database.EnsureCreatedAsync();
await db.Blogs.AnyAsync();
class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options
.UseCosmos(
Emulator.ConnectionString,
"Issue38232",
cosmosOptions => cosmosOptions
.HttpClientFactory(() => new HttpClient(Emulator.Handler, disposeHandler: false))
.ConnectionMode(ConnectionMode.Gateway))
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();
}
static class Emulator
{
public const string ConnectionString =
"AccountEndpoint=https://localhost:8081;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
public static readonly HttpClientHandler Handler = new()
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};
}
class Blog
{
public int Id { get; set; }
}