Skip to content

Grow QPackDecoder's Huffman buffers using ArrayPool - #138229

Open
asylkhan-azat wants to merge 2 commits into
dotnet:mainfrom
asylkhan-azat:system-net-http-huffman-pool-grow
Open

asylkhan-azat wants to merge 2 commits into
dotnet:mainfrom
asylkhan-azat:system-net-http-huffman-pool-grow

Conversation

@asylkhan-azat

Copy link
Copy Markdown
Contributor

This PR builds on this PR. Without it the decoder's buffers are never returned to the pool, so only part of the saving shows. The most wins come from dispose returning arrays to pool + renting when doubling the arrays of the decoder.

When a Huffman-coded header value doesn't fit the rented buffer, Huffman.Decode grows it with Array.Resize. The rented array is dropped and the new one is not from the pool. The QPackDecoder already rents from the pool, so it can return old used pool and grow from it

Benchmarks and results are here:

Details

I've run this benchmark:

[MemoryDiagnoser]
public class Http3HuffmanHeaders
{
    private HttpClient _client = null!;

    [GlobalSetup]
    public void Setup()
    {
        var handler = new SocketsHttpHandler();
        handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
        _client = new HttpClient(handler)
        {
            BaseAddress = new Uri("<loopback server>"),
            DefaultRequestVersion = HttpVersion.Version30,
            DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact,
        };
    }

    [GlobalCleanup]
    public void Cleanup() => _client.Dispose();

    [Benchmark]
    public async Task Get()
    {
        using HttpResponseMessage response = await _client.GetAsync("/");
    }
}

On this simple loopback server:

public static class Program
{
    private static readonly HttpHeaderData[] ResponseHeaders =
    {
        new("content-type", "application/json; charset=utf-8", huffmanEncoded: true),
        new("date", "Tue, 24 Nov 2026 22:10:00 GMT", huffmanEncoded: true),
        new("server", "bench-server/1.0", huffmanEncoded: true),
        new("cache-control", "private, max-age=0", huffmanEncoded: true),
        new("strict-transport-security", "max-age=31536000; includeSubDomains", huffmanEncoded: true),
        new("set-cookie", "session=" + new string('s', 64) + "; Path=/; Expires=Wed, 25 Nov 2026 22:00:00 GMT; Secure; HttpOnly; SameSite=Lax", huffmanEncoded: true),
        new("x-request-id", "4f1c2a7e-9b3d-4e8a-a1c5-7d2e9f0b6c13", huffmanEncoded: true),
    };

    public static async Task Main()
    {
        using var server = new Http3LoopbackServer();
        Console.WriteLine(server.Address);

        while (true)
        {
            var connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
            _ = Task.Run(() => ServeAsync(connection));
        }
    }

    private static async Task ServeAsync(Http3LoopbackConnection connection)
    {
        await using (connection)
        {
            try
            {
                while (true)
                {
                    await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
                    await stream.HandleRequestAsync(headers: ResponseHeaders);
                }
            }
            catch (Exception)
            {
            }
        }
    }
}

Results:

Method Job Mean Error StdDev Ratio Gen0 Allocated Alloc Ratio
Get with-pool 163.7 us 1.90 us 1.78 us 1.03 - 7.52 KB 0.93
Get without-pool 159.5 us 1.55 us 1.45 us 1.00 0.4883 8.09 KB 1.00

There is slight reduction o nthe execution time, but across several runs the ratio was changing between 0.98-1.03, so I suspect that it's a noise

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 24, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 4 pipeline(s).
11 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @karelz, @dotnet/ncl
See info in area-owners.md if you want to be subscribed.

@ManickaP

Copy link
Copy Markdown
Member

I don't know if you're aware, but this code is also used in ASP.NET (we share it as sources, not binaries).
And Kestrel also doesn't dispose the qpackdecoder.

@ManickaP

Copy link
Copy Markdown
Member

cc @BrennanConroy @rokonec

@asylkhan-azat

Copy link
Copy Markdown
Contributor Author

I don't know if you're aware, but this code is also used in ASP.NET (we share it as sources, not binaries). And Kestrel also doesn't dispose the qpackdecoder.

Yeah, that's why the parameter is nullable and optional. If you mean that for the shared code, tehre is a different process for the PR's, then I didn't knew and sorry :)

@ManickaP

Copy link
Copy Markdown
Member

AFAIK, the shared code is propagated back and forth automatically.

I'm more interested if you've looked at Kestrel side and decided it's not valuable there, or you plan to follow up there, or you weren't aware of the code sharing.

return j;
}

private static void Grow(ref byte[] dstArray, ArrayPool<byte>? pool)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO a bool to pick whether to pool or not would be better than a pool arg here, the only pool type that's ever used in practice here is ArrayPool.Shared

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason on why I went with pool arg was that the caller code on the decoder side held the pool as static field, which I'm passing here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, should I go with boolean or the pool itself?

@asylkhan-azat

asylkhan-azat commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

AFAIK, the shared code is propagated back and forth automatically.

I'm more interested if you've looked at Kestrel side and decided it's not valuable there, or you plan to follow up there, or you weren't aware of the code sharing.

I was aware that this is shared, but just went with the minimal amount of code in 1 repo to see if it wins anything. Not sure if the Kestrel rents from the pools too


byte[] newArray = pool.Rent(dstArray.Length * 2);
dstArray.AsSpan().CopyTo(newArray);
pool.Return(dstArray);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concurrent calls from multiple threads could result in a double-free, leading to a memory safety violation. Does the calling code guarantee the necessary synchronization to prevent this? Could a threading bug in user code trigger a double-free here?

@asylkhan-azat asylkhan-azat Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The QPackDecoder does sync the rented array returning. I'll see if aspnetcore call sites do sync those

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I'm back from digging into ASP.NET Core and HttpClient.

This doesn't add "new" risk.

Only QPackDecoder passes the pool, and it already rents and returns these same buffers in EnsureStringCapacity. Kestrel uses the same decoder (though it never disposes it, so its last buffers never go back to the pool), but it calls it from a single read loop per stream, so concurrent calls can't happen there.

On the client side, a double return is possible if user code reads the response stream from two threads, and that could corrupt data. But that risk was already there. _recvBuffer grows the same way. It rents a bigger array and returns old one. So the same concurrent reads could already return an array twice. This change uses the same pattern that's already in place. That's why it's not "new" risk

I tried to reproduce it with Claude, with two threads reading one HTTP/3 response stream that has huffman coded trailers. The process crashed first with InvalidOperationException from the QUIC stream, because it doesn't allow two pending reads. A double return would need both threads to work on data that's already buffered at the same moment, which is a very small window.

And honestly, I'm not sure what we'll should do. AFAIK, the Stream contract says it isn't safe to access it concurrently, so code like that already breaks the contract. If we need to prevent data corruption even when user code misuses the Stream and reads it from two threads, we would need to change ArrayBuffer too or ditch the pooling approach.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem is that array pool issues like this turn a local problem (e.g. single request fails with an exception) into a global process corruption (unrelated components that use array pool start misbehaving).

I agree that the existing array pool use looks problematic. The question is whether fixing this code can turn a minor problem into a serious problem. It is very hard to reason about it.

cc @EgorBo

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Net.Http community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants