Sr. Content Developer at Microsoft, working remotely in PA, TechBash conference organizer, former Microsoft MVP, Husband, Dad and Geek.
165739 stories
·
33 followers

Moving Off Windows Server 2016? Take Your Data Protection Keys With You

1 Share
Windows Server 2016 reaches end of extended support on January 12, 2027, and plenty of ASP.NET Core apps will move to new servers or Azure before then. If you never configured Data Protection, your keys are probably tied to the old machine, and the move signs everyone out. Here is how to find where your keys live today, give them a real home, and make the server move a non-event.
Read the whole story
alvinashcraft
just a second ago
reply
Pennsylvania, USA
Share this story
Delete

Visual Studio Code 1.149 (Insiders)

1 Share

Learn what's new in Visual Studio Code 1.149 (Insiders)

Read the full article

Read the whole story
alvinashcraft
21 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Bending Aspire to your will - Build a custom resource (Part 1)

1 Share

I spend a lot of time testing and debugging APIs, and so do my AI agents. Lately I notice that my agents lose time and tokens on it. They look for the right port, guess at endpoints, fight with a terminal, and try to get the database back into a known state. Every run starts with the same detective work.

So for this series of posts I picked one scenario and I’m sticking with it: the API-testing loop. The goal is to adapt Aspire so that I (and my agents) can debug and test easily and efficiently.

Note: this post is part of a series about the demos from my session “Bending Aspire to your will”.

Every API in my AppHost has its own OpenAPI document, and every API can have its own UI. I want one API reference for the whole graph. Scalar runs as a container, so it fits in Aspire as a resource. The question is how you build a custom resource that feels like it belongs there.

The naive way is a Scalar container with a hand-written list of API URLs. It works, but it is one more list I have to maintain, and the services have no say in it. What I want is this:

catalogService.WithOpenApi(endpointName: "https", title: "Catalog API");
builder.AddScalar().WaitFor(catalogService);

Services declare that they have an OpenAPI document. Scalar finds them. Neither knows more than that about the other.

Everything is a resource

In Aspire, everything in the graph is a resource: containers, executables, projects, parameters and connection strings. They are built from a small set of base types (ContainerResource, ExecutableResource, ProjectResource, ParameterResource, ConnectionStringResource) and interfaces that describe what a resource can do (IResourceWithEndpoints, IResourceWithConnectionString, IResourceWithEnvironment, IResourceWithWaitSupport, ...).

The most important rule to apply is that a resource class is inert. It is data. No side effects in the constructor. The behaviour lives next to it:

  • Extension methods: Add* creates a resource, With* configures it.
  • Annotations: typed metadata. URLs, commands, icons and health checks are all annotations.
  • Lifecycle events: the moments where your code may run, like before start or when ready.

Previous parts of this Aspire blog series used the annotation-based APIs without you noticing. WithIconName, WithUrls and WithCommand are all extension methods that add an annotation.

Classify before you code

Before I write a line, I answer four questions. Resources don't fit in one inheritance tree, so I look at four axes instead:

Axis Ask Examples
Resource shape What does it represent? Container, Executable, External reference, Sidecar
Lifecycle mode When does it exist? Run, Publish/Deploy, Both, Mode-agnostic
Integration role What job does it do? Dependency, Workload, Companion, Bridge, Controller
Structure How is it wired? Standalone, Parent-child, Facade, Singleton, Overlay

PostgreSQL, for example, is a container-backed service, a dependency, and has child and companion structures, all at once.

For Scalar, the answers are:

  • Shape: a tool container, so ContainerResource.
  • Lifecycle: run-only. It is always excluded from the manifest.
  • Role: a standalone developer tool.
  • Structure: a singleton utility with annotation-driven discovery.

That last answer gives me the naming. If a tool belongs to one parent, you write With{Tool} on that parent. If it serves many resources, you write Add{Tool} on the builder. Scalar serves many, so it's AddScalar().

The resource: one line

public sealed class ScalarResource(string name) : ContainerResource(name);

That's it. No logic, no constructor side effects.

The annotation: what a service offers

The service needs a way to say "I have an OpenAPI document". That is an annotation:

public sealed record OpenApiAnnotation(EndpointReference Endpoint, string Path, string Title) : IResourceAnnotation;

And an extension method to add it:

public static IResourceBuilder<T> WithOpenApi<T>(
    this IResourceBuilder<T> builder,
    string path = "/openapi/v1.json",
    string endpointName = "http",
    string? title = null) where T : IResourceWithEndpoints
{
    ArgumentNullException.ThrowIfNull(builder);
    ArgumentException.ThrowIfNullOrWhiteSpace(path);
    ArgumentException.ThrowIfNullOrWhiteSpace(endpointName);

    if (!path.StartsWith('/') || path.StartsWith("//", StringComparison.Ordinal) || path.Contains('\\')
        || !Uri.TryCreate(path, UriKind.Relative, out _))
    {
        throw new ArgumentException("The OpenAPI path must be an absolute URL path, such as /openapi/v1.json.", nameof(path));
    }

    if (title is not null)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(title);
    }

    return builder.WithAnnotation(new OpenApiAnnotation(
        builder.GetEndpoint(endpointName), path, title ?? builder.Resource.Name));
}

Most of this is argument validation. The core is the last statement: one annotation with an endpoint reference, a path and a title. The generic constraint where T : IResourceWithEndpoints means you can only call it on resources that actually have endpoints.

Now the services opt in:

catalogService.WithOpenApi(endpointName: "https", title: "Catalog API");
catalogDbManager.WithOpenApi(endpointName: "https", title: "Catalog DB Manager API");

Remark: services declare what they offer with an annotation and know nothing about Scalar. If I replace Scalar with another tool next year, the services don't change.

That's it! At this point nothing runs. A resource class, an annotation and an extension method are only data. In the next part, I add the behaviour: AddScalar, the container, and the way it discovers the documents when the AppHost starts.

