Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion .github/scripts/read_native_allocations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand All @@ -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):
Expand Down
25 changes: 25 additions & 0 deletions .github/scripts/read_receive_allocations.py
Original file line number Diff line number Diff line change
@@ -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))
121 changes: 120 additions & 1 deletion .github/scripts/test_native_allocations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand All @@ -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())
Expand Down
12 changes: 9 additions & 3 deletions .github/scripts/test_verify_retained_ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
12 changes: 6 additions & 6 deletions .github/scripts/verify_retained_ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
8 changes: 7 additions & 1 deletion .github/workflows/concurrent-allocation-owners.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
21 changes: 17 additions & 4 deletions tools/FrozenAllocationProfiler/Fixture/Program.cs
Original file line number Diff line number Diff line change
@@ -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();
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading