diff --git a/.github/scripts/read_native_allocations.py b/.github/scripts/read_native_allocations.py index a11057633..a3a49e7f0 100644 --- a/.github/scripts/read_native_allocations.py +++ b/.github/scripts/read_native_allocations.py @@ -4,6 +4,10 @@ def read_rows(rows): + if not rows or rows[-1].get("kind") != "coverage": + raise ValueError("Incomplete allocation report coverage") + window_rows = [row for row in rows if row.get("kind") in ("window", "window-type")] + rows = [row for row in rows if row.get("kind") not in ("window", "window-type")] coverage = [row for row in rows if row.get("kind") == "coverage"] types = [row for row in rows if row.get("kind") == "type"] if len(coverage) != 1 or not types or len(rows) != len(types) + 1 or rows[-1] != coverage[0]: @@ -23,7 +27,51 @@ def read_rows(rows): for key in ("objects", "bytes"): if sum(row[key] for row in types) != coverage[0][key]: raise ValueError("Coverage total does not match type counts") - return {"coverage": coverage[0], "types": types} + windows = validate_windows(window_rows, coverage[0], types) + return {"coverage": coverage[0], "types": types, "windows": windows} + + +def validate_windows(rows, coverage, types): + expected = coverage.get("windows", 0) + windows = [row for row in rows if row["kind"] == "window"] + if type(expected) is not int or expected < 0 or expected % 3 or len(windows) != expected: + raise ValueError("Incomplete window coverage") + if [row["index"] for row in windows] != list(range(expected)): + raise ValueError("Unordered or duplicate window boundaries") + totals = {row["classId"]: [0, 0] for row in types} + names = {row["classId"]: row["type"] for row in types} + result = [] + cursor = 0 + for index, window in enumerate(windows): + if window["mode"] != index % 3 or type(window["measured"]) is not int or window["measured"] < 0: + raise ValueError("Invalid window mode or measured counter") + entries = [] + while cursor < len(rows) and rows[cursor]["kind"] == "window-type": + entry = rows[cursor] + if entry["index"] != index or entry["classId"] not in totals or entry["type"] != names[entry["classId"]]: + raise ValueError("Invalid window type association") + if any(type(entry[key]) is not int or entry[key] <= 0 for key in ("objects", "bytes")): + raise ValueError("Invalid window allocation counts") + entries.append(entry) + for slot, key in enumerate(("objects", "bytes")): + totals[entry["classId"]][slot] += entry[key] + cursor += 1 + if len({entry["classId"] for entry in entries}) != len(entries): + raise ValueError("Duplicate window ClassID") + if cursor >= len(rows) or rows[cursor] != window: + raise ValueError("Unordered window records") + cursor += 1 + for key in ("objects", "bytes"): + if type(window[key]) is not int or sum(entry[key] for entry in entries) != window[key]: + raise ValueError("Window total does not match type counts") + result.append({**window, "types": entries}) + if cursor != len(rows): + raise ValueError("Unexpected window records") + if expected: + for row in types: + if totals[row["classId"]] != [row["objects"], row["bytes"]]: + raise ValueError("Window totals do not match aggregate coverage") + return result def read(path): diff --git a/.github/scripts/read_receive_allocations.py b/.github/scripts/read_receive_allocations.py new file mode 100644 index 000000000..29045b544 --- /dev/null +++ b/.github/scripts/read_receive_allocations.py @@ -0,0 +1,25 @@ +"""Correlate retained receive counters with callbacks from the same execution only.""" +import json +import re +from pathlib import Path + +from read_native_allocations import read + + +def correlate(report, log): + counters = re.findall(r"^window=(\d+); scoped=(\d+); consumer=(\d+); receive=(\d+)$", log, re.MULTILINE) + if len(counters) != 1000 or [int(row[0]) for row in counters] != list(range(1000)): + raise ValueError("Expected every one of the 1000 measured receive triples") + windows = report["windows"] + if len(windows) != 3000: + raise ValueError("Expected 3000 allocation checkpoints") + for index, row in enumerate(counters): + for mode in range(3): + if windows[index * 3 + mode]["measured"] != int(row[mode + 1]): + raise ValueError("Checkpoint counter differs from retained probe log") + return report + + +if __name__ == "__main__": + import sys + print(json.dumps(correlate(read(sys.argv[1]), Path(sys.argv[2]).read_text()), indent=2)) diff --git a/.github/scripts/test_native_allocations.py b/.github/scripts/test_native_allocations.py index b3bf0ec31..31dd0e9a2 100644 --- a/.github/scripts/test_native_allocations.py +++ b/.github/scripts/test_native_allocations.py @@ -5,7 +5,8 @@ import tempfile import unittest -from read_native_allocations import read +from read_native_allocations import read, read_rows +from read_receive_allocations import correlate class NativeAllocationReportTests(unittest.TestCase): @@ -43,6 +44,82 @@ def test_negative_count(self): self.check(lambda rows: rows[0].update(objects=-1)) +class WindowAllocationReportTests(unittest.TestCase): + def rows(self): + return [ + {"kind": "window-type", "index": 0, "classId": 42, "type": "Message", "objects": 2, "bytes": 48}, + {"kind": "window", "index": 0, "mode": 0, "measured": 111, "objects": 2, "bytes": 48}, + {"kind": "window", "index": 1, "mode": 1, "measured": 222, "objects": 0, "bytes": 0}, + {"kind": "window", "index": 2, "mode": 2, "measured": 333, "objects": 0, "bytes": 0}, + {"kind": "type", "classId": 42, "type": "Message", "objects": 2, "bytes": 48}, + {"kind": "coverage", "objects": 2, "bytes": 48, "failures": 0, "windows": 3}, + ] + + def test_valid_empty_windows_and_counters_distinct_from_object_bytes(self): + result = read_rows(self.rows()) + self.assertEqual([row["measured"] for row in result["windows"]], [111, 222, 333]) + self.assertEqual(result["windows"][1]["types"], []) + + def test_incomplete_triplet(self): + rows = self.rows() + rows[-1]["windows"] = 2 + with self.assertRaisesRegex(ValueError, "Incomplete window"): + read_rows(rows) + + def test_wrong_boundary_order(self): + rows = self.rows() + rows[2]["index"] = 2 + with self.assertRaisesRegex(ValueError, "window boundaries"): + read_rows(rows) + + def test_wrong_type_window(self): + rows = self.rows() + rows[0]["index"] = 1 + with self.assertRaisesRegex(ValueError, "association"): + read_rows(rows) + + def test_wrong_window_sum(self): + rows = self.rows() + rows[1]["bytes"] += 1 + with self.assertRaisesRegex(ValueError, "Window total"): + read_rows(rows) + + def test_unassigned_aggregate_object(self): + rows = self.rows() + rows[-2]["objects"] += 1 + rows[-1]["objects"] += 1 + with self.assertRaisesRegex(ValueError, "aggregate"): + read_rows(rows) + + +class ReceiveWindowCorrelationTests(unittest.TestCase): + def data(self): + report = {"windows": [{"measured": index} for index in range(3000)]} + log = "\n".join(f"window={index}; scoped={index * 3}; consumer={index * 3 + 1}; receive={index * 3 + 2}" for index in range(1000)) + return report, log + + def test_all_counters_from_the_same_execution(self): + report, log = self.data() + self.assertIs(correlate(report, log), report) + + def test_missing_final_log_window(self): + report, log = self.data() + with self.assertRaisesRegex(ValueError, "1000"): + correlate(report, log.rsplit("\n", 1)[0]) + + def test_mislabelled_counter(self): + report, log = self.data() + report["windows"][7]["measured"] += 1 + with self.assertRaisesRegex(ValueError, "differs"): + correlate(report, log) + + def test_missing_checkpoint(self): + report, log = self.data() + report["windows"].pop() + with self.assertRaisesRegex(ValueError, "3000"): + correlate(report, log) + + @unittest.skipUnless(os.environ.get("TEST_NATIVE_PROFILER"), "Native profiler fixture paths not supplied") class NativeAllocationFixtureTests(unittest.TestCase): def test_exact_counts_exclude_warmup_and_resolve_generic_arguments(self): @@ -67,6 +144,48 @@ def test_exact_counts_exclude_warmup_and_resolve_generic_arguments(self): self.assertEqual(records[0]["objects"], count) self.assertEqual(records[0]["bytes"], count * 24) + def test_window_markers_partition_multithread_and_caller_allocations(self): + profiler = str(Path(os.environ["TEST_NATIVE_PROFILER"]).resolve()) + fixture = str(Path(os.environ["TEST_NATIVE_FIXTURE"]).resolve()) + evidence = Path(os.environ["TEST_NATIVE_OUTPUT"]) + evidence.mkdir(parents=True, exist_ok=True) + report = (evidence / "windows.jsonl").resolve() + environment = dict(os.environ, CORECLR_ENABLE_PROFILING="1", + CORECLR_PROFILER="{32B7EF07-25E8-4AC7-B011-9A4321D702C8}", + CORECLR_PROFILER_PATH=profiler, RELAYER_ALLOCATION_PROFILER=profiler, + RELAYER_ALLOCATION_OUTPUT=str(report)) + result = subprocess.run(["dotnet", fixture, "1024", "--windows"], env=environment, + capture_output=True, text=True, timeout=60) + (evidence / "windows.log").write_text(result.stdout + result.stderr) + self.assertEqual(result.returncode, 0, result.stderr) + actual = read(report) + self.assertEqual([row["measured"] for row in actual["windows"]], [111, 222, 333]) + for window in actual["windows"]: + for name in ("FixtureMessage", "FixtureTypes+Box`1[FixtureMessage]"): + entries = [row for row in window["types"] if row["type"] == name] + if window["index"] == 2: + self.assertEqual(entries, []) + else: + self.assertEqual(len(entries), 1, window) + self.assertEqual(entries[0]["objects"], 1024) + self.assertEqual(entries[0]["bytes"], 1024 * 24) + + def test_unfinished_window_capture_fails_with_retained_coverage(self): + profiler = str(Path(os.environ["TEST_NATIVE_PROFILER"]).resolve()) + evidence = Path(os.environ["TEST_NATIVE_OUTPUT"]) + evidence.mkdir(parents=True, exist_ok=True) + report = (evidence / "windows-missing.jsonl").resolve() + environment = dict(os.environ, CORECLR_ENABLE_PROFILING="1", + CORECLR_PROFILER="{32B7EF07-25E8-4AC7-B011-9A4321D702C8}", + CORECLR_PROFILER_PATH=profiler, RELAYER_ALLOCATION_PROFILER=profiler, + RELAYER_ALLOCATION_OUTPUT=str(report)) + result = subprocess.run(["dotnet", os.environ["TEST_NATIVE_FIXTURE"], "1024", "--windows-missing"], + env=environment, capture_output=True, text=True, timeout=60) + (evidence / "windows-missing.log").write_text(result.stdout + result.stderr) + self.assertNotEqual(result.returncode, 0) + with self.assertRaisesRegex(ValueError, "failures"): + read(report) + def test_exact_method_counts_exclude_outside_work_and_reject_missing_or_repeated_boundaries(self): profiler = str(Path(os.environ["TEST_NATIVE_PROFILER"]).resolve()) fixture = str(Path(os.environ["TEST_NATIVE_FIXTURE"]).resolve()) diff --git a/.github/scripts/test_verify_retained_ci.py b/.github/scripts/test_verify_retained_ci.py index 89ea97e2d..9e30c2686 100644 --- a/.github/scripts/test_verify_retained_ci.py +++ b/.github/scripts/test_verify_retained_ci.py @@ -19,13 +19,19 @@ def setUp(self): def test_accepts_pr_merge_and_workflow_ref_suffix(self): verify(self.source, self.commit, self.git_commit) - def test_rejects_unrelated_merge_and_changed_run_association(self): + def test_accepts_changed_pr_metadata_after_subsequent_pushes(self): for key in ("base", "head"): with self.subTest(key=key): source = copy.deepcopy(self.source) source["pull_requests"][0][key]["sha"] = "d" * 40 - with self.assertRaises(ValueError): - verify(source, self.commit, self.git_commit) + verify(source, self.commit, self.git_commit) + + def test_rejects_unrelated_or_reversed_merge_parents(self): + for parents in ([self.base, "d" * 40], [self.head, self.base], + [self.head], [self.base, self.base, self.head]): + with self.subTest(parents=parents), self.assertRaises(ValueError): + verify(self.source, self.commit, + {"sha": self.commit, "parents": [{"sha": sha} for sha in parents]}) def test_rejects_head_checkout_instead_of_tested_merge(self): with self.assertRaises(ValueError): diff --git a/.github/scripts/verify_retained_ci.py b/.github/scripts/verify_retained_ci.py index 2a31c273a..30aa408ec 100644 --- a/.github/scripts/verify_retained_ci.py +++ b/.github/scripts/verify_retained_ci.py @@ -14,12 +14,12 @@ def verify(source, commit, git_commit): raise ValueError("Git commit response does not match retained commit") if source["event"] == "pull_request": parents = [parent["sha"] for parent in git_commit["parents"]] - if not any( - source["head_sha"] == pr["head"]["sha"] - and parents == [pr["base"]["sha"], pr["head"]["sha"]] - for pr in source["pull_requests"] - ): - raise ValueError("Retained merge parents do not match the CI run's PR base/head") + # The run's head_sha is fixed, but pull_requests contains the PR's + # current base/head after subsequent pushes. It cannot authenticate + # the historical merge's base. Bind the downloaded merge to the + # selected run's original head instead, preserving parent order. + if len(parents) != 2 or parents[1] != source["head_sha"]: + raise ValueError("Retained merge second parent does not match the CI run's head") elif source["head_sha"] != commit: raise ValueError("Retained commit does not match the selected CI run") diff --git a/.github/workflows/concurrent-allocation-owners.yml b/.github/workflows/concurrent-allocation-owners.yml index 68accf737..500c30aa9 100644 --- a/.github/workflows/concurrent-allocation-owners.yml +++ b/.github/workflows/concurrent-allocation-owners.yml @@ -8,6 +8,11 @@ on: - '.github/scripts/verify_retained_ci.py' - '.github/scripts/test_verify_retained_ci.py' - 'tools/FrozenReceiveProbe/**' + - 'tools/FrozenAllocationProfiler/**' + - 'tools/FrozenConcurrentProbe/NativeAllocationRegion.cs' + - '.github/scripts/read_native_allocations.py' + - '.github/scripts/read_receive_allocations.py' + - '.github/scripts/test_native_allocations.py' workflow_dispatch: inputs: ci_run_id: @@ -136,7 +141,7 @@ jobs: export RELAYER_ALLOCATION_PROFILER="$CORECLR_PROFILER_PATH" export RELAYER_ALLOCATION_OUTPUT="$PWD/results/objects.jsonl" dotnet --fx-version "$CAPTURE_RUNTIME" tools/FrozenReceiveProbe/bin/Release/${{ matrix.framework }}/FrozenReceiveProbe.dll "$TEST_IMAGE" > results/exact.log 2>&1 || failed=1 - python3 .github/scripts/read_native_allocations.py results/objects.jsonl > results/validated-types.json || failed=1 + python3 .github/scripts/read_receive_allocations.py results/objects.jsonl results/exact.log > results/validated-types.json || failed=1 sha256sum --check results/test-inputs-before.sha256 > results/test-inputs-after.log 2>&1 || failed=1 exit "$failed" - name: Retain all outcomes and executable inputs @@ -162,6 +167,7 @@ jobs: .artifacts/exact-profiler/ profiler-sdk/core/profiling/ .github/scripts/read_native_allocations.py + .github/scripts/read_receive_allocations.py .github/scripts/test_native_allocations.py .github/scripts/verify_retained_ci.py .github/scripts/test_verify_retained_ci.py diff --git a/tools/FrozenAllocationProfiler/Fixture/Program.cs b/tools/FrozenAllocationProfiler/Fixture/Program.cs index 693a7af5b..839dd0837 100644 --- a/tools/FrozenAllocationProfiler/Fixture/Program.cs +++ b/tools/FrozenAllocationProfiler/Fixture/Program.cs @@ -1,11 +1,13 @@ using System.Runtime.CompilerServices; -var automatic = args.Length > 1 && args[1].StartsWith("--", StringComparison.Ordinal); -var tail = args.Length > 1 && !automatic; -var region = tail || automatic ? null : NativeAllocationRegion.Load() ?? throw new InvalidOperationException("Profiler path is required."); +var checkpoints = args.Length > 1 && args[1].StartsWith("--windows", StringComparison.Ordinal); +var automatic = args.Length > 1 && args[1].StartsWith("--", StringComparison.Ordinal) && !checkpoints; +var tail = args.Length > 1 && !automatic && !checkpoints; +var region = tail || automatic ? null : NativeAllocationRegion.Load(checkpoints) ?? throw new InvalidOperationException("Profiler path is required."); var engine = tail ? FixtureEngine.Log : null; var count = int.Parse(args[0], System.Globalization.CultureInfo.InvariantCulture); var values = new object[count]; +var second = checkpoints ? new object[count] : []; // JIT all fixture allocation code before the marker, without counting warmup objects. Fill(new object[10]); var start = new ManualResetEventSlim(); @@ -62,8 +64,19 @@ if (args[1] == "extra-event") engine.WorkloadActualStart(8); Fill(new object[29]); // After benchmark excluded. } -else if (!automatic) region!.End(); +else if (!automatic) +{ + if (checkpoints) + { + region!.Checkpoint(0, 111); + Fill(second); + region.Checkpoint(1, 222); + if (args[1] != "--windows-missing") region.Checkpoint(2, 333, final: true); + } + region!.End(); +} GC.KeepAlive(values); +GC.KeepAlive(second); [MethodImpl(MethodImplOptions.NoInlining)] static void Fill(object[] values) diff --git a/tools/FrozenAllocationProfiler/Profiler.cpp b/tools/FrozenAllocationProfiler/Profiler.cpp index aed7f704d..f9c10314c 100644 --- a/tools/FrozenAllocationProfiler/Profiler.cpp +++ b/tools/FrozenAllocationProfiler/Profiler.cpp @@ -18,6 +18,10 @@ std::mutex gate; bool initialized = false, active = false, begun = false; unsigned long long failures = 0; std::map counts; +struct Window { long long measured; std::map counts; }; +std::vector windows; +bool windowsCompleted = false; +std::map previousCounts; ICorProfilerInfo12* info = nullptr; // Native BDN events are delivered synchronously on the emitting thread by the // profiler EventPipe API (pinned dotnet/samples EventPipeProfiler.cpp). @@ -307,6 +311,18 @@ int writeReport() output << "{\"kind\":\"native-engine-tail\",\"nativeOperations\":" << nativeOperations << ",\"iterations\":" << iterations << ",\"stopped\":" << (benchmarkStopped ? "true" : "false") << "}\n"; } + for (size_t index = 0; index < windows.size(); ++index) { + const auto& window = windows[index]; + unsigned long long objects = 0, bytes = 0; + for (const auto& entry : window.counts) { + objects += entry.second.objects; bytes += entry.second.bytes; + output << "{\"kind\":\"window-type\",\"index\":" << index + << ",\"classId\":" << entry.first << ",\"type\":\"" << entry.second.name + << "\",\"objects\":" << entry.second.objects << ",\"bytes\":" << entry.second.bytes << "}\n"; + } + output << "{\"kind\":\"window\",\"index\":" << index << ",\"mode\":" << index % 3 + << ",\"measured\":" << window.measured << ",\"objects\":" << objects << ",\"bytes\":" << bytes << "}\n"; + } unsigned long long objects = 0, bytes = 0; for (const auto& entry : counts) { objects += entry.second.objects; bytes += entry.second.bytes; @@ -315,6 +331,7 @@ int writeReport() } output << "{\"kind\":\"coverage\",\"objects\":" << objects << ",\"bytes\":" << bytes << ",\"failures\":" << failures + << ",\"windows\":" << windows.size() << ",\"methodEntries\":" << methodEntries << ",\"methodLeaves\":" << methodLeaves << ",\"boundary\":\"" << (selectedMethod.empty() ? "external-marker" : "method-enter-leave") << "\"" << ",\"limits\":\"Exact CLR ObjectAllocated callbacks in this separate instrumented region; callbacks change fast paths and scheduling. Native-tail mode includes final timed cleanup/logging and extra-stat setup/work/cleanup, not exact MeasureWithGc. No stacks, historical replay or cross-control subtraction.\"}\n"; @@ -326,7 +343,43 @@ int writeReport() extern "C" __attribute__((visibility("default"))) int EndAllocationRegion() { std::lock_guard lock(gate); - if (!initialized || nativeTail || !active || !selectedMethod.empty()) return 0; + if (!initialized || nativeTail || (!active && !windowsCompleted) || !selectedMethod.empty()) return 0; active = false; + if (!windows.empty() && !windowsCompleted) ++failures; + windowsCompleted = false; + if (!windows.empty()) { + if (windows.size() % 3 != 0) ++failures; + // The final checkpoint stops capture atomically. Every observed allocation + // must therefore belong to a checkpoint. + for (const auto& entry : counts) { + const auto found = previousCounts.find(entry.first); + if (found == previousCounts.end() || found->second.objects != entry.second.objects + || found->second.bytes != entry.second.bytes) ++failures; + } + } return writeReport(); } + +// External probe markers partition this instrumented process envelope, not the +// fixture's thread-byte counters. Native lock order assigns racing allocations. +extern "C" __attribute__((visibility("default"))) int CheckpointAllocationRegion(int index, long long measured, int final) +{ + std::lock_guard lock(gate); + if (!initialized || nativeTail || !active || !selectedMethod.empty() + || index < 0 || static_cast(index) != windows.size() || measured < 0 + || (final != 0 && final != 1) || (final && index % 3 != 2)) { + ++failures; + return 0; + } + Window window{measured, {}}; + for (const auto& entry : counts) { + auto previous = previousCounts.find(entry.first); + const auto objects = entry.second.objects - (previous == previousCounts.end() ? 0 : previous->second.objects); + const auto bytes = entry.second.bytes - (previous == previousCounts.end() ? 0 : previous->second.bytes); + if (objects) window.counts.emplace(entry.first, Count{objects, bytes, entry.second.name}); + } + previousCounts = counts; + windows.push_back(std::move(window)); + if (final) { active = false; windowsCompleted = true; } + return 1; +} diff --git a/tools/FrozenAllocationProfiler/README.md b/tools/FrozenAllocationProfiler/README.md index 56d724ed2..ffa12adbe 100644 --- a/tools/FrozenAllocationProfiler/README.md +++ b/tools/FrozenAllocationProfiler/README.md @@ -111,7 +111,9 @@ and inspect every type family and failed outcome before choosing an intervention builds and retains the test image. Manual dispatch can instead set `ci_run_id` and `ci_run_attempt` to download that failed CI run's original core-test artifact. The workflow verifies its binary manifest and commit against the selected CI run -(PR merge parents must match the run's recorded base/head; other events require +(PR checkouts must be two-parent merges whose second parent matches the run's +immutable `head_sha`; current PR base/head metadata can change after later pushes +and cannot verify the historical base. Other events require the run's exact head commit), selects the matching recorded runtime (failing if unavailable), and executes those binaries without rebuilding or modifying them. It retains the downloaded inputs, @@ -126,11 +128,35 @@ and exact native-scope equality. All three outcomes are attempted and retained e when a comparison fails. The profiler's existing known-count checks run first. The exact region surrounds all measured triples, including the external loop and -all process threads; it reports aggregate object types, not individual window -owners or allocation stacks. The external delegate driver excludes TUnit and its +all process threads; it reports aggregate object types and partitions them into the +external checkpoint windows described below. It does not collect allocation stacks. The external delegate driver excludes TUnit and its parallel test activity. It is a separate execution: callback scheduling and fastpath changes can hide or expose the failure. A passing run cannot explain the historical 12,360-byte window, and callback object sizes cannot be subtracted from thread byte counters or independent runs. Preserve every unfavorable outcome and correlate any new excess with its own exact report before proposing a production fix. Original unit-test assertions, warmup and normal test parallelism remain unchanged. + + +## Concurrent receive window correlation (#687) + +The external `FrozenReceiveProbe` checkpoints native callback totals after each +Scoped, Consumer and Receive invocation. The retained fixture remains unchanged: +1000 warmup triples, 1000 measured triples and exact thread-byte equality. Each +`window` row carries its sequential index, mode (0/1/2) and the fixture's returned +thread-byte counter. Preceding `window-type` rows partition the aggregate callback +counts. The reader rejects missing/reordered boundaries, incorrect totals or types, +and the receive reader checks all 3000 counters against the same process's full log. +Known-count checks exercise worker allocations, caller allocations and an empty +window. Other profiler clients keep their existing aggregate-only report. + +These boundaries are **external process envelopes**, wider than the fixture's own +counter intervals. They include marker transitions, caller bookkeeping and concurrent +background allocations. Native callback lock order assigns racing allocations to a +window. The final checkpoint stops capture under that same lock, before report-writing +transitions. Counter bytes and CLR object sizes remain distinct: do not subtract them or +claim they must sum. Callbacks and checkpoints change scheduling; no stacks are +collected and a passing run does not explain a historical failure. Preserve all +windows and types, including baseline excesses, failed equality and failed coverage. +Use an unfavorable same-execution window to narrow candidate objects before choosing +further stack diagnostics or a demonstrated fix. diff --git a/tools/FrozenConcurrentProbe/NativeAllocationRegion.cs b/tools/FrozenConcurrentProbe/NativeAllocationRegion.cs index b0e626373..11dd03f87 100644 --- a/tools/FrozenConcurrentProbe/NativeAllocationRegion.cs +++ b/tools/FrozenConcurrentProbe/NativeAllocationRegion.cs @@ -5,24 +5,35 @@ internal sealed class NativeAllocationRegion { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int Transition(); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate int CheckpointTransition(int index, long measured, int final); + private readonly CheckpointTransition? checkpoint; private readonly Transition begin; private readonly Transition end; - private NativeAllocationRegion(string path) + private NativeAllocationRegion(string path, bool checkpoints) { var library = NativeLibrary.Load(Path.GetFullPath(path)); begin = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, "BeginAllocationRegion")); + if (checkpoints) + checkpoint = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, "CheckpointAllocationRegion")); end = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, "EndAllocationRegion")); } - internal static NativeAllocationRegion? Load() => - Environment.GetEnvironmentVariable("RELAYER_ALLOCATION_PROFILER") is { Length: > 0 } path ? new(path) : null; + internal static NativeAllocationRegion? Load(bool checkpoints = false) => + Environment.GetEnvironmentVariable("RELAYER_ALLOCATION_PROFILER") is { Length: > 0 } path ? new(path, checkpoints) : null; internal void Begin() { if (begin() != 1) throw new InvalidOperationException("Native allocation profiler is absent, uninitialized, or the region already began."); } + internal void Checkpoint(int index, long measured, bool final = false) + { + if (checkpoint is null || checkpoint(index, measured, final ? 1 : 0) != 1) + throw new InvalidOperationException("Native allocation checkpoint failed; retain the incomplete report."); + } + internal void End() { if (end() != 1) throw new InvalidOperationException("Native allocation report failed; inspect its coverage record before interpreting counts."); diff --git a/tools/FrozenReceiveProbe/Program.cs b/tools/FrozenReceiveProbe/Program.cs index 04a61ef2b..3ecea4f78 100644 --- a/tools/FrozenReceiveProbe/Program.cs +++ b/tools/FrozenReceiveProbe/Program.cs @@ -15,7 +15,7 @@ using var fixture = (IDisposable)Activator.CreateInstance(type)!; var mode = type.GetNestedType("Mode")!; var run = type.GetMethod("Run")!; -var region = NativeAllocationRegion.Load(); +var region = NativeAllocationRegion.Load(checkpoints: true); typeof(Measurement).GetMethod(nameof(Measurement.Run))!.MakeGenericMethod(mode) .Invoke(null, [fixture, run, region]); @@ -40,16 +40,22 @@ public static void Run(object fixture, MethodInfo method, NativeAllocatio for (var i = 0; i < windows.Length; i++) { var native = run(scoped); + region?.Checkpoint(i * 3, native); var consume = run(consumer); + region?.Checkpoint(i * 3 + 1, consume); var full = run(receive); + region?.Checkpoint(i * 3 + 2, full, final: i == windows.Length - 1); windows[i] = (native, consume, full); scopedBytes += native; consumerBytes += consume; receiveBytes += full; } - region?.End(); - Console.WriteLine($"runtime={System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}; arch={System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}; instrumented={region is not null}; scoped={scopedBytes}; consumer={consumerBytes}; receive={receiveBytes}"); - for (var i = 0; i < windows.Length; i++) Console.WriteLine($"window={i}; scoped={windows[i].Scoped}; consumer={windows[i].Consumer}; receive={windows[i].Receive}"); + try { region?.End(); } + finally + { + Console.WriteLine($"runtime={System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}; arch={System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}; instrumented={region is not null}; scoped={scopedBytes}; consumer={consumerBytes}; receive={receiveBytes}"); + for (var i = 0; i < windows.Length; i++) Console.WriteLine($"window={i}; scoped={windows[i].Scoped}; consumer={windows[i].Consumer}; receive={windows[i].Receive}"); + } if (scopedBytes <= 0 || consumerBytes != scopedBytes || receiveBytes != scopedBytes) throw new InvalidOperationException("Exact native scope equality failed; retain this outcome and the complete object report."); }