More information

Read the whole story
alvinashcraft
29 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

DuckDB.NET 1.5.6.1: Scalar Functions Up to 7.7× Faster

1 Share

Introduction

, the .NET client for the DuckDB in-process analytical database, runs scalar functions written in C# 5 to 7.7 times as fast in version 1.5.6.1 as in 1.5.6, and table functions 2.5 to 5.9 times as fast. A query that reads one of the four columns of a table function is 6.3 times as fast, and the columns it doesn’t read are no longer worked out at all. Reading LIST, STRUCT and MAP columns is up to 5.9 times as fast, and functions with a nullable argument or result, as well as table functions that return structs, allocate almost nothing any more.

This is part 4 of a series. covers reading data, appending and dates, and 128-bit values and decimals. As in the previous parts, none of this comes from DuckDB itself. Every benchmark runs DuckDB.NET 1.5.6 and 1.5.6.1 against the same DuckDB 1.5.6 engine, so the difference is the .NET code alone.

Table of Contents

The results

The benchmarks ran with and .NET 10 on the same Linux virtual machine as in the previous posts, an Azure F8as_v7 with an AMD EPYC 9V45 (Zen 5). describes how they were run. The speedup is the range across all the benchmarks of a feature. The times and allocations are for the one benchmark in the Example column.

Feature Speedup Example 1.5.6 time 1.5.6.1 time 1.5.6 allocated 1.5.6.1 allocated
Typed scalar functions 5.0–7.7× 1M calls with an int? argument 21.2 ms 4.0 ms 20.7 MB 104 KB
Scalar function with a string argument 1.6× 1M calls, the length of a string 29.4 ms 18.4 ms 38 MB 38 MB
Table functions 2.5–5.9× 1M rows of four columns 37.4 ms 9.6 ms 20.8 MB 110 KB
Projection pushdown 6.3× 1M rows, one of four columns read 18.7 ms 2.95 ms 97 KB 40 KB
Reading LIST, STRUCT and MAP 1.1–5.9× 200k lists of int? 31.1 ms 5.3 ms 45.8 MB 18.3 MB
Control: work done by DuckDB 1.0× SUM over 1M rows in SQL 0.508 ms 0.506 ms 1.1 KB 1.1 KB
Control: a table instead of a table function 1.0× 1M rows of one column 0.378 ms 0.376 ms 1.4 KB 1.3 KB

For the tables that follow one change at a time, I ran the benchmarks again on the same machine and measured every commit against the one before it. The times of that run are a little different from the table above, so compare the rows within one table. Most of these functions and reads also got faster from the changes in the previous posts, so each table has a row for the commit just before the changes of its section, which has all of those.

Scalar functions

How a typed function reads and writes its values

added a simpler way to register a scalar function. You give it a lambda, and DuckDB.NET reads the arguments and writes the results for you:

connection.RegisterScalarFunction<int, int>("plus_one", value => value + 1);

DuckDB calls a scalar function once for every chunk of up to 2,048 rows, and DuckDB.NET then calls the lambda once for every row. In DuckDB.NET 1.5.6 it wrapped the lambda in a delegate for one row and a loop over the public reader and writer interfaces:

// DuckDB.NET 1.5.6, DuckDBConnectionScalarFunctionExtensions
public void RegisterScalarFunction<T, TResult>(string name, Func<T, TResult> func)
{
 var (nullability, anyNullable) = InferParameterNullability(func);

 connection.RegisterScalarFunction<T, TResult>(name, WrapScalarFunction<TResult>((readers, index) =>
 func(ReadValue<T>(readers[0], index, nullability[0], anyNullable))), new() { HandlesNulls = anyNullable });
}

private static Action<IReadOnlyList<IDuckDBDataReader>, IDuckDBDataWriter, ulong> WrapScalarFunction<TResult>(
 Func<IReadOnlyList<IDuckDBDataReader>, ulong, TResult> perRowFunc)
{
 return (readers, writer, rowCount) =>
 {
 for (ulong index = 0; index < rowCount; index++)
 {
 var result = perRowFunc(readers, index);

 writer.WriteValue(result, index); // IDuckDBDataWriter.WriteValue<TResult>
 }
 };
}

private static T ReadValue<T>(IDuckDBDataReader reader, ulong index, bool isNullable, bool checksNulls)
{
 ...
 return typeof(T) == typeof(object) ? (T)reader.GetValue(index) : reader.GetValue<T>(index); // IDuckDBDataReader.GetValue<T>
}

ReadValue calls GetValue<T> on an IDuckDBDataReader, and the loop calls WriteValue<T> on an IDuckDBDataWriter. Both are generic methods called through an interface, which is the generic virtual call from . The runtime has to look up the code for the actual class and the type argument on every call, so every row of a function with one argument pays for two lookups. The commit just before the fix still has this code, so let’s see what the JIT generates for its loop. On .NET 10.0.12, x64, Linux, the Tier1 code looks like this (edited for brevity):

; DuckDB.NET 0407f4c, the loop of WrapScalarFunction<int>
 call [r11]IReadOnlyList`1[__Canon]:get_Item(int) ; readers[0], an interface call
 ...
 call CORINFO_HELP_VIRTUAL_FUNC_PTR ; look up IDuckDBDataReader.GetValue<int>
 call rax
 ...
 call [rcx+0x18]System.Func`2[int,int]:Invoke(int) ; the lambda
 ...
 call CORINFO_HELP_VIRTUAL_FUNC_PTR ; look up IDuckDBDataWriter.WriteValue<int>
 call rax
 inc r12 ; next row

Besides the two lookups, every row makes an interface call to get the reader out of the list and calls the lambda through a delegate.

Calling the readers and the writer without generic virtual calls

The library doesn’t need the interfaces in its own loops, so I gave , which gets the readers and the writer as the VectorDataReaderBase and VectorDataWriterBase classes:

