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
55 changes: 55 additions & 0 deletions .github/scripts/read_allocation_stacks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""Validate CLR snapshot coverage against the same execution's exact callbacks."""
import json
from collections import Counter
from pathlib import Path

from read_native_allocations import read


def validate(rows, report):
if not rows or rows[-1].get("kind") != "stack-coverage":
raise ValueError("Incomplete stack coverage")
coverage = rows[-1]
if coverage.get("failures") != 0:
raise ValueError("CLR snapshot failures")
frames = {}
actual = Counter()
totals = Counter()
for row in rows[:-1]:
if row.get("kind") == "frame":
key = row["functionId"]
if type(key) is not int or key < 0 or key in frames or not row.get("name"):
raise ValueError("Invalid or duplicate frame")
frames[key] = row["name"]
elif row.get("kind") == "allocation-stack":
if row.get("snapshotResult") != 0 or not row.get("frames"):
raise ValueError("Incomplete CLR snapshot")
if any(type(row.get(key)) is not int or row[key] <= 0 for key in ("thread", "classId", "objects", "bytes")):
raise ValueError("Invalid stack allocation counts")
if type(row.get("index")) is not int or row["index"] < 0:
raise ValueError("Invalid stack window")
if any(type(frame) is not int or frame not in frames for frame in row["frames"]):
raise ValueError("Unknown stack frame")
for key in ("objects", "bytes"):
actual[row["index"], row["classId"], key] += row[key]
totals[key] += row[key]
else:
raise ValueError("Unknown stack record")
expected = Counter()
for window in report["windows"]:
for entry in window["types"]:
for key in ("objects", "bytes"):
expected[window["index"], entry["classId"], key] = entry[key]
if not expected or actual != expected:
raise ValueError("Stack allocations do not match checkpoint callbacks")
for key in ("objects", "bytes"):
if totals[key] != coverage.get(key) or totals[key] != report["coverage"][key]:
raise ValueError("Stack coverage total mismatch")
return {"coverage": coverage, "unresolved_frames": [key for key, name in frames.items() if name.startswith("<unresolved")],
"frames": frames, "allocations": [row for row in rows if row["kind"] == "allocation-stack"]}


if __name__ == "__main__":
import sys
rows = [json.loads(line) for line in Path(sys.argv[1]).read_text().splitlines()]
print(json.dumps(validate(rows, read(sys.argv[2])), indent=2))
14 changes: 14 additions & 0 deletions .github/scripts/read_native_allocations.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,20 @@ def read_rows(rows):
raise ValueError("Incomplete or repeated method boundary")
if len({row["classId"] for row in types}) != len(types):
raise ValueError("Duplicate ClassID records")
unavailable = 0
for row in types:
if "<metadata-unavailable" in row["type"].replace("<metadata-unavailable:0x80131351>", ""):
raise ValueError("Unknown metadata-unavailable HRESULT")
marked = row.get("metadataUnavailable", False)
if type(marked) is not bool or marked != ("<metadata-unavailable:0x80131351>" in row["type"]):
raise ValueError("Invalid metadata-unavailable type status")
unavailable += marked
if not row["type"] or "<unresolved" in row["type"] or "<type-depth" in row["type"]:
raise ValueError("Unresolved type")
if any(type(row[key]) is not int or row[key] <= 0 for key in ("classId", "objects", "bytes")):
raise ValueError("Invalid allocation counts")
if type(coverage[0].get("metadataUnavailableTypes", 0)) is not int or coverage[0].get("metadataUnavailableTypes", 0) != unavailable:
raise ValueError("Metadata-unavailable coverage does not match types")
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")
Expand All @@ -40,16 +49,21 @@ def validate_windows(rows, coverage, types):
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}
unavailable = {row["classId"]: row.get("metadataUnavailable", False) 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")
if "callerThread" in window and (type(window["callerThread"]) is not int or window["callerThread"] <= 0):
raise ValueError("Invalid checkpoint caller thread")
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 entry.get("metadataUnavailable", False) != unavailable[entry["classId"]]:
raise ValueError("Invalid window metadata-unavailable status")
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)
Expand Down
42 changes: 42 additions & 0 deletions .github/scripts/read_parallel_receive_allocations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""Correlate exact checkpoints with the real parallel TUnit test's retained output."""
import json
import re
from pathlib import Path

