Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,18 @@

```text
/
├── src/Cosmos.Sql/ – Cosmos DB SQL model (FSharp.Azure.Cosmos.Sql)
│ ├── EquatableArray.fs – immutable array with structural equality
│ ├── ImmutableArrayPatterns.fs – active patterns that match an `ImmutableArray` by its length
│ ├── Syntax.fs – syntax tree of the query language
│ ├── Keywords.fs – reserved words and the identifier rule
│ ├── FunctionSpec.fs – specification of a built-in function
│ ├── CatalogData.fs – one row per built-in function
│ ├── Catalog.fs – lookup of built-in functions
│ ├── ValidationError.fs – validation errors and options
│ ├── Inline.fs – replacement of parameters by literals
│ ├── Printer.fs – printer of the query text
│ └── Validator.fs – rules of the query language that the grammar cannot express
├── src/Cosmos/ – main library (FSharp.Azure.Cosmos)
│ ├── SubStatusCodes.fs – documented Cosmos DB sub-status codes
│ ├── Cosmos.fs – core types and container extensions
Expand All @@ -28,7 +40,9 @@
├── src/Shared/ – source files that every F# project under src and tests compiles
│ └── ValueCollections.fs – `Seq`, `List` and `Array` functions that return `voption` and struct tuples
├── tests/Cosmos.Tests/ – MSTest integration test project
├── tests/Cosmos.Sql.Tests/ – MSTest unit tests of FSharp.Azure.Cosmos.Sql, no emulator needed
├── tests/Cosmos.Tests.Infrastructure/ – shared test fixtures, emulator settings and assertion helpers
├── benchmarks/Cosmos.Quotations.Benchmarks/ – BenchmarkDotNet measurements for the quotation translator, run by hand
├── build/ – FAKE build scripts
└── docsSrc/ – FSharp.Formatting documentation source
```
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
* `FSharp.Azure.Cosmos.Sql` package: an immutable syntax tree of the Azure Cosmos DB NoSQL query language that mirrors the grammar of the .NET SDK, a deterministic printer with a parameterized and an inline mode, a validator for the rules the grammar cannot express and the catalog of the built-in functions as data, without a dependency on the Azure Cosmos DB SDK