// DuckDB.NET ee223da, DuckDBConnectionScalarFunctionExtensions
public void RegisterScalarFunction<T, TResult>(string name, Func<T, TResult> func)
{
 var (nullability, anyNullable) = InferParameterNullability(func);

 connection.RegisterScalarMethod(name, (readers, writer, rowCount) => // VectorDataReaderBase[], VectorDataWriterBase
 {
 var reader = readers[0];
 var nullable = nullability[0];

 for (ulong index = 0; index < rowCount; index++)
 {
 writer.WriteValue(func(ReadValue<T>(reader, index, nullable, anyNullable)), index);
 }
 }, LogicalType<TResult>(), varargs: false, new() { HandlesNulls = anyNullable }, LogicalType<T>());
}

GetValue<T> and WriteValue<T> aren’t virtual on these classes, so the JIT calls them directly and can inline them. The loop of plus_one now looks like this:

; DuckDB.NET ee223da, the loop of RegisterScalarFunction<int, int>
 cmp qword ptr [r13+0x28], 0 ; does the argument have NULLs?
 jne G_M000_IG10 ; then check the row's validity bit
 mov rdi, 0x72D160805240 ; typeof(int)
 cmp gword ptr [r13+0x20], rdi ; StorageType == typeof(int)?
 jne G_M000_IG11 ; no: ReadInt32, a plain virtual call
 mov rdi, qword ptr [r13+0x30] ; DataPointer
 mov esi, dword ptr [rdi+4*rax] ; the argument
 mov rdi, 0x72D164428420
 cmp qword ptr [rcx+0x18], rdi ; is the function the lambda seen while profiling?
 jne G_M000_IG12 ; no: call it through the delegate
 inc esi ; value + 1, the lambda inlined
 ...
 call [VectorDataWriterBase:WriteValue[int](int,ulong):this] ; the only call left
 inc rax ; next row

The read of the argument is the fast path we saw in part 1, a comparison of StorageType and a load. The JIT also guessed the lambda from profile data and inlined it, so value + 1 is the inc esi, and the only call left is WriteValue<int>.

In the table below, job 2 is the commit just before this change. The reader and writer changes of the previous posts had already taken IntFunction from 13.61 to 7.87 ms, and with this change it takes 2.50 ms. A function of two int arguments went from 11.59 to 3.14 ms, and a function of a double from 8.14 to 2.59 ms. The function that takes a string gains less, from 23.88 to 19.03 ms. It also creates a .NET string for every value, 38 MB for a million rows, which this change doesn’t touch:

Method Job Mean Median Ratio
IntFunction 1-1.5.6 13.46 ms 13.61 ms 1.00
IntFunction 2-0407f4c 8.06 ms 7.87 ms 0.60
IntFunction 3-ee223da 2.58 ms 2.50 ms 0.19
TwoIntFunction 1-1.5.6 20.69 ms 20.79 ms 1.00
TwoIntFunction 2-0407f4c 11.63 ms 11.59 ms 0.56
TwoIntFunction 3-ee223da 3.16 ms 3.14 ms 0.15
DoubleFunction 1-1.5.6 13.17 ms 13.01 ms 1.00
DoubleFunction 2-0407f4c 8.24 ms 8.14 ms 0.63
DoubleFunction 3-ee223da 2.65 ms 2.59 ms 0.20
StringFunction 1-1.5.6 31.93 ms 32.26 ms 1.00
StringFunction 2-0407f4c 23.80 ms 23.88 ms 0.75
StringFunction 3-ee223da 19.09 ms 19.03 ms 0.60

In this run, 1.5.6 also measured the SUM in SQL, which runs no function at all, about 7% slower than the other jobs did. So the ratios against 1.5.6 in this section are a little better than they should be, and the steps between the rows are the numbers to look at.

Nullable results

The functions that take or return an int? gained less from that change. NullableIntFunction adds one to an int? argument, and after the change it still took 11.66 ms, more than four times as long as the same function on an int. It also allocated 21 MB for a million rows. That’s the box from , because the result went through WriteValue<int?>, whose type switch boxed every nullable value that wasn’t NULL. The fix from part 2, which writes a nullable value as the type under it, removes the box here too. NullableIntFunction went down to 7.32 ms, and IntToNullableFunction, which takes an int and returns an int?, from 10.89 to 6.29 ms:

Method Job Mean Median Ratio Allocated Alloc Ratio
NullableIntFunction 1-1.5.6 21.25 ms 21.24 ms 1.00 21,195.43 KB 1.000
NullableIntFunction 3-ee223da 11.74 ms 11.66 ms 0.55 21,199.22 KB 1.000
NullableIntFunction 4-40b625b 7.32 ms 7.32 ms 0.34 104.33 KB 0.005
IntToNullableFunction 1-1.5.6 19.51 ms 19.50 ms 1.00 23,539.21 KB 1.000
IntToNullableFunction 3-ee223da 10.96 ms 10.89 ms 0.56 23,543.01 KB 1.000
IntToNullableFunction 4-40b625b 6.30 ms 6.29 ms 0.32 104.32 KB 0.004

As you can see, that still left IntToNullableFunction more than twice as slow as IntFunction, although both add one to an int. The difference is how the result reaches the writer. On the commit just before the next fix, the loop looks like this:

; DuckDB.NET d9bf172, the loop of RegisterScalarFunction<int, int?>
 mov esi, dword ptr [rdi+4*rax] ; the argument
 ...
 inc esi ; value + 1, the lambda inlined
 mov byte ptr [rbp-0x38], 1 ; the int? on the stack: HasValue
 mov dword ptr [rbp-0x34], esi ; and Value
 mov rsi, qword ptr [rbp-0x38] ; both read back as one 8-byte value
 ...
 call [VectorDataWriterBase:WriteValue[System.Nullable`1[int]](System.Nullable`1[int],ulong):this]