from read_native_allocations import read
from read_receive_allocations import correlate


# TUnit can repeat captured output in its detailed summary. Accept identical
# echoes only; never choose a favorable copy of a conflicting measurement.
WINDOW = re.compile(
r"^\s*window=(\d+); scoped=Window \{ Bytes = (\d+),[^\r\n]*?\}; "
r"consumer=Window \{ Bytes = (\d+),[^\r\n]*?\}; "
r"receive=Window \{ Bytes = (\d+),[^\r\n]*?\}\s*$", re.MULTILINE)


def correlate_parallel(report, log):
log = re.sub(r"\x1b\[[0-9;]*m", "", log)
counters = {}
for match in WINDOW.finditer(log):
index, *values = map(int, match.groups())
if index in counters and counters[index] != values:
raise ValueError("Conflicting repeated test window")
counters[index] = values
if set(counters) != set(range(1000)):
raise ValueError("Expected every one of the 1000 measured test triples")
normalized = "\n".join(
f"window={index}; scoped={values[0]}; consumer={values[1]}; receive={values[2]}"
for index, values in sorted(counters.items()))
result = correlate(report, normalized)
result["test_output"] = {
"unique_triples": len(counters),
"rows_including_echoes": len(WINDOW.findall(log)),
"limits": "Callbacks cover all process threads between test checkpoints, including other parallel tests. "
"Their object bytes are not the fixture's thread counters. No stacks or historical attribution."}
return result


if __name__ == "__main__":
import sys
print(json.dumps(correlate_parallel(read(sys.argv[1]), Path(sys.argv[2]).read_text()), indent=2))
44 changes: 44 additions & 0 deletions .github/scripts/test_allocation_stacks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import copy
import unittest

from read_allocation_stacks import validate


class AllocationStackTests(unittest.TestCase):
def setUp(self):
self.rows = [
{"kind": "frame", "functionId": 11, "name": "Fixture.FillRange"},
{"kind": "allocation-stack", "index": 0, "thread": 7, "classId": 42,
"snapshotResult": 0, "objects": 2, "bytes": 48, "frames": [11]},
{"kind": "stack-coverage", "objects": 2, "bytes": 48, "failures": 0},
]
self.report = {"coverage": {"objects": 2, "bytes": 48}, "windows": [
{"index": 0, "types": [{"classId": 42, "objects": 2, "bytes": 48}]}]}

def test_valid_same_execution_thread_and_window(self):
self.assertEqual(validate(self.rows, self.report)["allocations"][0]["thread"], 7)

def test_snapshot_failure_and_empty_frames_are_rejected(self):
for key, value in (("snapshotResult", -1), ("frames", []), ("frames", [99])):
rows = copy.deepcopy(self.rows)
rows[1][key] = value
with self.assertRaises(ValueError):
validate(rows, self.report)

def test_wrong_window_class_or_counts_are_rejected(self):
for key, value in (("index", 1), ("classId", 43), ("bytes", 49), ("objects", 3), ("thread", 0)):
rows = copy.deepcopy(self.rows)
rows[1][key] = value
with self.assertRaises(ValueError):
validate(rows, self.report)

def test_missing_or_duplicate_frame_and_coverage_are_rejected(self):
for rows in (self.rows[1:], [self.rows[0], *self.rows], self.rows[:-1],
[*self.rows[:-1], {**self.rows[-1], "failures": 1}],
[*self.rows[:-1], {**self.rows[-1], "bytes": 49}]):
with self.assertRaises(ValueError):
validate(rows, self.report)

