diff --git a/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj b/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj
index 28d1c7e2..ca82ae78 100644
--- a/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj
+++ b/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj
@@ -7,8 +7,10 @@
false
true
- $(NoWarn);CA1707;CA1861
+ arrays in assertions are fine in tests. The DevProxy reference brings in the
+ VS threading analyzers, whose VSTHRD003/VSTHRD202 rules flag test methods that
+ await helpers or tasks they didn't start. -->
+ $(NoWarn);CA1707;CA1861;VSTHRD003;VSTHRD202
@@ -37,6 +39,7 @@
+
diff --git a/DevProxy.Integration.Tests/FakeOrigin.cs b/DevProxy.Integration.Tests/FakeOrigin.cs
index 034d6201..a5c50395 100644
--- a/DevProxy.Integration.Tests/FakeOrigin.cs
+++ b/DevProxy.Integration.Tests/FakeOrigin.cs
@@ -29,6 +29,8 @@ namespace DevProxy.Integration.Tests;
/// GET /big/{n} → 200, n bytes of 'A' (large finite body)
/// GET /json → 200 application/json, a 2-element array
/// GET /socket-b → WebSocket sends "rewritten"
+/// * /abort → aborts the connection without a response
+/// * /delay/{ms} → 200 "delayed" after {ms} milliseconds
///
///
internal sealed class FakeOrigin : IAsyncDisposable
@@ -50,7 +52,11 @@ private FakeOrigin(WebApplication app, int port, System.Collections.Concurrent.C
_received = received;
}
- public static async Task StartAsync()
+ ///
+ /// Whether to record received requests in . Turn off for
+ /// high-volume tests, where the recording would grow memory with every request.
+ ///
+ public static async Task StartAsync(bool recordRequests = true)
{
var port = NetUtil.GetFreePort();
var builder = WebApplication.CreateEmptyBuilder(new WebApplicationOptions());
@@ -67,7 +73,10 @@ public static async Task StartAsync()
var received = new System.Collections.Concurrent.ConcurrentQueue();
app.Use(async (ctx, next) =>
{
- received.Enqueue(new ReceivedRequest(ctx.Request.Method, ctx.Request.Path + ctx.Request.QueryString));
+ if (recordRequests)
+ {
+ received.Enqueue(new ReceivedRequest(ctx.Request.Method, ctx.Request.Path + ctx.Request.QueryString));
+ }
await next().ConfigureAwait(false);
});
@@ -120,6 +129,14 @@ public static async Task StartAsync()
new { id = 2, name = "beta" },
}));
+ app.Map("/abort", (HttpContext ctx) => ctx.Abort());
+
+ app.Map("/delay/{ms:int}", async (int ms, HttpContext ctx) =>
+ {
+ await Task.Delay(ms, ctx.RequestAborted).ConfigureAwait(false);
+ return Results.Text("delayed");
+ });
+
app.Map("/socket-b", async context =>
{
if (!context.WebSockets.IsWebSocketRequest)
diff --git a/DevProxy.Integration.Tests/MemoryRetentionTests.cs b/DevProxy.Integration.Tests/MemoryRetentionTests.cs
new file mode 100644
index 00000000..7fccb9db
--- /dev/null
+++ b/DevProxy.Integration.Tests/MemoryRetentionTests.cs
@@ -0,0 +1,656 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Concurrent;
+using System.Globalization;
+using System.Net;
+using System.Runtime.CompilerServices;
+using System.Text;
+using DevProxy.Abstractions.Plugins;
+using DevProxy.Abstractions.Proxy;
+using DevProxy.Commands;
+using DevProxy.Logging;
+using DevProxy.Plugins.Mocking;
+using DevProxy.Proxy;
+using DevProxy.Proxy.Kestrel;
+using DevProxy.Proxy.Kestrel.Internal;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Logging.Console;
+using Microsoft.Extensions.Options;
+using Xunit;
+using Xunit.Abstractions;
+
+namespace DevProxy.Integration.Tests;
+
+///
+/// Checks that Dev Proxy doesn't keep memory alive across proxied requests and hot
+/// reloads. The checks use where the retained objects are
+/// reachable, so they're exact, and otherwise compare the managed heap after a forced
+/// full collection, which is stable on CI runners where timing isn't.
+///
+/// Each check has a canary test that adds a deliberate leak (a plugin that appends
+/// every request or generation to a static list) and asserts the check catches it, so
+/// the checks can't silently pass because they measure nothing.
+///
+public sealed class MemoryRetentionTests(ITestOutputHelper output)
+{
+ private const string HotReloadSkipReason =
+ "One stopped hot-reload generation remains reachable with the process-wide SystemProxySession.";
+
+ private const string FailedRequestsSkipReason =
+ "Request logs of failed and cancelled requests stay buffered on main. Passes with https://github.com/dotnet/dev-proxy/pull/2151.";
+
+ private const int HotReloadGenerations = 20;
+
+ // Allows for pools that keep growing towards their peak use long after warm-up.
+ // Heap snapshots show 10,000-30,000 requests adding 2-4 MB, nearly all of it 4 KB
+ // blocks in Kestrel's memory pool. A leak of one small object per request would
+ // stay under it, which is why the tests also track sessions with weak references.
+ private const long AllowedGrowthBytes = 8 * 1024 * 1024;
+
+ private static readonly HttpClient SharedHttpClient = new();
+ private static readonly TestProxyConfiguration ProxyConfig = new();
+
+ private readonly ITestOutputHelper _output = output;
+
+ // Skipped until the remaining hot-reload retention is fixed.
+#pragma warning disable xUnit1004
+ [Fact(Skip = HotReloadSkipReason)]
+#pragma warning restore xUnit1004
+ public async Task HotReload_ReleasesPreviousGenerations()
+ {
+ var result = await MeasureHotReloadAsync(HotReloadGenerations, leakGenerations: false);
+
+ Assert.True(
+ result.RetainedGenerations == 0,
+ $"{result.RetainedGenerations} of {result.Generations} hot-reload generations are still reachable after a full collection ({result.RetainedObjects}).");
+ }
+
+ [Fact]
+ public async Task HotReload_DetectsGenerationsHeldByALeak()
+ {
+ var result = await MeasureHotReloadAsync(generations: 3, leakGenerations: true);
+
+ Assert.Equal(result.Generations, result.RetainedGenerations);
+ }
+
+ [Fact]
+ public async Task Requests_DoNotRetainMemory()
+ {
+ var result = await MeasureRequestsAsync(
+ RequestMix.Successful, warmupRequests: 1_000, measuredRequests: 10_000, leakSessions: false);
+
+ Assert.True(
+ result.RetainedSessions == 0,
+ $"{result.RetainedSessions} of {result.TrackedSessions} proxy sessions are still reachable after their requests completed.");
+ Assert.True(
+ result.GrowthBytes < AllowedGrowthBytes,
+ $"The managed heap grew by {result.GrowthBytes:N0} bytes over {result.MeasuredRequests:N0} requests; allowed: {AllowedGrowthBytes:N0}.");
+ }
+
+ // Skipped until the linked fix merges; remove the skip and the suppression then.
+#pragma warning disable xUnit1004
+ [Fact(Skip = FailedRequestsSkipReason)]
+#pragma warning restore xUnit1004
+ public async Task FailedAndCancelledRequests_DoNotRetainMemory()
+ {
+ var result = await MeasureRequestsAsync(
+ RequestMix.FailedAndCancelled, warmupRequests: 200, measuredRequests: 1_000, leakSessions: false);
+
+ Assert.True(
+ result.RetainedSessions == 0,
+ $"{result.RetainedSessions} of {result.TrackedSessions} proxy sessions are still reachable after their requests failed or were cancelled.");
+ Assert.True(
+ result.GrowthBytes < AllowedGrowthBytes,
+ $"The managed heap grew by {result.GrowthBytes:N0} bytes over {result.MeasuredRequests:N0} requests; allowed: {AllowedGrowthBytes:N0}.");
+ }
+
+ [Fact]
+ public async Task Requests_DetectSessionsHeldByALeak()
+ {
+ var result = await MeasureRequestsAsync(
+ RequestMix.Successful, warmupRequests: 100, measuredRequests: 1_000, leakSessions: true);
+
+ Assert.Equal(result.TrackedSessions, result.RetainedSessions);
+ Assert.True(
+ result.GrowthBytes >= AllowedGrowthBytes,
+ $"A plugin that keeps every session grew the managed heap by only {result.GrowthBytes:N0} bytes; the check needs at least {AllowedGrowthBytes:N0} to catch it.");
+ }
+
+ #region Hot reload
+
+ private sealed record HotReloadResult(int Generations, int RetainedGenerations, string RetainedObjects);
+
+ private async Task MeasureHotReloadAsync(int generations, bool leakGenerations)
+ {
+ await using var origin = await FakeOrigin.StartAsync(recordRequests: false);
+ var configDir = Directory.CreateTempSubdirectory("devproxy-memory-");
+ var configPath = Path.Combine(configDir.FullName, "devproxyrc.json");
+ await File.WriteAllTextAsync(Path.Combine(configDir.FullName, "mocks.json"), MocksFile(origin.Host));
+ await File.WriteAllTextAsync(configPath, ConfigFile(origin.Host, generation: 0));
+
+ string[] args = [DevProxyCommand.ConfigFileOptionName, configPath];
+ var options = new DevProxyConfigOptions();
+ options.ParseOptions(args);
+ var proxyEnvironment = new HttpProxyEnvironment();
+ var systemProxySession = new SystemProxySession();
+ // Starting the host creates the root and leaf certificates, so keep them in the
+ // temp folder instead of the user's Dev Proxy folder.
+ var rootCertPath = Path.Combine(configDir.FullName, "rootCert.pfx");
+ var leafCertDirectory = Path.Combine(configDir.FullName, "certificates");
+
+ var generationRefs = new List();
+ try
+ {
+ for (var generation = 1; generation <= generations; generation++)
+ {
+ generationRefs.Add(await RunGenerationAsync(
+ args, options, proxyEnvironment, systemProxySession, configPath, rootCertPath, leafCertDirectory,
+ origin.Host, generation, leakGenerations));
+ }
+
+ await CollectUntilAsync(() => generationRefs.All(g => !g.IsAlive));
+ var retained = generationRefs.Where(g => g.IsAlive).ToArray();
+ var retainedObjects = string.Join(
+ ", ",
+ retained.SelectMany(g => g.AliveObjects()).GroupBy(n => n).Select(g => $"{g.Key} x{g.Count()}"));
+
+ _output.WriteLine($"Hot-reload generations checked: {generations}");
+ _output.WriteLine($"Hot-reload generations retained: {retained.Length}");
+ if (retained.Length > 0)
+ {
+ _output.WriteLine($"Retained objects: {retainedObjects}");
+ }
+
+ return new(generations, retained.Length, retainedObjects);
+ }
+ finally
+ {
+ LeakedGenerations.Clear();
+ ConfigFileWatcher.Reset();
+ try
+ {
+ configDir.Delete(recursive: true);
+ }
+ catch (IOException)
+ {
+ // A late file watcher can still hold the folder; it's a temp folder.
+ }
+ }
+ }
+
+ /// The deliberate leak for the hot-reload canary.
+ private static readonly List