The JIT inlines the lambda and builds its int? result on the stack with two stores, one byte for HasValue and four bytes for the value. Then it reads both back with one 8-byte load to pass the int? to WriteValue<int?>. The CPU can’t hand the data of two smaller stores that are still in flight to one larger load, so it waits for the stores to finish. looks at that wait in detail. WriteValue<int?> then passes the value by reference to WriteNullable, which isn’t inlined.

takes a nullable result apart in the loop and writes its value as the type under it:

// DuckDB.NET 1.5.6.1, the loop of RegisterScalarFunction<T, TResult>
for (ulong index = 0; index < rowCount; index++)
{
 var result = func(ReadValue<T>(reader, index, nullable, anyNullable));
 if (typeof(TResult).IsValueType && default(TResult) is null) WriteResult(writer, result, index); else writer.WriteValue(result, index);
}

// DuckDB.NET 1.5.6.1, DuckDBConnectionScalarFunctionExtensions
private static void WriteResult<TResult>(VectorDataWriterBase writer, TResult result, ulong index)
{
 if (typeof(TResult).IsValueType && default(TResult) is null)
 {
 ...
 if (typeof(TResult) == typeof(int?)) { WriteNullableResult(writer, (int?)(object?)result, index); return; }
 if (typeof(TResult) == typeof(long?)) { WriteNullableResult(writer, (long?)(object?)result, index); return; }
 ... // one line for every nullable type a function can return
 }

 writer.WriteValue(result, index);
}

private static void WriteNullableResult<TValue>(VectorDataWriterBase writer, TValue? value, ulong index) where TValue : struct
{
 if (value.HasValue)
 {
 writer.WriteValue(value.GetValueOrDefault(), index);
 }
 else
 {
 writer.WriteNull(index);
 }
}

The typeof checks are constants for the JIT, so only the int? line is left, and the cast through object? is removed too without boxing anything. In part 2 I used Unsafe.As for the same job, but here it would take the address of the result and bring the 8-byte load back. Now the value and HasValue stay in registers:

; DuckDB.NET 80216f9, the loop of RegisterScalarFunction<int, int?>
 mov esi, dword ptr [rdi+4*rcx] ; the argument
 ...
 inc esi ; value + 1, the lambda inlined
 mov r8d, 1 ; HasValue, in a register
 test r8d, r8d
 jne G_M000_IG04 ; it has a value
 ... ; no value: WriteNull, inlined
G_M000_IG04:
 call [VectorDataWriterBase:WriteValue[int](int,ulong):this] ; written as an int

With the fix, IntToNullableFunction went from 6.27 to 2.50 ms, about the time of IntFunction, and NullableIntFunction from 7.33 to 4.02 ms:

Method Job Mean Median Ratio
NullableIntFunction 1-1.5.6 21.25 ms 21.24 ms 1.00
NullableIntFunction 5-d9bf172 7.36 ms 7.33 ms 0.35
NullableIntFunction 6-80216f9 4.02 ms 4.02 ms 0.19
IntToNullableFunction 1-1.5.6 19.51 ms 19.50 ms 1.00
IntToNullableFunction 5-d9bf172 6.27 ms 6.27 ms 0.32
IntToNullableFunction 6-80216f9 2.54 ms 2.50 ms 0.13

Table functions

Rows that keep their type

Now that we have covered scalar functions, let’s look at table functions. A table function returns rows that a query reads like a table. With the simpler API from 1.5, you give DuckDB.NET the rows and a projection that turns a row into columns:

connection.RegisterTableFunction("bench_rows", () => rows, row => new { row.Id, row.Value, row.Ratio, row.Optional });

DuckDB asks for the rows one chunk at a time, through a callback. In DuckDB.NET 1.5.6 the callback held the rows as a non-generic IEnumerator and handed each row to a Mapper that took it as an object:

// DuckDB.NET 1.5.6, DuckDBConnection.TableFunction
private static void TableFunction(IntPtr info, IntPtr chunk)
{
 ...
 for (; size < DuckDBGlobalData.VectorSize; size++)
 {
 if (tableFunctionInitData.Enumerator.MoveNext())
 {
 tableFunctionInfo.Mapper(tableFunctionInitData.Enumerator.Current, writers, size);
 }
 else
 {
 break;
 }
 }
 ...
}

// DuckDB.NET 1.5.6, DuckDBConnectionTableFunctionExtensions.ParseProjection
void Mapper(object? item, IDuckDBDataWriter[] writers, ulong rowIndex)
{
 combinedWriter((TData)item!, writers, rowIndex); // the compiled writer of the row
}

IEnumerator.Current returns an object, so a row that is a struct is boxed on every call, and Mapper unboxes it again for the compiled writer of the row. A row that is a class isn’t boxed, but it still goes through two interface calls and a delegate call. On the commit just before the fix, the loop of the callback looks like this (edited for brevity):