def test_unresolved_names_remain_explicit(self):
self.rows[0]["name"] = "<unresolved-function>"
self.assertEqual(validate(self.rows, self.report)["unresolved_frames"], [11])
75 changes: 75 additions & 0 deletions .github/scripts/test_native_allocations.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,24 @@ def test_failed_resolution(self):
with self.assertRaisesRegex(ValueError, "failures"):
self.check(lambda rows: rows[-1].update(failures=1))

def test_explicit_metadata_unavailable_keeps_exact_counts(self):
def mark(rows):
rows[0].update(type="<metadata-unavailable:0x80131351>", metadataUnavailable=True)
rows[-1].update(metadataUnavailableTypes=1)
result = self.check(mark)
self.assertEqual(result["coverage"]["objects"], 10)
self.assertTrue(result["types"][0]["metadataUnavailable"])

def test_metadata_unavailable_requires_explicit_matching_status(self):
for name, marked, total in (("<metadata-unavailable:0xdeadbeef>", True, 1),
("<metadata-unavailable:0x80131351>", False, 0),
("Message", True, 1),
("<metadata-unavailable:0x80131351>", True, 0),
("<unresolved-class>", False, 0)):
with self.subTest(name=name, marked=marked, total=total), self.assertRaises(ValueError):
self.check(lambda rows: (rows[0].update(type=name, metadataUnavailable=marked),
rows[-1].update(metadataUnavailableTypes=total)))

def test_inconsistent_sum(self):
with self.assertRaisesRegex(ValueError, "total"):
self.check(lambda rows: rows[-1].update(bytes=241))
Expand Down Expand Up @@ -60,6 +78,16 @@ def test_valid_empty_windows_and_counters_distinct_from_object_bytes(self):
self.assertEqual([row["measured"] for row in result["windows"]], [111, 222, 333])
self.assertEqual(result["windows"][1]["types"], [])

def test_metadata_unavailable_window_status_matches_aggregate(self):
rows = self.rows()
for row in (rows[0], rows[-2]):
row.update(type="<metadata-unavailable:0x80131351>", metadataUnavailable=True)
rows[-1]["metadataUnavailableTypes"] = 1
self.assertTrue(read_rows(rows)["windows"][0]["types"][0]["metadataUnavailable"])
rows[0]["metadataUnavailable"] = False
with self.assertRaisesRegex(ValueError, "metadata-unavailable"):
read_rows(rows)

def test_incomplete_triplet(self):
rows = self.rows()
rows[-1]["windows"] = 2
Expand All @@ -72,6 +100,16 @@ def test_wrong_boundary_order(self):
with self.assertRaisesRegex(ValueError, "window boundaries"):
read_rows(rows)

def test_checkpoint_caller_thread_is_positive_and_preserved(self):
for caller in (0, -1, True, "7"):
rows = self.rows()
rows[1]["callerThread"] = caller
with self.assertRaisesRegex(ValueError, "checkpoint caller"):
read_rows(rows)
rows = self.rows()
rows[1]["callerThread"] = 7
self.assertEqual(read_rows(rows)["windows"][0]["callerThread"], 7)

def test_wrong_type_window(self):
rows = self.rows()
rows[0]["index"] = 1
Expand Down Expand Up @@ -122,6 +160,43 @@ def test_missing_checkpoint(self):

