/
CosmosQueryExecutionContextFactory.cs
1113 lines (1000 loc) · 54.7 KB
/
CosmosQueryExecutionContextFactory.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Query.Core.ExecutionContext
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.CosmosElements;
using Microsoft.Azure.Cosmos.Pagination;
using Microsoft.Azure.Cosmos.Query.Core;
using Microsoft.Azure.Cosmos.Query.Core.Exceptions;
using Microsoft.Azure.Cosmos.Query.Core.Monads;
using Microsoft.Azure.Cosmos.Query.Core.Parser;
using Microsoft.Azure.Cosmos.Query.Core.Pipeline;
using Microsoft.Azure.Cosmos.Query.Core.Pipeline.CrossPartition.Parallel;
using Microsoft.Azure.Cosmos.Query.Core.Pipeline.OptimisticDirectExecutionQuery;
using Microsoft.Azure.Cosmos.Query.Core.Pipeline.Pagination;
using Microsoft.Azure.Cosmos.Query.Core.Pipeline.Tokens;
using Microsoft.Azure.Cosmos.Query.Core.QueryClient;
using Microsoft.Azure.Cosmos.Query.Core.QueryPlan;
using Microsoft.Azure.Cosmos.SqlObjects;
using Microsoft.Azure.Cosmos.SqlObjects.Visitors;
using Microsoft.Azure.Cosmos.Tracing;
using Microsoft.Azure.Documents.Routing;
internal static class CosmosQueryExecutionContextFactory
{
internal const string ClientDisableOptimisticDirectExecution = "clientDisableOptimisticDirectExecution";
private const string InternalPartitionKeyDefinitionProperty = "x-ms-query-partitionkey-definition";
private const string QueryInspectionPattern = @"\s*(GROUP\s+BY\s+|COUNT\s*\(|MIN\s*\(|MAX\s*\(|AVG\s*\(|SUM\s*\(|DISTINCT\s+)";
private const string OptimisticDirectExecution = "OptimisticDirectExecution";
private const string Passthrough = "Passthrough";
private const string Specialized = "Specialized";
private const int PageSizeFactorForTop = 5;
private static readonly Regex QueryInspectionRegex = new Regex(QueryInspectionPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static IQueryPipelineStage Create(
DocumentContainer documentContainer,
CosmosQueryContext cosmosQueryContext,
InputParameters inputParameters,
ITrace trace)
{
if (cosmosQueryContext == null)
{
throw new ArgumentNullException(nameof(cosmosQueryContext));
}
if (inputParameters == null)
{
throw new ArgumentNullException(nameof(inputParameters));
}
if (trace == null)
{
throw new ArgumentNullException(nameof(trace));
}
NameCacheStaleRetryQueryPipelineStage nameCacheStaleRetryQueryPipelineStage = new NameCacheStaleRetryQueryPipelineStage(
cosmosQueryContext: cosmosQueryContext,
queryPipelineStageFactory: () =>
{
// Query Iterator requires that the creation of the query context is deferred until the user calls ReadNextAsync
AsyncLazy<TryCatch<IQueryPipelineStage>> lazyTryCreateStage = new AsyncLazy<TryCatch<IQueryPipelineStage>>(
valueFactory: (trace, innerCancellationToken) => TryCreateCoreContextAsync(
documentContainer,
cosmosQueryContext,
inputParameters,
trace,
innerCancellationToken));
LazyQueryPipelineStage lazyQueryPipelineStage = new LazyQueryPipelineStage(lazyTryCreateStage: lazyTryCreateStage);
return lazyQueryPipelineStage;
});
CatchAllQueryPipelineStage catchAllQueryPipelineStage = new CatchAllQueryPipelineStage(nameCacheStaleRetryQueryPipelineStage);
return catchAllQueryPipelineStage;
}
private static async Task<TryCatch<IQueryPipelineStage>> TryCreateCoreContextAsync(
DocumentContainer documentContainer,
CosmosQueryContext cosmosQueryContext,
InputParameters inputParameters,
ITrace trace,
CancellationToken cancellationToken)
{
// The default
using (ITrace createQueryPipelineTrace = trace.StartChild("Create Query Pipeline", TraceComponent.Query, Tracing.TraceLevel.Info))
{
// Try to parse the continuation token.
CosmosElement continuationToken = inputParameters.InitialUserContinuationToken;
PartitionedQueryExecutionInfo queryPlanFromContinuationToken = inputParameters.PartitionedQueryExecutionInfo;
if (continuationToken != null)
{
if (!PipelineContinuationToken.TryCreateFromCosmosElement(
continuationToken,
out PipelineContinuationToken pipelineContinuationToken))
{
return TryCatch<IQueryPipelineStage>.FromException(
new MalformedContinuationTokenException(
$"Malformed {nameof(PipelineContinuationToken)}: {continuationToken}."));
}
if (PipelineContinuationToken.IsTokenFromTheFuture(pipelineContinuationToken))
{
return TryCatch<IQueryPipelineStage>.FromException(
new MalformedContinuationTokenException(
$"{nameof(PipelineContinuationToken)} Continuation token is from a newer version of the SDK. " +
$"Upgrade the SDK to avoid this issue." +
$"{continuationToken}."));
}
if (!PipelineContinuationToken.TryConvertToLatest(
pipelineContinuationToken,
out PipelineContinuationTokenV1_1 latestVersionPipelineContinuationToken))
{
return TryCatch<IQueryPipelineStage>.FromException(
new MalformedContinuationTokenException(
$"{nameof(PipelineContinuationToken)}: '{continuationToken}' is no longer supported."));
}
continuationToken = latestVersionPipelineContinuationToken.SourceContinuationToken;
if (latestVersionPipelineContinuationToken.QueryPlan != null)
{
queryPlanFromContinuationToken = latestVersionPipelineContinuationToken.QueryPlan;
}
}
CosmosQueryClient cosmosQueryClient = cosmosQueryContext.QueryClient;
ContainerQueryProperties containerQueryProperties = await cosmosQueryClient.GetCachedContainerQueryPropertiesAsync(
cosmosQueryContext.ResourceLink,
inputParameters.PartitionKey,
createQueryPipelineTrace,
cancellationToken);
cosmosQueryContext.ContainerResourceId = containerQueryProperties.ResourceId;
Documents.PartitionKeyRange targetRange = await TryGetTargetRangeOptimisticDirectExecutionAsync(
inputParameters,
queryPlanFromContinuationToken,
cosmosQueryContext,
containerQueryProperties,
trace);
if (targetRange != null)
{
return await TryCreateSinglePartitionExecutionContextAsync(
documentContainer,
partitionedQueryExecutionInfo: null,
cosmosQueryContext,
containerQueryProperties,
inputParameters,
targetRange,
createQueryPipelineTrace,
cancellationToken);
}
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo;
if (queryPlanFromContinuationToken != null)
{
partitionedQueryExecutionInfo = queryPlanFromContinuationToken;
}
else
{
// If the query would go to gateway, but we have a partition key,
// then try seeing if we can execute as a passthrough using client side only logic.
// This is to short circuit the need to go to the gateway to get the query plan.
if (cosmosQueryContext.QueryClient.BypassQueryParsing()
&& inputParameters.PartitionKey.HasValue)
{
bool parsed;
SqlQuery sqlQuery;
using (ITrace queryParseTrace = createQueryPipelineTrace.StartChild("Parse Query", TraceComponent.Query, Tracing.TraceLevel.Info))
{
parsed = SqlQueryParser.TryParse(inputParameters.SqlQuerySpec.QueryText, out sqlQuery);
}
if (parsed)
{
bool hasDistinct = sqlQuery.SelectClause.HasDistinct;
bool hasGroupBy = sqlQuery.GroupByClause != default;
bool hasAggregates = AggregateProjectionDetector.HasAggregate(sqlQuery.SelectClause.SelectSpec);
bool createPassthroughQuery = !hasAggregates && !hasDistinct && !hasGroupBy;
if (createPassthroughQuery)
{
SetTestInjectionPipelineType(inputParameters, Passthrough);
// Only thing that matters is that we target the correct range.
Documents.PartitionKeyDefinition partitionKeyDefinition = GetPartitionKeyDefinition(inputParameters, containerQueryProperties);
List<Documents.PartitionKeyRange> targetRanges = await cosmosQueryContext.QueryClient.GetTargetPartitionKeyRangesAsync(
cosmosQueryContext.ResourceLink,
containerQueryProperties.ResourceId,
containerQueryProperties.EffectiveRangesForPartitionKey,
forceRefresh: false,
createQueryPipelineTrace);
return TryCreatePassthroughQueryExecutionContext(
documentContainer,
inputParameters,
targetRanges,
containerQueryProperties);
}
}
}
partitionedQueryExecutionInfo = await GetPartitionedQueryExecutionInfoAsync(
cosmosQueryContext,
inputParameters,
containerQueryProperties,
createQueryPipelineTrace,
cancellationToken);
}
return await TryCreateFromPartitionedQueryExecutionInfoAsync(
documentContainer,
partitionedQueryExecutionInfo,
containerQueryProperties,
cosmosQueryContext,
inputParameters,
createQueryPipelineTrace,
cancellationToken);
}
}
private static async Task<TryCatch<IQueryPipelineStage>> TryCreateFromPartitionedQueryExecutionInfoAsync(
DocumentContainer documentContainer,
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo,
ContainerQueryProperties containerQueryProperties,
CosmosQueryContext cosmosQueryContext,
InputParameters inputParameters,
ITrace trace,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
List<Documents.PartitionKeyRange> targetRanges = await GetTargetPartitionKeyRangesAsync(
cosmosQueryContext.QueryClient,
cosmosQueryContext.ResourceLink,
partitionedQueryExecutionInfo,
containerQueryProperties,
inputParameters.Properties,
inputParameters.InitialFeedRange,
trace);
TryCatch<IQueryPipelineStage> tryCreatePipelineStage;
Documents.PartitionKeyRange targetRange = await TryGetTargetRangeOptimisticDirectExecutionAsync(
inputParameters,
partitionedQueryExecutionInfo,
cosmosQueryContext,
containerQueryProperties,
trace);
if (targetRange != null)
{
tryCreatePipelineStage = await TryCreateSinglePartitionExecutionContextAsync(
documentContainer,
partitionedQueryExecutionInfo,
cosmosQueryContext,
containerQueryProperties,
inputParameters,
targetRange,
trace,
cancellationToken);
}
else
{
bool singleLogicalPartitionKeyQuery = inputParameters.PartitionKey.HasValue
|| ((partitionedQueryExecutionInfo.QueryRanges.Count == 1)
&& partitionedQueryExecutionInfo.QueryRanges[0].IsSingleValue);
bool serverStreamingQuery = !partitionedQueryExecutionInfo.QueryInfo.HasAggregates
&& !partitionedQueryExecutionInfo.QueryInfo.HasDistinct
&& !partitionedQueryExecutionInfo.QueryInfo.HasGroupBy;
bool streamingSinglePartitionQuery = singleLogicalPartitionKeyQuery && serverStreamingQuery;
bool clientStreamingQuery = serverStreamingQuery
&& !partitionedQueryExecutionInfo.QueryInfo.HasOrderBy
&& !partitionedQueryExecutionInfo.QueryInfo.HasTop
&& !partitionedQueryExecutionInfo.QueryInfo.HasLimit
&& !partitionedQueryExecutionInfo.QueryInfo.HasOffset;
bool streamingCrossContinuationQuery = !singleLogicalPartitionKeyQuery && clientStreamingQuery;
bool createPassthroughQuery = streamingSinglePartitionQuery || streamingCrossContinuationQuery;
if (createPassthroughQuery)
{
SetTestInjectionPipelineType(inputParameters, Passthrough);
tryCreatePipelineStage = TryCreatePassthroughQueryExecutionContext(
documentContainer,
inputParameters,
targetRanges,
containerQueryProperties);
}
else
{
tryCreatePipelineStage = TryCreateSpecializedDocumentQueryExecutionContext(documentContainer, cosmosQueryContext, inputParameters, targetRanges, containerQueryProperties, partitionedQueryExecutionInfo);
}
}
return tryCreatePipelineStage;
}
private static async Task<TryCatch<IQueryPipelineStage>> TryCreateSinglePartitionExecutionContextAsync(
DocumentContainer documentContainer,
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo,
CosmosQueryContext cosmosQueryContext,
ContainerQueryProperties containerQueryProperties,
InputParameters inputParameters,
Documents.PartitionKeyRange targetRange,
ITrace trace,
CancellationToken cancellationToken)
{
// Retrieve the query plan in a subset of cases to ensure the query is valid before creating the Ode pipeline
if (partitionedQueryExecutionInfo == null && QueryInspectionRegex.IsMatch(inputParameters.SqlQuerySpec.QueryText))
{
partitionedQueryExecutionInfo = await GetPartitionedQueryExecutionInfoAsync(
cosmosQueryContext,
inputParameters,
containerQueryProperties,
trace,
cancellationToken);
}
// Test code added to confirm the correct pipeline is being utilized
SetTestInjectionPipelineType(inputParameters, OptimisticDirectExecution);
TryCatch<IQueryPipelineStage> tryCreatePipelineStage = TryCreateOptimisticDirectExecutionContext(
documentContainer,
cosmosQueryContext,
containerQueryProperties,
inputParameters,
targetRange,
cancellationToken);
// A malformed continuation token exception would happen for 2 reasons here
// 1. the token is actually malformed
// 2. Its a non Ode continuation token
// In both cases, Ode pipeline delegates the work to the Specialized pipeline
// as Ode pipeline should not take over execution while some other pipeline is already handling it
if (tryCreatePipelineStage.Failed && tryCreatePipelineStage.InnerMostException is MalformedContinuationTokenException)
{
SetTestInjectionPipelineType(inputParameters, Specialized);
if (partitionedQueryExecutionInfo != null)
{
List<Documents.PartitionKeyRange> targetRanges = new List<Documents.PartitionKeyRange>
{
targetRange
};
tryCreatePipelineStage = TryCreateSpecializedDocumentQueryExecutionContext(
documentContainer,
cosmosQueryContext,
inputParameters,
targetRanges,
containerQueryProperties,
partitionedQueryExecutionInfo);
}
else
{
tryCreatePipelineStage = await TryCreateSpecializedDocumentQueryExecutionContextAsync(
documentContainer,
cosmosQueryContext,
containerQueryProperties,
inputParameters,
trace,
cancellationToken);
}
}
return tryCreatePipelineStage;
}
private static TryCatch<IQueryPipelineStage> TryCreateSpecializedDocumentQueryExecutionContext(
DocumentContainer documentContainer,
CosmosQueryContext cosmosQueryContext,
InputParameters inputParameters,
List<Documents.PartitionKeyRange> targetRanges,
ContainerQueryProperties containerQueryProperties,
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo)
{
SetTestInjectionPipelineType(inputParameters, Specialized);
if (!string.IsNullOrEmpty(partitionedQueryExecutionInfo.QueryInfo.RewrittenQuery))
{
// We need pass down the rewritten query.
SqlQuerySpec rewrittenQuerySpec = new SqlQuerySpec()
{
QueryText = partitionedQueryExecutionInfo.QueryInfo.RewrittenQuery,
Parameters = inputParameters.SqlQuerySpec.Parameters
};
inputParameters = new InputParameters(
rewrittenQuerySpec,
inputParameters.InitialUserContinuationToken,
inputParameters.InitialFeedRange,
inputParameters.MaxConcurrency,
inputParameters.MaxItemCount,
inputParameters.MaxBufferedItemCount,
inputParameters.PartitionKey,
inputParameters.Properties,
inputParameters.PartitionedQueryExecutionInfo,
inputParameters.ExecutionEnvironment,
inputParameters.ReturnResultsInDeterministicOrder,
inputParameters.EnableOptimisticDirectExecution,
inputParameters.IsNonStreamingOrderByQueryFeatureDisabled,
inputParameters.TestInjections);
}
return TryCreateSpecializedDocumentQueryExecutionContext(
documentContainer,
cosmosQueryContext,
inputParameters,
partitionedQueryExecutionInfo,
targetRanges,
containerQueryProperties);
}
private static async Task<TryCatch<IQueryPipelineStage>> TryCreateSpecializedDocumentQueryExecutionContextAsync(
DocumentContainer documentContainer,
CosmosQueryContext cosmosQueryContext,
ContainerQueryProperties containerQueryProperties,
InputParameters inputParameters,
ITrace trace,
CancellationToken cancellationToken)
{
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo = await GetPartitionedQueryExecutionInfoAsync(
cosmosQueryContext,
inputParameters,
containerQueryProperties,
trace,
cancellationToken);
List<Documents.PartitionKeyRange> targetRanges = await GetTargetPartitionKeyRangesAsync(
cosmosQueryContext.QueryClient,
cosmosQueryContext.ResourceLink,
partitionedQueryExecutionInfo,
containerQueryProperties,
inputParameters.Properties,
inputParameters.InitialFeedRange,
trace);
return TryCreateSpecializedDocumentQueryExecutionContext(
documentContainer,
cosmosQueryContext,
inputParameters,
targetRanges,
containerQueryProperties,
partitionedQueryExecutionInfo);
}
private static TryCatch<IQueryPipelineStage> TryCreateOptimisticDirectExecutionContext(
DocumentContainer documentContainer,
CosmosQueryContext cosmosQueryContext,
ContainerQueryProperties containerQueryProperties,
InputParameters inputParameters,
Documents.PartitionKeyRange targetRange,
CancellationToken cancellationToken)
{
// Return a OptimisticDirectExecution context
return OptimisticDirectExecutionQueryPipelineStage.MonadicCreate(
documentContainer: documentContainer,
inputParameters: inputParameters,
targetRange: new FeedRangeEpk(targetRange.ToRange()),
containerQueryProperties: containerQueryProperties,
fallbackQueryPipelineStageFactory: (continuationToken) =>
// In fallback scenario, the Specialized pipeline is always invoked
TryCreateSpecializedDocumentQueryExecutionContextAsync(
documentContainer,
cosmosQueryContext,
containerQueryProperties,
inputParameters.WithContinuationToken(continuationToken),
NoOpTrace.Singleton,
cancellationToken),
cancellationToken: cancellationToken);
}
private static TryCatch<IQueryPipelineStage> TryCreatePassthroughQueryExecutionContext(
DocumentContainer documentContainer,
InputParameters inputParameters,
List<Documents.PartitionKeyRange> targetRanges,
ContainerQueryProperties containerQueryProperties)
{
// Return a parallel context, since we still want to be able to handle splits and concurrency / buffering.
return ParallelCrossPartitionQueryPipelineStage.MonadicCreate(
documentContainer: documentContainer,
sqlQuerySpec: inputParameters.SqlQuerySpec,
targetRanges: targetRanges
.Select(range => new FeedRangeEpk(
new Documents.Routing.Range<string>(
min: range.MinInclusive,
max: range.MaxExclusive,
isMinInclusive: true,
isMaxInclusive: false)))
.ToList(),
queryPaginationOptions: new QueryPaginationOptions(
pageSizeHint: inputParameters.MaxItemCount),
partitionKey: inputParameters.PartitionKey,
containerQueryProperties: containerQueryProperties,
maxConcurrency: inputParameters.MaxConcurrency,
prefetchPolicy: PrefetchPolicy.PrefetchSinglePage,
continuationToken: inputParameters.InitialUserContinuationToken);
}
private static TryCatch<IQueryPipelineStage> TryCreateSpecializedDocumentQueryExecutionContext(
DocumentContainer documentContainer,
CosmosQueryContext cosmosQueryContext,
InputParameters inputParameters,
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo,
List<Documents.PartitionKeyRange> targetRanges,
ContainerQueryProperties containerQueryProperties)
{
QueryInfo queryInfo = partitionedQueryExecutionInfo.QueryInfo;
// We need to compute the optimal initial page size for order-by queries
long optimalPageSize = inputParameters.MaxItemCount;
if (queryInfo.HasOrderBy)
{
int top;
if (queryInfo.HasTop && (partitionedQueryExecutionInfo.QueryInfo.Top.Value > 0))
{
top = partitionedQueryExecutionInfo.QueryInfo.Top.Value;
}
else if (queryInfo.HasLimit && (partitionedQueryExecutionInfo.QueryInfo.Limit.Value > 0))
{
top = (partitionedQueryExecutionInfo.QueryInfo.Offset ?? 0) + partitionedQueryExecutionInfo.QueryInfo.Limit.Value;
}
else
{
top = 0;
}
if (top > 0)
{
// All partitions should initially fetch about 1/nth of the top value.
long pageSizeWithTop = (long)Math.Min(
Math.Ceiling(top / (double)targetRanges.Count) * CosmosQueryExecutionContextFactory.PageSizeFactorForTop,
top);
optimalPageSize = Math.Min(pageSizeWithTop, optimalPageSize);
}
else if (cosmosQueryContext.IsContinuationExpected)
{
optimalPageSize = (long)Math.Min(
Math.Ceiling(optimalPageSize / (double)targetRanges.Count) * CosmosQueryExecutionContextFactory.PageSizeFactorForTop,
optimalPageSize);
}
}
Debug.Assert(
(optimalPageSize > 0) && (optimalPageSize <= int.MaxValue),
$"Invalid MaxItemCount {optimalPageSize}");
return PipelineFactory.MonadicCreate(
executionEnvironment: inputParameters.ExecutionEnvironment,
documentContainer: documentContainer,
sqlQuerySpec: inputParameters.SqlQuerySpec,
targetRanges: targetRanges
.Select(range => new FeedRangeEpk(
new Documents.Routing.Range<string>(
min: range.MinInclusive,
max: range.MaxExclusive,
isMinInclusive: true,
isMaxInclusive: false)))
.ToList(),
partitionKey: inputParameters.PartitionKey,
queryInfo: partitionedQueryExecutionInfo.QueryInfo,
queryPaginationOptions: new QueryPaginationOptions(
pageSizeHint: (int)optimalPageSize),
containerQueryProperties: containerQueryProperties,
maxConcurrency: inputParameters.MaxConcurrency,
requestContinuationToken: inputParameters.InitialUserContinuationToken);
}
private static async Task<PartitionedQueryExecutionInfo> GetPartitionedQueryExecutionInfoAsync(
CosmosQueryContext cosmosQueryContext,
InputParameters inputParameters,
ContainerQueryProperties containerQueryProperties,
ITrace trace,
CancellationToken cancellationToken)
{
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo;
if (cosmosQueryContext.QueryClient.BypassQueryParsing())
{
// For non-Windows platforms(like Linux and OSX) in .NET Core SDK, we cannot use ServiceInterop, so need to bypass in that case.
// We are also now bypassing this for 32 bit host process running even on Windows as there are many 32 bit apps that will not work without this
partitionedQueryExecutionInfo = await QueryPlanRetriever.GetQueryPlanThroughGatewayAsync(
cosmosQueryContext,
inputParameters.SqlQuerySpec,
cosmosQueryContext.ResourceLink,
inputParameters.PartitionKey,
inputParameters.IsNonStreamingOrderByQueryFeatureDisabled,
trace,
cancellationToken);
}
else
{
Documents.PartitionKeyDefinition partitionKeyDefinition = GetPartitionKeyDefinition(inputParameters, containerQueryProperties);
partitionedQueryExecutionInfo = await QueryPlanRetriever.GetQueryPlanWithServiceInteropAsync(
cosmosQueryContext.QueryClient,
inputParameters.SqlQuerySpec,
cosmosQueryContext.ResourceTypeEnum,
partitionKeyDefinition,
inputParameters.PartitionKey != null,
containerQueryProperties.GeospatialType,
cosmosQueryContext.UseSystemPrefix,
trace,
cancellationToken);
}
return partitionedQueryExecutionInfo;
}
/// <summary>
/// Gets the list of partition key ranges.
/// 1. Check partition key range id
/// 2. Check Partition key
/// 3. Check the effective partition key
/// 4. Get the range from the FeedToken
/// 5. Get the range from the PartitionedQueryExecutionInfo
/// </summary>
internal static async Task<List<Documents.PartitionKeyRange>> GetTargetPartitionKeyRangesAsync(
CosmosQueryClient queryClient,
string resourceLink,
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo,
ContainerQueryProperties containerQueryProperties,
IReadOnlyDictionary<string, object> properties,
FeedRangeInternal feedRangeInternal,
ITrace trace)
{
List<Documents.PartitionKeyRange> targetRanges;
if (containerQueryProperties.EffectiveRangesForPartitionKey != null)
{
targetRanges = await queryClient.GetTargetPartitionKeyRangesAsync(
resourceLink,
containerQueryProperties.ResourceId,
containerQueryProperties.EffectiveRangesForPartitionKey,
forceRefresh: false,
trace);
}
else if (TryGetEpkProperty(properties, out string effectivePartitionKeyString))
{
//Note that here we have no way to consume the EPK string as there is no way to convert
//the string to the partition key type to evaulate the number of components which needs to be done for the
//multihahs methods/classes. This is particually important for queries with prefix partition key.
//the EPK sting header is only for internal use but this needs to be fixed in the future.
List<Range<string>> effectiveRanges = new List<Range<string>>
{ Range<string>.GetPointRange(effectivePartitionKeyString) };
targetRanges = await queryClient.GetTargetPartitionKeyRangesAsync(
resourceLink,
containerQueryProperties.ResourceId,
effectiveRanges,
forceRefresh: false,
trace);
}
else if (feedRangeInternal != null)
{
targetRanges = await queryClient.GetTargetPartitionKeyRangeByFeedRangeAsync(
resourceLink,
containerQueryProperties.ResourceId,
containerQueryProperties.PartitionKeyDefinition,
feedRangeInternal,
forceRefresh: false,
trace);
}
else
{
targetRanges = await queryClient.GetTargetPartitionKeyRangesAsync(
resourceLink,
containerQueryProperties.ResourceId,
partitionedQueryExecutionInfo.QueryRanges,
forceRefresh: false,
trace);
}
return targetRanges;
}
private static bool TryGetEpkProperty(
IReadOnlyDictionary<string, object> properties,
out string effectivePartitionKeyString)
{
if (properties != null
&& properties.TryGetValue(
Documents.WFConstants.BackendHeaders.EffectivePartitionKeyString,
out object effectivePartitionKeyStringObject))
{
effectivePartitionKeyString = effectivePartitionKeyStringObject as string;
if (string.IsNullOrEmpty(effectivePartitionKeyString))
{
throw new ArgumentOutOfRangeException(nameof(effectivePartitionKeyString));
}
return true;
}
effectivePartitionKeyString = null;
return false;
}
private static void SetTestInjectionPipelineType(InputParameters inputParameters, string pipelineType)
{
TestInjections.ResponseStats responseStats = inputParameters?.TestInjections?.Stats;
if (responseStats != null)
{
if (pipelineType == OptimisticDirectExecution)
{
responseStats.PipelineType = TestInjections.PipelineType.OptimisticDirectExecution;
}
else if (pipelineType == Specialized)
{
responseStats.PipelineType = TestInjections.PipelineType.Specialized;
}
else
{
responseStats.PipelineType = TestInjections.PipelineType.Passthrough;
}
}
}
private static Documents.PartitionKeyDefinition GetPartitionKeyDefinition(InputParameters inputParameters, ContainerQueryProperties containerQueryProperties)
{
//todo:elasticcollections this may rely on information from collection cache which is outdated
//if collection is deleted/created with same name.
//need to make it not rely on information from collection cache.
Documents.PartitionKeyDefinition partitionKeyDefinition;
if ((inputParameters.Properties != null)
&& inputParameters.Properties.TryGetValue(InternalPartitionKeyDefinitionProperty, out object partitionKeyDefinitionObject))
{
if (!(partitionKeyDefinitionObject is Documents.PartitionKeyDefinition definition))
{
throw new ArgumentException(
"partitionkeydefinition has invalid type",
nameof(partitionKeyDefinitionObject));
}
partitionKeyDefinition = definition;
}
else
{
partitionKeyDefinition = containerQueryProperties.PartitionKeyDefinition;
}
return partitionKeyDefinition;
}
private static async Task<Documents.PartitionKeyRange> TryGetTargetRangeOptimisticDirectExecutionAsync(
InputParameters inputParameters,
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo,
CosmosQueryContext cosmosQueryContext,
ContainerQueryProperties containerQueryProperties,
ITrace trace)
{
bool clientDisableOptimisticDirectExecution = await cosmosQueryContext.QueryClient.GetClientDisableOptimisticDirectExecutionAsync();
bool isOdeContinuationToken = inputParameters.InitialUserContinuationToken != null &&
OptimisticDirectExecutionContinuationToken.IsOptimisticDirectExecutionContinuationToken(inputParameters.InitialUserContinuationToken);
// Use the Ode code path only if ClientDisableOptimisticDirectExecution is false and EnableOptimisticDirectExecution is true
// But allow the query using ODE pipeline if it's earlier roundtrips are made using ODE continuation token.
if ((clientDisableOptimisticDirectExecution || !inputParameters.EnableOptimisticDirectExecution) &&
!isOdeContinuationToken)
{
return null;
}
Debug.Assert(containerQueryProperties.ResourceId != null, "CosmosQueryExecutionContextFactory Assert!", "Container ResourceId cannot be null!");
List<Documents.PartitionKeyRange> targetRanges;
if (partitionedQueryExecutionInfo != null || inputParameters.InitialFeedRange != null)
{
targetRanges = await GetTargetPartitionKeyRangesAsync(
cosmosQueryContext.QueryClient,
cosmosQueryContext.ResourceLink,
partitionedQueryExecutionInfo,
containerQueryProperties,
inputParameters.Properties,
inputParameters.InitialFeedRange,
trace);
}
else
{
Documents.PartitionKeyDefinition partitionKeyDefinition = GetPartitionKeyDefinition(inputParameters, containerQueryProperties);
if (inputParameters.PartitionKey.HasValue)
{
Debug.Assert(partitionKeyDefinition != null, "CosmosQueryExecutionContextFactory Assert!", "PartitionKeyDefinition cannot be null if partitionKey is defined");
targetRanges = await cosmosQueryContext.QueryClient.GetTargetPartitionKeyRangesAsync(
cosmosQueryContext.ResourceLink,
containerQueryProperties.ResourceId,
containerQueryProperties.EffectiveRangesForPartitionKey,
forceRefresh: false,
trace);
}
else
{
targetRanges = await cosmosQueryContext.QueryClient.GetTargetPartitionKeyRangesAsync(
cosmosQueryContext.ResourceLink,
containerQueryProperties.ResourceId,
new List<Documents.Routing.Range<string>> { FeedRangeEpk.FullRange.Range },
forceRefresh: false,
trace);
}
}
if (targetRanges.Count == 1)
{
return targetRanges.Single();
}
if (isOdeContinuationToken)
{
throw new InvalidOperationException("Execution of this query cannot resume using Optimistic Direct Execution continuation token due to partition split. Please restart the query without the continuation token.");
}
return null;
}
public sealed class InputParameters
{
private const int DefaultMaxConcurrency = 0;
private const int DefaultMaxItemCount = 1000;
private const int DefaultMaxBufferedItemCount = 1000;
private const bool DefaultReturnResultsInDeterministicOrder = true;
private const ExecutionEnvironment DefaultExecutionEnvironment = ExecutionEnvironment.Client;
public InputParameters(
SqlQuerySpec sqlQuerySpec,
CosmosElement initialUserContinuationToken,
FeedRangeInternal initialFeedRange,
int? maxConcurrency,
int? maxItemCount,
int? maxBufferedItemCount,
PartitionKey? partitionKey,
IReadOnlyDictionary<string, object> properties,
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo,
ExecutionEnvironment? executionEnvironment,
bool? returnResultsInDeterministicOrder,
bool enableOptimisticDirectExecution,
bool isNonStreamingOrderByQueryFeatureDisabled,
TestInjections testInjections)
{
this.SqlQuerySpec = sqlQuerySpec ?? throw new ArgumentNullException(nameof(sqlQuerySpec));
this.InitialUserContinuationToken = initialUserContinuationToken;
this.InitialFeedRange = initialFeedRange;
int resolvedMaxConcurrency = maxConcurrency.GetValueOrDefault(InputParameters.DefaultMaxConcurrency);
if (resolvedMaxConcurrency < 0)
{
resolvedMaxConcurrency = int.MaxValue;
}
this.MaxConcurrency = resolvedMaxConcurrency;
int resolvedMaxItemCount = maxItemCount.GetValueOrDefault(InputParameters.DefaultMaxItemCount);
if (resolvedMaxItemCount < 0)
{
resolvedMaxItemCount = int.MaxValue;
}
this.MaxItemCount = resolvedMaxItemCount;
int resolvedMaxBufferedItemCount = maxBufferedItemCount.GetValueOrDefault(InputParameters.DefaultMaxBufferedItemCount);
if (resolvedMaxBufferedItemCount < 0)
{
resolvedMaxBufferedItemCount = int.MaxValue;
}
this.MaxBufferedItemCount = resolvedMaxBufferedItemCount;
this.PartitionKey = partitionKey;
this.Properties = properties;
this.PartitionedQueryExecutionInfo = partitionedQueryExecutionInfo;
this.ExecutionEnvironment = executionEnvironment.GetValueOrDefault(InputParameters.DefaultExecutionEnvironment);
this.ReturnResultsInDeterministicOrder = returnResultsInDeterministicOrder.GetValueOrDefault(InputParameters.DefaultReturnResultsInDeterministicOrder);
this.EnableOptimisticDirectExecution = enableOptimisticDirectExecution;
this.IsNonStreamingOrderByQueryFeatureDisabled = isNonStreamingOrderByQueryFeatureDisabled;
this.TestInjections = testInjections;
}
public SqlQuerySpec SqlQuerySpec { get; }
public CosmosElement InitialUserContinuationToken { get; }
public FeedRangeInternal InitialFeedRange { get; }
public int MaxConcurrency { get; }
public int MaxItemCount { get; }
public int MaxBufferedItemCount { get; }
public PartitionKey? PartitionKey { get; }
public IReadOnlyDictionary<string, object> Properties { get; }
public PartitionedQueryExecutionInfo PartitionedQueryExecutionInfo { get; }
public ExecutionEnvironment ExecutionEnvironment { get; }
public bool ReturnResultsInDeterministicOrder { get; }
public TestInjections TestInjections { get; }
public bool EnableOptimisticDirectExecution { get; }
public bool IsNonStreamingOrderByQueryFeatureDisabled { get; }
public InputParameters WithContinuationToken(CosmosElement token)
{
return new InputParameters(
this.SqlQuerySpec,
token,
this.InitialFeedRange,
this.MaxConcurrency,
this.MaxItemCount,
this.MaxBufferedItemCount,
this.PartitionKey,
this.Properties,
this.PartitionedQueryExecutionInfo,
this.ExecutionEnvironment,
this.ReturnResultsInDeterministicOrder,
this.EnableOptimisticDirectExecution,
this.IsNonStreamingOrderByQueryFeatureDisabled,
this.TestInjections);
}
}
internal sealed class AggregateProjectionDetector
{
/// <summary>
/// Determines whether or not the SqlSelectSpec has an aggregate in the outer most query.
/// </summary>
/// <param name="selectSpec">The select spec to traverse.</param>
/// <returns>Whether or not the SqlSelectSpec has an aggregate in the outer most query.</returns>
public static bool HasAggregate(SqlSelectSpec selectSpec)
{
return selectSpec.Accept(AggregateProjectionDectorVisitor.Singleton);
}
private sealed class AggregateProjectionDectorVisitor : SqlSelectSpecVisitor<bool>
{
public static readonly AggregateProjectionDectorVisitor Singleton = new AggregateProjectionDectorVisitor();
public override bool Visit(SqlSelectListSpec selectSpec)
{
bool hasAggregates = false;
foreach (SqlSelectItem selectItem in selectSpec.Items)
{
hasAggregates |= selectItem.Expression.Accept(AggregateScalarExpressionDetector.Singleton);
}
return hasAggregates;
}
public override bool Visit(SqlSelectValueSpec selectSpec)
{
return selectSpec.Expression.Accept(AggregateScalarExpressionDetector.Singleton);
}
public override bool Visit(SqlSelectStarSpec selectSpec)
{
return false;
}
/// <summary>
/// Determines if there is an aggregate in a scalar expression.
/// </summary>
private sealed class AggregateScalarExpressionDetector : SqlScalarExpressionVisitor<bool>
{
private enum Aggregate
{
Min,
Max,
Sum,
Count,
Avg,
}
public static readonly AggregateScalarExpressionDetector Singleton = new AggregateScalarExpressionDetector();
public override bool Visit(SqlAllScalarExpression sqlAllScalarExpression)
{
// No need to worry about aggregates within the subquery (they will recursively get rewritten).
return false;
}
public override bool Visit(SqlArrayCreateScalarExpression sqlArrayCreateScalarExpression)
{
bool hasAggregates = false;
foreach (SqlScalarExpression item in sqlArrayCreateScalarExpression.Items)
{
hasAggregates |= item.Accept(this);
}
return hasAggregates;
}
public override bool Visit(SqlArrayScalarExpression sqlArrayScalarExpression)
{
// No need to worry about aggregates in the subquery (they will recursively get rewritten).
return false;
}
public override bool Visit(SqlBetweenScalarExpression sqlBetweenScalarExpression)
{
return sqlBetweenScalarExpression.Expression.Accept(this) ||
sqlBetweenScalarExpression.StartInclusive.Accept(this) ||
sqlBetweenScalarExpression.EndInclusive.Accept(this);
}