; DuckDB.NET dbb63cd, DuckDBConnection.TableFunction, one row
 call [r11]System.Collections.IEnumerator:MoveNext():bool:this ; an interface call
 ...
 call [r11]System.Collections.IEnumerator:get_Current():System.Object:this ; another one, the row as an object
 ...
 call [rax+0x18]System.Action`3[__Canon,__Canon,ulong]:Invoke(...) ; Mapper(object, writers, row)
 inc rbx ; next row

The struct rows of the benchmark have eight int properties. That’s 32 bytes, and with the object header the box is 48 bytes, so a million rows allocate 45.9 MB.

adds a scan that knows the type of its rows. The callback that DuckDB calls is static and can’t be generic, so it calls Fill on the scan’s non-generic base class once for every chunk, and the generic class keeps the type of the rows from there to the writer. An array and a List<T> are read by position, and any other source is enumerated as IEnumerator<T>:

// DuckDB.NET 1.5.6.1, TableFunctionScan
internal abstract class TableFunctionScan : IDisposable
{
 public abstract ulong Fill(VectorDataWriterBase[] writers, ulong maxRows);

 public static TableFunctionScan Create<T>(IEnumerable<T> rows, Action<T, VectorDataWriterBase[], ulong> write) => rows switch
 {
 T[] array => new ArrayScan<T>(array, write),
 List<T> list when list.GetType() == typeof(List<T>) => new ListScan<T>(list, write),
 _ => new EnumeratorScan<T>(rows.GetEnumerator(), write)
 };

 private sealed class ArrayScan<T>(T[] rows, Action<T, VectorDataWriterBase[], ulong> write) : TableFunctionScan
 {
 private int position;

 public override ulong Fill(VectorDataWriterBase[] writers, ulong maxRows)
 {
 var count = (int)Math.Min(maxRows, (ulong)(rows.Length - position));
 var chunk = new ReadOnlySpan<T>(rows, position, count);

 for (var index = 0; index < chunk.Length; index++)
 {
 write(chunk[index], writers, (ulong)index);
 }

 position += count;
 return (ulong)count;
 }
 }
 ...
}

Fill of an array of structs is now a loop with one call for every row, and the call gets the struct itself:

; DuckDB.NET 909c0cf, TableFunctionScan.ArrayScan<StructRow>.Fill, one row
 mov rsi, qword ptr [rdx+r13] ; the row, read from the array by position
 mov rdx, qword ptr [r13+rdx+0x08]
 ...
 call [r9+0x18]System.Action`3[StructRow,__Canon,ulong]:Invoke(StructRow,...) ; the writer of the row
 inc eax ; next row

In the table below, job 4 is the commit just before this change, which has the changes of the previous posts and of the scalar function section. Struct rows with one column went from 13.69 to 3.80 ms, and their allocations from 45.9 MB to 40 KB. Class rows, which were never boxed, went from 7.87 to 4.12 ms with one column, and rows that come from an iterator from 7.92 to 5.44 ms. With eight columns the gain is smaller for every kind of row:

Method Job Columns Mean Median Ratio Allocated Alloc Ratio
StructRows 1-1.5.6 1 17.21 ms 17.14 ms 1.00 46,962.50 KB 1.000
StructRows 4-dbb63cd 1 13.73 ms 13.69 ms 0.80 46,962.48 KB 1.000
StructRows 5-909c0cf 1 3.82 ms 3.80 ms 0.22 40.17 KB 0.001
StructRows 1-1.5.6 8 58.61 ms 58.51 ms 1.00 47,286.61 KB 1.000
StructRows 4-dbb63cd 8 29.98 ms 29.85 ms 0.51 47,286.62 KB 1.000
StructRows 5-909c0cf 8 20.21 ms 20.07 ms 0.34 203.87 KB 0.004
ClassRows 1-1.5.6 1 11.31 ms 11.29 ms 1.00 86.01 KB 1.00
ClassRows 4-dbb63cd 1 8.11 ms 7.87 ms 0.72 85.99 KB 1.00
ClassRows 5-909c0cf 1 4.13 ms 4.12 ms 0.37 40.16 KB 0.47
ClassRows 1-1.5.6 8 52.46 ms 52.42 ms 1.00 410.18 KB 1.00
ClassRows 4-dbb63cd 8 23.30 ms 23.27 ms 0.44 410.14 KB 1.00
ClassRows 5-909c0cf 8 20.31 ms 20.29 ms 0.39 203.86 KB 0.50
EnumeratedRows 1-1.5.6 1 10.93 ms 10.90 ms 1.00 86.06 KB 1.00
EnumeratedRows 4-dbb63cd 1 7.95 ms 7.92 ms 0.73 86.03 KB 1.00
EnumeratedRows 5-909c0cf 1 5.48 ms 5.44 ms 0.50 40.23 KB 0.47
EnumeratedRows 1-1.5.6 8 58.57 ms 52.79 ms 1.02 410.25 KB 1.00
EnumeratedRows 4-dbb63cd 8 24.24 ms 24.22 ms 0.42 410.18 KB 1.00
EnumeratedRows 5-909c0cf 8 21.68 ms 21.60 ms 0.38 203.93 KB 0.50

The times of 1.5.6 for eight columns of rows from an iterator vary a lot from one iteration to the next, so the median is the number to look at for that row.

Writing only the columns a query reads

Next, let’s look at the writer of a row. It is compiled from the projection with expression trees, and DuckDB.NET 1.5.6 compiled it once, when the function was registered, for every column:

// DuckDB.NET 1.5.6, DuckDBConnectionTableFunctionExtensions.CompileCombinedWriter
for (int i = 0; i < columnCount; i++)
{
 var reboundAccessor = replacer.Visit(accessors[i]); // data.Id, data.Value, ...
 var writerAccess = Expression.ArrayIndex(writersParam, Expression.Constant(i));

 writeCalls[i] = Expression.Call(writerAccess, WriteValueMethod.MakeGenericMethod(types[i]), reboundAccessor, rowIndexParam);
}
// (data, writers, rowIndex) => { writers[0].WriteValue(data.Id, rowIndex); writers[1].WriteValue(data.Value, rowIndex); ... }

A column that the query doesn’t read gets a writer that does nothing, but its value is still read from the row and handed to that writer through the interface. The change from the scalar function section added a test for VectorDataWriterBase in front of every column, so a column that the query reads calls WriteValue<T> directly. That’s the code just before the fix, and for four columns it compiles to 470 bytes:

; DuckDB.NET 909c0cf, the compiled writer of a row, first column
 mov r13, gword ptr [rbx+0x10] ; writers[0]
 mov rsi, r13
 mov rdi, 0x702760180430 ; VectorDataWriterBase
 call [CORINFO_HELP_ISINSTANCEOFCLASS] ; is writers[0] a VectorDataWriterBase?
 test rax, rax
 je G_M000_IG11 ; no, a column the query doesn't read
 mov esi, dword ptr [rbp-0x30] ; data.A
 call [VectorDataWriterBase:WriteValue[int](int,ulong):this]
 ... ; the same for the other three columns