@unittest.skipUnless(os.environ.get("TEST_NATIVE_PROFILER"), "Native profiler fixture paths not supplied")
class NativeAllocationFixtureTests(unittest.TestCase):
def test_opt_in_stacks_preserve_multithreaded_known_counts_and_call_sites(self):
from read_allocation_stacks import validate
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 / "stack-windows.jsonl").resolve()
stacks = (evidence / "stack-windows-stacks.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), RELAYER_ALLOCATION_STACKS=str(stacks))
result = subprocess.run(["dotnet", fixture, "1024", "--windows"], env=environment,
capture_output=True, text=True, timeout=60)
(evidence / "stack-windows.log").write_text(result.stdout + result.stderr)
self.assertEqual(result.returncode, 0, result.stderr)
worker_threads = {int(line.split("thread=")[1]) for line in result.stdout.splitlines()
if line.startswith("allocation-worker=")}
self.assertEqual(len(worker_threads), 4)
self.assertNotIn(0, worker_threads)
actual = read(report)
snapshot = validate([json.loads(line) for line in stacks.read_text().splitlines()], actual)
for name in ("FixtureMessage", "FixtureTypes+Box`1[FixtureMessage]"):
class_id = next(row["classId"] for row in actual["types"] if row["type"] == name)
for index in (0, 1):
rows = [row for row in snapshot["allocations"] if row["classId"] == class_id and row["index"] == index]
self.assertEqual(sum(row["objects"] for row in rows), 1024)
self.assertEqual(sum(row["bytes"] for row in rows), 1024 * 24)
self.assertEqual(len({row["thread"] for row in rows}), 4 if index == 0 else 1)
if index == 0:
self.assertEqual({row["thread"] for row in rows}, worker_threads)
caller = actual["windows"][index]["callerThread"]
self.assertGreater(caller, 0)
self.assertEqual({row["thread"] == caller for row in rows}, {False} if index == 0 else {True})
for row in rows:
self.assertTrue(any("g__FillRange|" in snapshot["frames"][frame] for frame in row["frames"]), row)

def test_exact_counts_exclude_warmup_and_resolve_generic_arguments(self):
profiler = str(Path(os.environ["TEST_NATIVE_PROFILER"]).resolve())
fixture = str(Path(os.environ["TEST_NATIVE_FIXTURE"]).resolve())
Expand Down
47 changes: 47 additions & 0 deletions .github/scripts/test_parallel_receive_allocations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import copy
import unittest

from read_parallel_receive_allocations import correlate_parallel


class ParallelReceiveAllocationTests(unittest.TestCase):
def setUp(self):
self.report = {"windows": [{"measured": 1024} for _ in range(3000)]}
window = "Window { Bytes = 1024, CallerBytes = 1024, WorkerBytes = 0, Gen0 = 0, Gen1 = 0, Gen2 = 0 }"
self.lines = [f"window={index}; scoped={window}; consumer={window}; receive={window}" for index in range(1000)]

def test_correlates_indented_colored_tunit_echoes(self):
log = "\n".join(self.lines) + "\n\x1b[32m" + "\n".join(" " + line for line in self.lines) + "\x1b[m\n"
result = correlate_parallel(self.report, log)
self.assertEqual(result["test_output"]["unique_triples"], 1000)
self.assertEqual(result["test_output"]["rows_including_echoes"], 2000)

def test_retains_unfavorable_window_without_requiring_equality(self):
self.lines[305] = self.lines[305].replace("consumer=Window { Bytes = 1024", "consumer=Window { Bytes = 13384")
self.report["windows"][305 * 3 + 1]["measured"] = 13384
result = correlate_parallel(self.report, "\n".join(self.lines))
self.assertEqual(result["windows"][916]["measured"], 13384)

def test_rejects_conflicting_echo_instead_of_selecting_favorable_copy(self):
log = "\n".join(self.lines + [self.lines[305].replace("consumer=Window { Bytes = 1024", "consumer=Window { Bytes = 13384")])
with self.assertRaisesRegex(ValueError, "Conflicting"):
correlate_parallel(self.report, log)

def test_rejects_missing_or_out_of_range_windows(self):
for lines in (self.lines[:-1], self.lines + [self.lines[0].replace("window=0;", "window=1000;")]):
with self.subTest(length=len(lines)), self.assertRaisesRegex(ValueError, "1000"):
correlate_parallel(copy.deepcopy(self.report), "\n".join(lines))

def test_rejects_checkpoint_from_a_different_counter_execution(self):
self.report["windows"][916]["measured"] = 13384
with self.assertRaisesRegex(ValueError, "differs"):
correlate_parallel(self.report, "\n".join(self.lines))

def test_rejects_incomplete_profiler_capture(self):
self.report["windows"].pop()
with self.assertRaisesRegex(ValueError, "3000"):
correlate_parallel(self.report, "\n".join(self.lines))


if __name__ == "__main__":
unittest.main()
Loading
Loading