### Changed
* BREAKING: the package targets `net10.0` only and no longer supports `net8.0`, which makes this a major release
* BREAKING: `Microsoft.Azure.Cosmos` updated from 3.60.0 to 3.62.0, which becomes the minimum version for consumers. Its release notes list a breaking change of their own: thin client mode is enabled by default and does not support resource-token authentication (opt out with `AZURE_COSMOS_THIN_CLIENT_ENABLED=false`)
Expand Down
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
</ItemGroup>
<ItemGroup Label="Build and Test">
<PackageVersion Include="Argu" Version="6.2.5" />
<PackageVersion Include="BenchmarkDotNet" Version="0.15.8" />
<PackageVersion Include="Fake.Api.GitHub" Version="6.1.5" />
<PackageVersion Include="Fake.BuildServer.GitHubActions" Version="6.1.5" />
<PackageVersion Include="Fake.Core.Environment" Version="6.1.5" />
Expand All @@ -28,6 +29,7 @@
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="10.0.401" />
<PackageVersion Include="MSTest" Version="4.2.3" />
<PackageVersion Include="MSTest.TestFramework" Version="4.2.3" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
<PackageVersion Include="NuGet.Common" Version="6.14.3" />
<PackageVersion Include="NuGet.Protocol" Version="6.14.3" />
<PackageVersion Include="Octokit" Version="14.0.0" />
Expand Down
3 changes: 3 additions & 0 deletions FSharp.Azure.Cosmos.slnf
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
"solution": {
"path": "FSharp.Azure.Cosmos.slnx",
"projects": [
"benchmarks\\Cosmos.Quotations.Benchmarks\\FSharp.Azure.Cosmos.Quotations.Benchmarks.fsproj",
"src\\Cosmos.Sql\\FSharp.Azure.Cosmos.Sql.fsproj",
"src\\Cosmos\\FSharp.Azure.Cosmos.fsproj",
"tests\\Cosmos.Sql.Tests\\FSharp.Azure.Cosmos.Sql.Tests.fsproj",
"tests\\Cosmos.Tests.Infrastructure\\FSharp.Azure.Cosmos.Tests.Infrastructure.fsproj",
"tests\\Cosmos.Tests\\FSharp.Azure.Cosmos.Tests.fsproj"
]
Expand Down
4 changes: 4 additions & 0 deletions FSharp.Azure.Cosmos.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,13 @@
<File Path="Directory.Packages.props" />
<File Path="global.json" />
<File Path="README.md" />
<File Path="THIRD-PARTY-NOTICES.md" />
</Folder>
<Project Path="benchmarks/Cosmos.Quotations.Benchmarks/FSharp.Azure.Cosmos.Quotations.Benchmarks.fsproj" />
<Project Path="build/build.fsproj" />
<Project Path="src/Cosmos.Sql/FSharp.Azure.Cosmos.Sql.fsproj" />
<Project Path="src/Cosmos/FSharp.Azure.Cosmos.fsproj" />
<Project Path="tests/Cosmos.Sql.Tests/FSharp.Azure.Cosmos.Sql.Tests.fsproj" />
<Project Path="tests/Cosmos.Tests.Infrastructure/FSharp.Azure.Cosmos.Tests.Infrastructure.fsproj" />
<Project Path="tests/Cosmos.Tests/FSharp.Azure.Cosmos.Tests.fsproj" />
</Solution>
42 changes: 42 additions & 0 deletions THIRD-PARTY-NOTICES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Third-party notices

This repository and the packages built from it include material from the third-party projects listed below. The
original copyright notices and licences are reproduced here.

## Azure Cosmos DB .NET SDK v3

* Source: <https://github.com/Azure/azure-cosmos-dotnet-v3>, tag `3.62.0` (commit `fe16fe00617e962dbab246244813d605871c086d`)
* Licence: MIT
* Used in `FSharp.Azure.Cosmos.Sql` (`src/Cosmos.Sql`) and its tests (`tests/Cosmos.Sql.Tests`):
* the node inventory of the syntax tree, after the classes in `Microsoft.Azure.Cosmos/src/SqlObjects` and the
grammar `Microsoft.Azure.Cosmos/src/Query/Core/Parser/sql.g4`;
* the printing rules, after `Microsoft.Azure.Cosmos/src/SqlObjects/Visitors/SqlObjectTextSerializer.cs`;
* the names of the built-in functions in the catalog, from `SqlFunctionCallScalarExpression.Names` in
`Microsoft.Azure.Cosmos/src/SqlObjects/SqlFunctionCallScalarExpression.cs`;
* expected query texts in the tests, from the baselines in
`Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/BaselineTest/TestBaseline` and
`Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/BaselineTest/TestBaseline`.

```text
MIT License

Copyright (c) Microsoft Corporation. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
```
28 changes: 28 additions & 0 deletions benchmarks/Cosmos.Quotations.Benchmarks/EvaluationBenchmarks.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace FSharp.Azure.Cosmos.Quotations.Benchmarks

open FSharp.Linq.RuntimeHelpers
open BenchmarkDotNet.Attributes

/// <summary>
/// What it costs to turn a subexpression that does not read the document into the value of a parameter, in two ways:
/// by reflection over its nodes, as <see cref="T:FSharp.Azure.Cosmos.Quotations.Benchmarks.ShapeKey"/> does, and by
/// <see cref="M:Microsoft.FSharp.Linq.RuntimeHelpers.LeafExpressionConverter.EvaluateQuotation(Microsoft.FSharp.Quotations.FSharpExpr)"/>,
/// which converts the quotation to a LINQ expression tree and compiles it.
/// </summary>
[<MemoryDiagnoser>]
type EvaluationBenchmarks () =

let memberOfRecord = SampleQuery.minAgeOf { MinAge = 18; City = "Kyiv" }
let clockArithmetic = SampleQuery.thirtyDaysAgo ()

[<Benchmark(Description = "Reflection: filter.MinAge")>]
member _.ReflectMember () : QueryShape = ShapeKey.compute memberOfRecord

[<Benchmark(Description = "Compiled: filter.MinAge")>]
member _.CompileMember () : objnull = LeafExpressionConverter.EvaluateQuotation memberOfRecord

[<Benchmark(Description = "Reflection: UtcNow.AddDays -30.0")>]
member _.ReflectClock () : QueryShape = ShapeKey.compute clockArithmetic

[<Benchmark(Description = "Compiled: UtcNow.AddDays -30.0")>]
member _.CompileClock () : objnull = LeafExpressionConverter.EvaluateQuotation clockArithmetic
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">

<!--
Measurements for the cost model of the quotation translator (ADR 0001): a console application that is run by hand,
see README.md next to this file. It lies outside src/ and tests/, so nothing packs it, runs it as a test or counts
it in the coverage.
-->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<AssemblyName>$(AssemblyBaseName).Quotations.Benchmarks</AssemblyName>
<OutputType>Exe</OutputType>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<Compile Include="SampleQuery.fs" />
<Compile Include="ShapeKey.fs" />
<Compile Include="QuotationBenchmarks.fs" />
<Compile Include="EvaluationBenchmarks.fs" />
<Compile Include="SqlModelBenchmarks.fs" />
<Compile Include="RoundTripBenchmarks.fs" />
<Compile Include="Program.fs" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="BenchmarkDotNet" />
<PackageReference Include="Microsoft.Azure.Cosmos" />
<!--
The SDK loads Newtonsoft.Json in the constructor of the client, whatever the serializer, and declares no
dependency on it. A test project gets the assembly from the test host; a console application has to bring it.
-->
<PackageReference Include="Newtonsoft.Json" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Cosmos.Sql\FSharp.Azure.Cosmos.Sql.fsproj" />
<!-- Only for the round trip benchmarks: the client of the emulator and the prefix of the databases the test runs sweep -->
<ProjectReference Include="..\..\tests\Cosmos.Tests.Infrastructure\FSharp.Azure.Cosmos.Tests.Infrastructure.fsproj" />
</ItemGroup>

</Project>
14 changes: 14 additions & 0 deletions benchmarks/Cosmos.Quotations.Benchmarks/Program.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/// <summary>
/// Runs the benchmarks chosen on the command line, such as <c>--filter *QuotationBenchmarks*</c>; without arguments
/// BenchmarkDotNet asks which ones to run.
/// </summary>
module FSharp.Azure.Cosmos.Quotations.Benchmarks.Program

open BenchmarkDotNet.Running

[<EntryPoint>]
let main (arguments : string array) : int =
BenchmarkSwitcher.FromAssembly(typeof<QuotationBenchmarks>.Assembly).Run arguments
|> ignore

0
76 changes: 76 additions & 0 deletions benchmarks/Cosmos.Quotations.Benchmarks/QuotationBenchmarks.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
namespace FSharp.Azure.Cosmos.Quotations.Benchmarks

open System.Collections.Generic
open System.Collections.Immutable
open Microsoft.Azure.Cosmos
open FSharp.Quotations
open BenchmarkDotNet.Attributes

open FSharp.Azure.Cosmos.Sql

/// A translated query the way a plan cache holds it: the query text and, for every slot, the name of its parameter.
[<Struct>]
type CachedPlan = { Sql : string; ParameterNames : ImmutableArray<string> }

/// <summary>
/// What an execution of a query costs on the client before the request leaves, once its translation is cached: the
/// quotation literal is evaluated, walked for its
/// <see cref="T:FSharp.Azure.Cosmos.Quotations.Benchmarks.QueryShape"/>, the plan is found by the key, and the values
/// are bound to a new <see cref="T:Microsoft.Azure.Cosmos.QueryDefinition"/>.
/// </summary>
[<MemoryDiagnoser>]
type QuotationBenchmarks () =

let minAge = 18
let city = "Kyiv"
let predicate = SampleQuery.predicate minAge city
let shape = ShapeKey.compute predicate

let plan = {
Sql = Printer.print PropertyStyle.Brackets (SampleQuery.syntaxTree ())
ParameterNames = SampleQuery.parameterNames
}

let plans = Dictionary<EquatableArray<int64>, CachedPlan>()

do
plans.Add (shape.Key, plan)

// The prototype has no tests of its own, so what the numbers rest on is checked before anything is measured
if shape.SlotValues.Length <> plan.ParameterNames.Length then
invalidOp $"The predicate has {shape.SlotValues.Length} slots, the query {plan.ParameterNames.Length} parameters."

if not (plans.ContainsKey (ShapeKey.compute (SampleQuery.predicate 21 "Lviv")).Key) then
invalidOp "The same predicate over other values should have the same key."

if plans.ContainsKey (ShapeKey.compute <@ fun (p : Person) -> p.Age > minAge && p.City = city @>).Key then
invalidOp "Another predicate should have another key."

let bind (plan : CachedPlan) (values : ImmutableArray<objnull>) : QueryDefinition =
let mutable definition = QueryDefinition plan.Sql

for index in 0 .. values.Length - 1 do
definition <- definition.WithParameter (plan.ParameterNames[index], values[index])

definition

/// The cost FSharp.Core adds to every use of a quotation literal: it reads the pickled tree anew each time.
[<Benchmark(Description = "Evaluate the quotation literal")>]
member _.EvaluateLiteral () : Expr<Person -> bool> = SampleQuery.predicate minAge city

[<Benchmark(Description = "Evaluate a literal of one condition")>]
member _.EvaluateShortLiteral () : Expr<Person -> bool> = SampleQuery.shortPredicate minAge

[<Benchmark(Description = "Shape key and slot values")>]
member _.ComputeShape () : QueryShape = ShapeKey.compute predicate

[<Benchmark(Description = "Find the plan by the key")>]
member _.FindPlan () : CachedPlan = plans[shape.Key]

[<Benchmark(Description = "QueryDefinition with 3 parameters")>]
member _.Bind () : QueryDefinition = bind plan shape.SlotValues

[<Benchmark(Description = "All four: one cached execution")>]
member _.CachedExecution () : QueryDefinition =
let shape = ShapeKey.compute (SampleQuery.predicate minAge city)
bind plans[shape.Key] shape.SlotValues
Loading
Loading