G_M000_IG11:
 call [CORINFO_HELP_VIRTUAL_FUNC_PTR] ; look up WriteValue<int> of the writer that does nothing
 call rax

So SELECT sum(Id) FROM bench_rows() makes four type tests for every row, and three lookups and calls for writers that do nothing.

My first attempt kept the writer compiled once and made the test for the writer that does nothing cheaper. A test of its type compiled to a call of Object.GetType and gained nothing. Comparing the writer with the one instance that does nothing was faster, but the writer still tested every column for every row and still read the values of the columns the query doesn’t need.

DuckDB tells a table function which columns a query reads when it starts a scan. DuckDB.NET 1.5.6.1 , for those columns only, and keeps it by the list of columns, so the same query run again finds it:

// DuckDB.NET 1.5.6.1, DuckDBConnectionTableFunctionExtensions
var writers = new ConcurrentDictionary<string, Action<TData, VectorDataWriterBase[], ulong>>();

return (columns, (data, projected, _) =>
{
 var writeRow = writers.GetOrAdd(string.Join(',', projected), _ => CompileRowWriter<TData>(projected, types, accessors, parameter));

 return TableFunctionScan.Create((IEnumerable<TData>)data, writeRow);
});

private static Action<TData, VectorDataWriterBase[], ulong> CompileRowWriter<TData>(int[] projected, Type[] types, Expression[] accessors, ParameterExpression originalParam)
{
 ...
 for (int i = 0; i < projected.Length; i++)
 {
 var column = projected[i];
 var reboundAccessor = replacer.Visit(accessors[column]);
 var writerAccess = Expression.ArrayIndex(writersParam, Expression.Constant(i));

 writeCalls[i] = Expression.Call(writerAccess, WriteValueMethod.MakeGenericMethod(types[column]), reboundAccessor, rowIndexParam);
 }
 ...
}

The value of a column that the query doesn’t read isn’t worked out at all any more. For one column, the compiled writer is now a bounds check and a jump to WriteValue<int>:

; DuckDB.NET ea7aefe, the compiled writer of a row, one column
 push rax
 cmp dword ptr [rcx+0x08], 0 ; bounds check of the writers
 jbe SHORT G_M000_IG04
 mov rdi, gword ptr [rcx+0x10] ; writers[0]
 mov rdx, r8 ; the row
 cmp dword ptr [rdi], edi ; null check
 add rsp, 8
 tail.jmp [VectorDataWriterBase:WriteValue[int](int,ulong):this] ; data.A
G_M000_IG04:
 call CORINFO_HELP_RNGCHKFAIL

For four columns it’s 141 bytes, three calls and a jump, with no type test. With this change, the query that reads one of four columns went from 14.83 to 3.14 ms:

Method Job Mean Median Ratio Allocated Alloc Ratio
TableFunctionOneColumn 1-1.5.6 19.68 ms 19.49 ms 1.00 97.38 KB 1.00
TableFunctionOneColumn 5-909c0cf 14.86 ms 14.83 ms 0.76 40.05 KB 0.41
TableFunctionOneColumn 6-ea7aefe 3.17 ms 3.14 ms 0.16 40.07 KB 0.41

Queries that read every column gain too, without the type tests. Struct rows with one column went from 3.80 to 2.65 ms, and eight columns of class rows from 20.29 to 14.83 ms:

Method Job Columns Mean Median Ratio
StructRows 1-1.5.6 1 17.21 ms 17.14 ms 1.00
StructRows 5-909c0cf 1 3.82 ms 3.80 ms 0.22
StructRows 6-ea7aefe 1 2.65 ms 2.65 ms 0.15
ClassRows 1-1.5.6 8 52.46 ms 52.42 ms 1.00
ClassRows 5-909c0cf 8 20.31 ms 20.29 ms 0.39
ClassRows 6-ea7aefe 8 14.86 ms 14.83 ms 0.28
StructRows 1-1.5.6 8 58.61 ms 58.51 ms 1.00
StructRows 5-909c0cf 8 20.21 ms 20.07 ms 0.34
StructRows 6-ea7aefe 8 14.61 ms 14.56 ms 0.25

All the table function changes together

The table function of the results table has four columns, one of them an int?, and every change in this post touches it. The changes of the previous posts took it from 37.94 to 29.10 ms, and the loop without generic virtual calls to 23.04 ms. The commit before the typed scan also has the nullable write from part 2, which removed the 20.8 MB of boxes of the int? column. The typed scan and the writer for the columns a query reads took it the rest of the way, and in 1.5.6.1 it takes 9.79 ms, about 3.9 times as fast as in 1.5.6:

Method Job Mean Median Ratio Allocated Alloc Ratio
TableFunction 1-1.5.6 38.41 ms 37.94 ms 1.00 21,334.82 KB 1.000
TableFunction 2-0407f4c 29.24 ms 29.10 ms 0.76 21,334.80 KB 1.000
TableFunction 3-ee223da 23.02 ms 23.04 ms 0.60 21,334.80 KB 1.000
TableFunction 4-dbb63cd 17.27 ms 17.26 ms 0.45 239.71 KB 0.011
TableFunction 5-909c0cf 14.06 ms 14.10 ms 0.37 109.82 KB 0.005
TableFunction 6-ea7aefe 10.27 ms 10.41 ms 0.27 109.92 KB 0.005
TableFunction 7-1.5.6.1 9.78 ms 9.79 ms 0.25 109.92 KB 0.005

Reading the same kind of rows from a table instead of a table function took the same time in every job, 0.37 to 0.38 ms for one column, so all of the time saved is in DuckDB.NET.

Reading lists, structs and maps

Working out the target type once per column

Finally, let’s see how DuckDB.NET reads lists, structs and maps. GetFieldValue<List<int>> reads a LIST or ARRAY column as a List<int>, GetFieldValue<T> with a class reads a STRUCT into the properties of that class, and GetFieldValue<Dictionary<int, string>> reads a MAP. In DuckDB.NET 1.5.6, the list reader worked out what to do with the type you asked for on every row:

