From b1d018848bd2dafff3e5cdb4b201f4592410eab3 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Tue, 10 Nov 2026 03:13:52 +0000 Subject: [PATCH 1/2] Measure synchronous release batch allocations for #349 --- .github/scripts/frozen_concurrent_control.py | 13 ++++++- .../scripts/test_frozen_concurrent_control.py | 30 +++++++++++++++ .github/workflows/frozen-fixture-control.yml | 8 ++++ tools/FrozenFixtureProbe/Program.cs | 37 +++++++++++++------ website/docs/contributing/performance.md | 12 ++++++ 5 files changed, 86 insertions(+), 14 deletions(-) diff --git a/.github/scripts/frozen_concurrent_control.py b/.github/scripts/frozen_concurrent_control.py index a0b90fa74..e3fa50957 100644 --- a/.github/scripts/frozen_concurrent_control.py +++ b/.github/scripts/frozen_concurrent_control.py @@ -28,10 +28,14 @@ def main(): parser.add_argument("--profile-reader", type=Path) parser.add_argument("--exact-invocations", action="store_true", help="Separate instrumented fixture control using synchronous thread-local counters.") + parser.add_argument("--exact-releases", action="store_true", + help="Separate exact calling-thread counts around each eight-write release batch.") args = parser.parse_args() + if args.exact_invocations and args.exact_releases: + parser.error("Exact handler and release counters require separate ABBAs") if bool(args.trace_tool) != bool(args.profile_reader): parser.error("--trace-tool and --profile-reader must be supplied together") - if args.exact_invocations and args.trace_tool: + if (args.exact_invocations or args.exact_releases) and args.trace_tool: parser.error("Exact invocation counters and sampled profiles require separate ABBAs") args.output.mkdir(parents=True, exist_ok=False) builds = args.artifact / "performance-builds" @@ -40,8 +44,11 @@ def main(): "warmup_batches": 4096, "measured_batches": 32768, "messages_per_batch": 8, "counter": "GC.GetTotalAllocatedBytes(true)", "limits": "Inclusive fixed-count control; not original BDN replay, allocation-owner attribution, throughput equivalence or native-client budget evidence."} - protocol["instrumented"] = args.trace_tool is not None or args.exact_invocations + protocol["instrumented"] = args.trace_tool is not None or args.exact_invocations or args.exact_releases protocol["exact_invocations"] = args.exact_invocations + protocol["exact_releases"] = args.exact_releases + if args.exact_releases: + protocol["release_boundary"] = "Eight synchronous Release.Writer.TryWrite calls per record; no await. Calling-thread work only, not historical allocation attribution." if args.exact_invocations: protocol["invocation_counter"] = "GC.GetAllocatedBytesForCurrentThread()" protocol["invocation_boundary"] = "Synchronous cached handler call only; no await between counter reads. Excludes other threads and subsequent continuations; does not identify object types or the historical delta." @@ -57,6 +64,8 @@ def main(): command = ["dotnet", str(args.probe.resolve()), str(images[0].parent.resolve())] if args.exact_invocations: command.append("--exact-invocations") + if args.exact_releases: + command.append("--exact-releases") trace = args.output / f"{index + 1}-{side}.nettrace" if args.trace_tool: command = [str(args.trace_tool.resolve()), "collect", "--profile", "gc-verbose", diff --git a/.github/scripts/test_frozen_concurrent_control.py b/.github/scripts/test_frozen_concurrent_control.py index 2f843b6cd..672a19f32 100644 --- a/.github/scripts/test_frozen_concurrent_control.py +++ b/.github/scripts/test_frozen_concurrent_control.py @@ -98,12 +98,42 @@ def test_exact_invocations_use_separate_processes_and_protocol(self): self.assertTrue(protocol["instrumented"]) self.assertTrue(protocol["exact_invocations"]) + def test_exact_releases_use_separate_processes_and_protocol(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for side in ("baseline", "candidate", "baseline-after"): + image = root / "performance-builds" / side / "builds/net10.0/Relayer.Benchmarks-DefaultJob-1/bin/Release/net10.0/Relayer.Benchmarks.dll" + image.parent.mkdir(parents=True) + image.touch() + output = root / "results" + arguments = ["control", str(root), str(root / "probe.dll"), str(output), "--exact-releases"] + with patch("sys.argv", arguments), patch("frozen_concurrent_control.verify", return_value="frozen"), patch("frozen_concurrent_control.subprocess.run") as execute: + main() + self.assertEqual(execute.call_count, 4) + for call in execute.call_args_list: + self.assertEqual(call.args[0][-1], "--exact-releases") + self.assertNotIn("collect", call.args[0]) + protocol = json.loads((output / "protocol.json").read_text()) + self.assertTrue(protocol["instrumented"]) + self.assertTrue(protocol["exact_releases"]) + + def test_release_counters_reject_combined_sampled_profiles(self): + arguments = ["control", "inputs", "probe.dll", "output", "--exact-releases", + "--trace-tool", "dotnet-trace", "--profile-reader", "reader.dll"] + with patch("sys.argv", arguments), self.assertRaises(SystemExit): + main() + def test_exact_counters_reject_combined_sampled_profiles(self): arguments = ["control", "inputs", "probe.dll", "output", "--exact-invocations", "--trace-tool", "dotnet-trace", "--profile-reader", "reader.dll"] with patch("sys.argv", arguments), self.assertRaises(SystemExit): main() + def test_rejects_combining_exact_regions(self): + arguments = ["control", "inputs", "probe.dll", "output", "--exact-invocations", "--exact-releases"] + with patch("sys.argv", arguments), self.assertRaises(SystemExit): + main() + def test_profile_extracts_all_launches_and_removes_successful_raw_captures(self): self.run_profile(False) diff --git a/.github/workflows/frozen-fixture-control.yml b/.github/workflows/frozen-fixture-control.yml index 5b981eb50..1e35c9f16 100644 --- a/.github/workflows/frozen-fixture-control.yml +++ b/.github/workflows/frozen-fixture-control.yml @@ -64,6 +64,14 @@ jobs: python3 .github/scripts/frozen_concurrent_control.py "inputs/$run" tools/FrozenFixtureProbe/bin/Release/net10.0/FrozenFixtureProbe.dll "results/$run-exact-invocations" --exact-invocations || failed=1 done exit "$failed" + - name: Run separate exact release batch ABBA + if: always() + run: | + failed=0 + for run in 42306276036 42312305889; do + python3 .github/scripts/frozen_concurrent_control.py "inputs/$run" tools/FrozenFixtureProbe/bin/Release/net10.0/FrozenFixtureProbe.dll "results/$run-exact-releases" --exact-releases || failed=1 + done + exit "$failed" - name: Retain all outcomes and executable inputs if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/tools/FrozenFixtureProbe/Program.cs b/tools/FrozenFixtureProbe/Program.cs index 5781f81c9..79a1553d9 100644 --- a/tools/FrozenFixtureProbe/Program.cs +++ b/tools/FrozenFixtureProbe/Program.cs @@ -6,9 +6,10 @@ using Relayer.Diagnostics; // Diagnostic only. Bind the original handler once; never rebuild historical workload assemblies. -if (args.Length is < 1 or > 2 || (args.Length == 2 && args[1] != "--exact-invocations")) - throw new ArgumentException("Expected the retained benchmark dependency directory and optional --exact-invocations."); -var exactInvocations = args.Length == 2; +if (args.Length is < 1 or > 2 || (args.Length == 2 && args[1] is not ("--exact-invocations" or "--exact-releases"))) + throw new ArgumentException("Expected the retained benchmark dependency directory and optional --exact-invocations or --exact-releases."); +var exactInvocations = args.Length == 2 && args[1] == "--exact-invocations"; +var exactReleases = args.Length == 2 && args[1] == "--exact-releases"; var image = Path.GetFullPath(args[0]); var context = new AssemblyLoadContext("Frozen", isCollectible: false); context.Resolving += (_, name) => @@ -25,12 +26,12 @@ var handler = Activator.CreateInstance(handlerType, signals)!; var run = (Func)typeof(FixtureControl).GetMethod(nameof(FixtureControl.Measure))! .MakeGenericMethod(parameters[0].ParameterType, parameters[1].ParameterType) - .Invoke(null, [image, handler, method, signals, exactInvocations])!; + .Invoke(null, [image, handler, method, signals, exactInvocations, exactReleases])!; await run(); static class FixtureControl { - public static Func Measure(string image, object handler, MethodInfo method, object signals, bool exactInvocations) + public static Func Measure(string image, object handler, MethodInfo method, object signals, bool exactInvocations, bool exactReleases) { var invoke = method.CreateDelegate>(handler); var message = (TMessage)Activator.CreateInstance(typeof(TMessage), 42)!; @@ -38,6 +39,14 @@ public static Func Measure(string image, object handle var entered = (Channel)type.GetProperty("Entered")!.GetValue(signals)!; var release = (Channel)type.GetProperty("Release")!.GetValue(signals)!; var completed = (Channel)type.GetProperty("Completed")!.GetValue(signals)!; + // Cache the delegate before warmup. The region includes all eight synchronous writes, + // including native completion scheduling on this thread; never await inside it. + Func releaseBatch = (_, _, _) => + { + for (var i = 0; i < 8; i++) + if (!release.Writer.TryWrite(0)) throw new InvalidOperationException("Release channel is full."); + return ValueTask.CompletedTask; + }; return Run; async Task Run() @@ -46,7 +55,7 @@ async Task Run() var pending = new ValueTask[8]; const int warmupBatches = 4096; const int measuredBatches = 32768; - var invocations = exactInvocations ? new InvocationAllocations(measuredBatches * 8) : null; + var invocations = exactInvocations || exactReleases ? new InvocationAllocations(measuredBatches * (exactReleases ? 1 : 8)) : null; for (var i = 0; i < warmupBatches; i++) await Batch(); GC.Collect(); GC.WaitForPendingFinalizers(); @@ -64,14 +73,15 @@ async Task Run() if (invocations is not null) invocations.Enabled = false; if (sum != measuredBatches * 8L * 42) throw new InvalidOperationException($"Unexpected sum: {sum}."); var invocationReport = invocations?.Report(); - if (invocationReport is not null && invocationReport.Invocations != measuredBatches * 8) + if (invocationReport is not null && invocationReport.Invocations != measuredBatches * (exactReleases ? 1 : 8)) throw new InvalidOperationException("Exact invocation count does not match the measured workload."); Console.WriteLine(JsonSerializer.Serialize(new { image, control = "original-handler-and-signal-channels", warmupBatches, measuredBatches, - instrumentation = exactInvocations ? "exact-synchronous-invocations" : "none", + instrumentation = exactReleases ? "exact-synchronous-release-batches" : exactInvocations ? "exact-synchronous-invocations" : "none", + exactRegion = exactReleases ? "Eight synchronous Release.Writer.TryWrite calls per record; includes calling-thread native completion scheduling, excludes other threads and later continuations." : "One synchronous handler delegate call per record.", invocationAllocations = invocationReport, - invocationLimits = "Exact bytes on the calling thread during the synchronous handler invocation only. Excludes continuations after suspension, other threads and the diagnostic driver. Includes original handler and called channel/runtime work; no exact type attribution or historical end-to-end delta attribution. Instrumentation changes scheduling; compare only within this separate ABBA.", + invocationLimits = exactReleases ? "Exact bytes on the calling thread for the whole synchronous eight-write release batch only. No exact type attribution or historical delta attribution; do not subtract from inclusive totals. Recording changes scheduling; compare within this separate ABBA only." : "Exact bytes on the calling thread during the synchronous handler invocation only. Excludes continuations after suspension, other threads and the diagnostic driver. Includes original handler and called channel/runtime work; no exact type attribution or historical end-to-end delta attribution. Instrumentation changes scheduling; compare only within this separate ABBA.", messages = measuredBatches * 8, bytes, bytesPerMessage = bytes / (measuredBatches * 8.0), seconds, runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, arch = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString(), @@ -83,14 +93,17 @@ async ValueTask Batch() { for (var i = 0; i < pending.Length; i++) { - pending[i] = invocations is null + pending[i] = invocations is null || exactReleases ? invoke(message, default!, limit.Token) : invocations.Invoke(invoke, message, default(TContext)!, limit.Token); if (pending[i].IsCompleted) throw new InvalidOperationException("Handler must await release."); } for (var i = 0; i < pending.Length; i++) await entered.Reader.ReadAsync(limit.Token); - for (var i = 0; i < pending.Length; i++) - if (!release.Writer.TryWrite(0)) throw new InvalidOperationException("Release channel is full."); + if (exactReleases) + _ = invocations!.Invoke(releaseBatch, 0, 0, limit.Token); + else + for (var i = 0; i < pending.Length; i++) + if (!release.Writer.TryWrite(0)) throw new InvalidOperationException("Release channel is full."); var total = 0; for (var i = 0; i < pending.Length; i++) total += await completed.Reader.ReadAsync(limit.Token); // Completion notification can precede handler return. Drain every original ValueTask before reuse. diff --git a/website/docs/contributing/performance.md b/website/docs/contributing/performance.md index 2eef7b74a..af577bf73 100644 --- a/website/docs/contributing/performance.md +++ b/website/docs/contributing/performance.md @@ -497,3 +497,15 @@ and in-memory receiver channel reads. Sample weights do not assign exact bytes to any of these owners. The exact synchronous-invocation ABBA now includes this input set to measure the original handler call region separately; its results must remain distinct from these untraced totals and sampled profiles. + +The fixture workflow also runs a separate `--exact-releases` ABBA. Each record +counts calling-thread bytes around the entire synchronous batch of eight +`Release.Writer.TryWrite` calls. The native channel completes waiting readers +and schedules their continuations during these calls, so this tests a region +excluded by the handler-invocation counter. There are exactly 32768 measured +records, each representing eight writes; warmup is excluded. The JSON +`invocationAllocations` histogram counts release-batch delegate calls in this +mode, **not messages**. No await occurs inside the counter boundary. Other +threads and later continuations remain excluded, and byte counts do not identify +object types. This instrumented comparison neither attributes the historical +excess nor permits subtraction from the other controls' totals. From f172d3c503512c011077b91da79628a51fe1ecb1 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Tue, 10 Nov 2026 03:47:43 +0000 Subject: [PATCH 2/2] Extend exact release control to frozen inputs for #357 --- .github/workflows/frozen-fixture-control.yml | 2 +- website/docs/contributing/performance.md | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/.github/workflows/frozen-fixture-control.yml b/.github/workflows/frozen-fixture-control.yml index 1e35c9f16..9d1f8b7fc 100644 --- a/.github/workflows/frozen-fixture-control.yml +++ b/.github/workflows/frozen-fixture-control.yml @@ -68,7 +68,7 @@ jobs: if: always() run: | failed=0 - for run in 42306276036 42312305889; do + for run in 42306276036 42312305889 42310409459; do python3 .github/scripts/frozen_concurrent_control.py "inputs/$run" tools/FrozenFixtureProbe/bin/Release/net10.0/FrozenFixtureProbe.dll "results/$run-exact-releases" --exact-releases || failed=1 done exit "$failed" diff --git a/website/docs/contributing/performance.md b/website/docs/contributing/performance.md index af577bf73..5838daf3b 100644 --- a/website/docs/contributing/performance.md +++ b/website/docs/contributing/performance.md @@ -509,3 +509,15 @@ mode, **not messages**. No await occurs inside the counter boundary. Other threads and later continuations remain excluded, and byte counts do not identify object types. This instrumented comparison neither attributes the historical excess nor permits subtraction from the other controls' totals. + +The separate native exact-invocation ABBA for #357 completed in +[run 42748223325](https://github.com/thomhurst/Relayer/actions/runs/42748223325). +All four histograms contain exactly 262144 measured calls, with verified weighted +byte sums. Synchronous handler-call bytes per invocation were +192.003052 / 192.000122 / 192.000122 / 192.004517 (A/B/B/A). Both +candidates fall below both baselines in this instrumented region. This does not +explain the earlier unfavorable untraced fixture comparison or identify historical +end-to-end allocation owners. Histogram sizes do not identify allocated types. +The separate exact release-batch ABBA also includes this input set, testing +calling-thread channel completion scheduling outside the handler-call boundary. +Its measurements must remain separate from handler-call and inclusive totals.