// DuckDB.NET 1.5.6, ListVectorDataReader
private object GetList(Type returnType, ulong listOffset, ulong length)
{
 if (!returnType.IsGenericType) { throw ... }

 var listType = returnType.GetGenericArguments()[0]; // allocates an array
 ...
 var allowNulls = listType.AllowsNullValue(out _, out var nullableType);

 var list = Activator.CreateInstance(returnType) as IList ?? throw ...;

 //Special case for specific types to avoid boxing
 return list switch
 {
 List<int> theList => BuildList(theList),
 List<int?> theList => BuildList(theList),
 ... // float, double, decimal and their nullable forms
 _ => BuildListCommon(list, nullableType ?? listType)
 };
 ...
}

For every row it asked the type for its generic arguments, which allocates an array, checked whether the items can be NULL, created the list with Activator.CreateInstance and tested it against eight list types. The list also started empty and grew as the items were added. The struct reader did even more for every row. It created the object with Activator and looked its type up in a cache with a lambda that captured a parameter of the method, so every row allocated a closure. Then it looked up the reader of every field by name and set each property with a value passed as an object.

DuckDB.NET 1.5.6.1 , because a column is read as the same type row after row:

// DuckDB.NET 1.5.6.1, ListVectorDataReader
private Type? planType;
private ListPlan plan;

private object GetList(Type returnType, ulong listOffset, ulong length)
{
 if (returnType != planType)
 {
 plan = CreatePlan(returnType); // GetGenericArguments, AllowsNullValue and the type tests
 planType = returnType;
 }

 // The eight types read without boxing an item. The list is created with room for every item.
 var capacity = (int)length;

 return plan.Kind switch
 {
 ListKind.Int32 => BuildList(new List<int>(capacity), listOffset, length),
 ListKind.NullableInt32 => BuildNullableList(new List<int?>(capacity), listOffset, length),
 ...
 _ => BuildOtherList(returnType, listOffset, length)
 };
}

The struct reader pairs each property with the reader of its field once, in the same way. The allocations show what was saved for a list. A List<int> of five items now allocates 80 bytes per row, the list and its array of five items. In 1.5.6 it allocated 160 bytes, and the other 80 were the array from GetGenericArguments and the arrays the list grew through, with room for four items and then eight.

The reader changes of the previous posts are already in job 2, the commit just before this change. With the change, reading a List<int> went from 17.74 to 4.74 ms, a List<int?> with NULLs from 28.78 to 6.26 ms, and a MAP read as a Dictionary<int, string> from 22.46 to 10.17 ms:

Method Job Mean Median Ratio Allocated Alloc Ratio
ReadArrayAsListOfInt 1-1.5.6 20.89 ms 20.76 ms 1.00 30.52 MB 1.00
ReadArrayAsListOfInt 2-cedc176 17.76 ms 17.74 ms 0.85 30.52 MB 1.00
ReadArrayAsListOfInt 3-d9bf172 4.76 ms 4.74 ms 0.23 15.26 MB 0.50
ReadListWithNullsAsListOfNullableInt 1-1.5.6 32.74 ms 32.44 ms 1.00 45.78 MB 1.00
ReadListWithNullsAsListOfNullableInt 2-cedc176 28.76 ms 28.78 ms 0.88 45.78 MB 1.00
ReadListWithNullsAsListOfNullableInt 3-d9bf172 6.28 ms 6.26 ms 0.19 18.32 MB 0.40
ReadArrayAsListOfLong 1-1.5.6 37.53 ms 37.76 ms 1.00 85.46 MB 1.00
ReadArrayAsListOfLong 2-cedc176 31.72 ms 31.59 ms 0.85 85.46 MB 1.00
ReadArrayAsListOfLong 3-d9bf172 21.93 ms 21.75 ms 0.58 79.35 MB 0.93
ReadStructAsClass 1-1.5.6 16.61 ms 16.64 ms 1.00 28.23 MB 1.00
ReadStructAsClass 2-cedc176 14.78 ms 14.78 ms 0.89 28.23 MB 1.00
ReadStructAsClass 3-d9bf172 9.31 ms 9.27 ms 0.56 23.66 MB 0.84
ReadStructAsDictionary 1-1.5.6 16.57 ms 16.57 ms 1.00 61.80 MB 1.00
ReadStructAsDictionary 2-cedc176 16.05 ms 15.98 ms 0.97 61.81 MB 1.00
ReadStructAsDictionary 3-d9bf172 15.20 ms 15.29 ms 0.92 57.23 MB 0.93
ReadMapAsDictionary 1-1.5.6 22.97 ms 23.00 ms 1.00 60.28 MB 1.00
ReadMapAsDictionary 2-cedc176 22.51 ms 22.46 ms 0.98 60.28 MB 1.00
ReadMapAsDictionary 3-d9bf172 10.32 ms 10.17 ms 0.45 52.65 MB 0.87

As you can see, the other three reads changed much less. A List<long> read from an INTEGER column went from 31.59 to 21.75 ms, a STRUCT read into a class from 14.78 to 9.27 ms, and a STRUCT read as a Dictionary<string, object> only from 15.98 to 15.29 ms. Every item of a list whose type differs from the type stored, every field of a struct and every key and value of a map is still read as an object and boxed, and such a list is still created with Activator and grows as items are added. Reading them the typed way changes what some reads return, so I left that for DuckDB.NET 2.0.

What’s next

The last post of the series explains the wait that showed up four times and how to find such problems yourself. We saw it in List<int?> in part 2, in the wide decimal read and the decimal append in part 3, and in the nullable function result in this post. All the changes in this series are in DuckDB.NET 1.5.6.1 on , and they carry over to . To upgrade, run:

dotnet add package DuckDB.NET.Data.Full --version 1.5.6.1

DuckDB.NET.Data.Full includes the native DuckDB library. If you supply the library yourself, use DuckDB.NET.Data instead.

Read the whole story
alvinashcraft
36 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Types of SQL Server Triggers

1 Share

Learn about SQL trigger types and their powerful capabilities within SQL Server and Azure SQL for automated processes.

The post Types of SQL Server Triggers appeared first on MSSQLTips.com.

Read the whole story
alvinashcraft
48 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Paging in SQL Server: Five Methods, Tested Like for Like

1 Share

Paging in SQL Server, done five ways against the same 1,200,000 rows, the same sort, and the same page size. Every completed method produced the same checksum at each depth, which checks consistency without proving row-by-row equality. Then I counted the reads.

Five identical test rigs on a laboratory bench, each holding a printed query for paging in SQL Server, photographed in the flat even light of a product test.

Every application pages. Most do it the way the first tutorial showed them, and never measure it again.

So I measured it. Same table, same order, page 1, page 1,000 and page 20,000.

How we tested paging in SQL Server

A 1,200,000 row orders table on SQL Server 2025, with a nonclustered index on OrderDate. Sort order OrderDate descending, then OrderID descending, so every page is deterministic.

Page size 50. Three depths: page 1, page 1,000 (skip 49,950 rows) and page 20,000 (skip 999,950 rows).

Each method lives in its own stored procedure. Each was warmed once, then measured on logical reads and CPU. Five methods completed page 1 and their results checksummed the same. Four completed the deeper pages, with matching checksums again.

A matching checksum is a consistency check, not a proof that every row was identical. Double TOP didn’t finish the deeper pages at all. That’s a result, and it’s in the table.

The five methods

OFFSET and FETCH. The modern syntax. ORDER BY ... OFFSET @skip ROWS FETCH NEXT 50 ROWS ONLY.

ROW_NUMBER. The pre-2012 way. Number every row in a CTE, then filter on the number.

Keyset. Remember the last row of the previous page and seek past it. WHERE OrderDate < @lastDate OR (OrderDate = @lastDate AND OrderID < @lastId), then TOP (50).

Double TOP. The old trick: TOP (50) ... WHERE OrderID NOT IN (SELECT TOP (@skip) OrderID ...).

Cursor. A static cursor over the whole ordered set, FETCH ABSOLUTE to the start row, then fifty FETCH NEXT.

The ratings

Method Page 1 Page 1,000 Page 20,000 Verdict
Keyset 168 reads, 0 ms 159 reads, 0 ms 159 reads, 0 ms Recommended
OFFSET / FETCH 156 reads, 0 ms 153,233 reads, 109 ms 3,064,485 reads, 1,391 ms Shallow pages only
ROW_NUMBER 156 reads, 0 ms 153,233 reads, 93 ms 3,064,485 reads, 1,797 ms Same as OFFSET
Double TOP 156 reads, 0 ms did not finish in 120 s not attempted Not acceptable
Cursor 20,370 + 3,495,750 worktable, 3,875 ms 20,370 + 3,495,750 worktable, 3,360 ms 20,370 + 3,495,750 worktable, 3,375 ms Not acceptable

Every cell uses the same scope. Logical reads on the orders table from STATISTICS IO, plus the tempdb worktable where the cursor keeps its copy. CPU is that statement’s alone. The earlier draft of this table mixed in bookkeeping reads and a neighbouring query’s CPU. This one doesn’t.

A product test style line chart with page depth along the bottom and logical reads up the side. Two lines climb steeply, the keyset line stays flat and low, the cursor line stays flat and high at three and a half million, and double TOP appears only at page one.

What the numbers say

Keyset is flat. Page 1 and page 20,000 cost the same. The seek starts where the last page ended and reads 50 rows. That’s the whole trick.

OFFSET and ROW_NUMBER climb in a straight line. To skip 999,950 rows they read all 999,950 rows and threw them away. Page 20,000 cost about 19,600 times the reads of page 1.

They behave identically because the optimiser turns them into nearly the same plan. Choose OFFSET for the cleaner syntax and know what it does.

Double TOP is the one to remove from any code you still own. At page 1,000 it ran for 800 seconds and 10 million reads before I killed it the first time. On the rerun I gave it 120 seconds and it didn’t make it.

The cursor is a different kind of wrong. It costs 3.5 million reads on every page, including page 1. A static cursor copies the entire ordered result into tempdb before it fetches anything.

The catch with OFFSET

One thing the ratings table can’t show. OFFSET’s cost depends on which page the plan was compiled for.

The 3,064,485 reads above came from a plan compiled for page 1 and reused for page 20,000. It walks the date index and looks up every row on the way past.

I then forced a recompile at page 20,000 and captured the plan. The optimiser chose a parallel scan and a sort: 25,370 reads and 1,871 ms of CPU. Reused from page 1 in the same session, the lookup plan did 2,876,967 reads and 2,115 ms.

So the reads fall by a hundredfold and the CPU barely moves. Sorting a million rows costs what it costs. OFFSET is parameter sensitive in its reads, and expensive at depth either way.

What keyset costs you

It isn’t free. You can’t jump to page 20,000 directly, because you need the last row of page 19,999. It suits “next page” and infinite scroll, not “go to page 500”.

The sort key must be unique, which is why OrderID is in there. And the index has to match the sort, or the seek turns into a scan.

For a customer paging through their own orders, none of that matters. That’s most paging.

Recommendation

Keyset for anything a user scrolls through. OFFSET for admin screens where nobody goes past page ten, with an index that matches the ORDER BY.

Delete the double TOP wherever you find it. Delete the cursor twice.

If your application pages a large table and nobody has measured the method, that’s a two-hour job I’d enjoy.

Page depth is not a small number, it is the number of rows you agreed to read and discard.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.

First appeared on Paging in SQL Server: Five Methods, Tested Like for Like

Read the whole story
alvinashcraft
52 seconds ago
reply
Pennsylvania, USA
Share this story
Delete
Next Page of Stories