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
43 changes: 40 additions & 3 deletions .github/scripts/frozen_bdn_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
"""Replay a retained BenchmarkDotNet engine, without rebuilding or changing its job."""
import argparse
import json
import os
from pathlib import Path
import re
import subprocess

from frozen_concurrent_control import verify
from frozen_scope_control import result as timing_result


BENCHMARK = "Relayer.Benchmarks.EndToEndBenchmarks.ConcurrentRoundTrip"
Expand Down Expand Up @@ -91,9 +91,16 @@ def main():
help="Bind the original executable to an installed exact patch without editing retained inputs.")
parser.add_argument("--same-image", choices=("baseline", "candidate"),
help="Negative control: launch the selected original image four times, without an image comparison.")
parser.add_argument("--allocation-profiler", type=Path,
help="Separate exact CLR callback counts in the native final-stop tail envelope.")
args = parser.parse_args()
from frozen_scope_control import result as timing_result
if args.allocation_profiler and args.case != "concurrent":
parser.error("Exact allocation callbacks support only the concurrent benchmark")
owner, method, parameter, operations = CASES[args.case]
benchmark = f"Relayer.Benchmarks.{owner}.{method}"
if args.trace_tool and args.allocation_profiler:
parser.error("Choose sampled traces or synchronous CLR allocation callbacks, not both")
builds = args.artifact.resolve() / "performance-builds"
# Verify all three original inventories before starting any process. A2 deliberately
# repeats the first baseline executable, as in the external-probe ABBA.
Expand All @@ -105,7 +112,7 @@ def main():
"case": args.case, "parameter": parameter,
"engine": "Original retained BenchmarkDotNet generated executable and Default job",
"host": "Native NoAcknowledgementConsoleHost; original anonymous-pipe parent absent",
"operationsPerInvoke": operations, "instrumented": args.trace_tool is not None,
"operationsPerInvoke": operations, "instrumented": args.trace_tool is not None or args.allocation_profiler is not None,
"limits": "New original-engine executions, not historical reconstruction, allocation-type attribution, throughput equivalence or native-client budget evidence. No external fixed-count driver, sampled profile, job override or threshold change.",
"requestedRuntime": args.runtime_version, "commands": []}
for side in launches:
Expand All @@ -127,6 +134,17 @@ def main():
"--output", str((args.output / f"{index}-{side}.nettrace").resolve()),
"--show-child-io", "--", *command]
for index, (side, command) in enumerate(zip(launches, protocol["commands"]), 1)]
if args.allocation_profiler:
from read_native_tail_allocations import read as read_tail

protocol["allocationProfiler"] = str(args.allocation_profiler.resolve())
protocol["limits"] = (
"Separate instrumented native-engine ABBA; exact CLR ObjectAllocated notifications and GetObjectSize2 sizes, not all allocation-context overhead. "
"Synchronous native EventPipe callbacks reset counts at each WorkloadActualStop, retaining only the final stop to BenchmarkStop envelope. "
"Includes final timed cleanup/GC/logging and extra-stat setup/work/cleanup, not exact MeasureWithGc. "
"Callbacks, metadata resolution and locking change allocation paths and scheduling. No stacks or exact call-site attribution. "
"New executions do not establish historical ownership, production regression, throughput equivalence or a performance trade-off. "
"No independent-total subtraction or threshold relaxation.")
if args.same_image:
protocol["limits"] += " Same-image negative control: no candidate-versus-baseline comparison; process order, adaptive operation counts and host drift remain uncontrolled."
(args.output / "protocol.json").write_text(json.dumps(protocol, indent=2) + "\n")
Expand All @@ -137,8 +155,15 @@ def main():
outcome = {"launch": index, "side": side}
with log_path.open("w") as log:
try:
environment = None
if args.allocation_profiler:
environment = dict(os.environ, CORECLR_ENABLE_PROFILING="1",
CORECLR_PROFILER="{32B7EF07-25E8-4AC7-B011-9A4321D702C8}",
CORECLR_PROFILER_PATH=str(args.allocation_profiler.resolve()),
RELAYER_ALLOCATION_BDN_TAIL="1",
RELAYER_ALLOCATION_OUTPUT=str((args.output / f"{index}-{side}-objects.jsonl").resolve()))
subprocess.run(command, cwd=runners[side][0].parent, stdout=log,
stderr=subprocess.STDOUT, check=True, timeout=900)
stderr=subprocess.STDOUT, check=True, timeout=900, env=environment)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError) as error:
log.write(f"\nLaunch failed: {error}\n")
outcome["error"] = str(error)
Expand All @@ -159,6 +184,18 @@ def main():
except ValueError as error:
outcome["error"] = str(error)
failed = True
if args.allocation_profiler:
report = args.output / f"{index}-{side}-objects.jsonl"
try:
if "operations" not in outcome:
raise ValueError("No native GC-stat denominator for callback report")
validated = read_tail(report, outcome["operations"])
outcome["allocationReport"] = report.name
outcome["callbackObjects"] = validated["coverage"]["objects"]
outcome["callbackBytes"] = validated["coverage"]["bytes"]
except (ValueError, OSError, KeyError, TypeError) as error:
outcome["allocationError"] = str(error)
failed = True
if args.trace_tool:
trace = args.output / f"{index}-{side}.nettrace"
if not trace.is_file() or trace.stat().st_size == 0:
Expand Down
7 changes: 5 additions & 2 deletions .github/scripts/read_native_allocations.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
from pathlib import Path


def read(path):
rows = [json.loads(line) for line in Path(path).read_text().splitlines()]
def read_rows(rows):
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 @@ -24,6 +23,10 @@ def read(path):
return {"coverage": coverage[0], "types": types}


def read(path):
return read_rows([json.loads(line) for line in Path(path).read_text().splitlines()])


if __name__ == "__main__":
import sys
print(json.dumps({str(path): read(path) for path in sys.argv[1:]}, indent=2))
47 changes: 47 additions & 0 deletions .github/scripts/read_native_tail_allocations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Validate synchronous CLR callback tail counts, not historical allocation ownership."""
import json
from pathlib import Path

from read_native_allocations import read_rows


def read(path, expected_operations):
rows = [json.loads(line) for line in Path(path).read_text().splitlines()]
events = [r for r in rows if r.get("kind") == "engine-event"]
tails = [r for r in rows if r.get("kind") == "native-engine-tail"]
allocations = [r for r in rows if r.get("kind") in ("type", "coverage")]
if len(tails) != 1 or rows != events + tails + allocations:
raise ValueError("Missing, unordered or unknown tail records")
started = stopped = opened = False
iterations = operations = pending = 0
thread = None
for event in events:
identity, current, count = event["id"], event["thread"], event["operations"]
if type(current) is not int or current <= 0 or (thread is not None and thread != current) or stopped:
raise ValueError("Invalid engine thread or event after benchmark stop")
thread = current
if identity in (1, 2):
if count != 0:
raise ValueError("Unexpected benchmark payload")
elif type(count) is not int or count <= 0 or count % 8:
raise ValueError("Invalid native operation count")
if not started and 3 <= identity <= 6:
continue
if identity == 1 and not started:
started = True
elif not started:
raise ValueError("Missing benchmark start")
elif identity == 15 and not opened:
opened, pending = True, count
elif identity == 16 and opened and pending == count:
opened, operations = False, count
iterations += 1
elif identity == 2 and not opened and iterations:
stopped = True
elif not 3 <= identity <= 14 or opened or iterations:
raise ValueError("Unexpected engine stage or unmatched iteration")
tail = tails[0]
if (not stopped or tail.get("stopped") is not True or tail.get("iterations") != iterations
or tail.get("nativeOperations") != operations or operations != expected_operations):
raise ValueError("Incomplete tail or native // GC denominator mismatch")
return {"tail": tail, "events": events, **read_rows(allocations)}
83 changes: 83 additions & 0 deletions .github/scripts/test_frozen_bdn_control.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import json
import shutil
import sys
from pathlib import Path
import subprocess
import tempfile
Expand All @@ -12,6 +14,17 @@


class NativeResultTests(unittest.TestCase):
def test_retained_uninstrumented_launcher_needs_no_allocation_readers(self):
# Existing control artifacts retain these two scripts without allocation readers.
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
for name in ("frozen_bdn_control.py", "frozen_concurrent_control.py"):
shutil.copyfile(Path(__file__).with_name(name), root / name)
completed = subprocess.run([sys.executable, str(root / "frozen_bdn_control.py"), "--help"],
cwd=root, capture_output=True, text=True)
self.assertEqual(completed.returncode, 0, completed.stderr)
self.assertIn("--allocation-profiler", completed.stdout)

def test_uses_native_operations_without_dividing_by_eight_again(self):
actual = result(COMPLETE)
self.assertEqual(actual["operations"], 65536)
Expand Down Expand Up @@ -292,6 +305,76 @@ def execute(command, **kwargs):
self.assertEqual([o["side"] for o in outcomes], ["candidate"] * 4)
self.assertEqual(json.loads((output / "protocol.json").read_text())["requestedRuntime"], "10.0.14")

def test_exact_callbacks_attempt_every_launch_and_fail_closed_on_denominator_mismatch(self):
from test_native_tail_allocations import report
for invalid, same_image in ((invalid, same) for invalid in (None, "coverage", "denominator", "missing") for same in (False, True)):
with self.subTest(invalid=invalid, same_image=same_image), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
for side in ("baseline", "candidate"):
_, image = self.fixture(root / "performance-builds" / side)
image.with_suffix(".runtimeconfig.json").write_text(json.dumps({"runtimeOptions": {
"framework": {"name": "Microsoft.NETCore.App", "version": "10.0.0"}}}))
output = root / "results"
calls = []

def execute(command, **kwargs):
calls.append(command)
environment = kwargs["env"]
self.assertEqual(environment["RELAYER_ALLOCATION_BDN_TAIL"], "1")
self.assertEqual(environment["CORECLR_ENABLE_PROFILING"], "1")
self.assertIn("--job", command)
self.assertNotIn("collect", command)
if same_image:
self.assertEqual(command[:5], ["dotnet", "--fx-version", "10.0.14", "--roll-forward", "Disable"])
self.assertIn("/performance-builds/candidate/", command[5])
kwargs["stdout"].write("// Runtime=.NET 10.0.14 (test), X64\n" + COMPLETE)
rows = report()
# Keep every native iteration payload and final scope consistent.
for row in rows:
if row["kind"] == "engine-event" and row["id"] in (15, 16):
row["operations"] = 65536
if row["kind"] == "native-engine-tail":
row["nativeOperations"] = 65536
if len(calls) == 2:
if invalid == "coverage":
rows[-1]["failures"] = 1
elif invalid == "denominator":
rows[-3]["nativeOperations"] = 8
elif invalid == "missing":
return
Path(environment["RELAYER_ALLOCATION_OUTPUT"]).write_text("\n".join(map(json.dumps, rows)))

with patch("sys.argv", ["control", str(root), str(output), "--allocation-profiler", str(root / "profiler.so"),
*(["--same-image", "candidate", "--runtime-version", "10.0.14"] if same_image else [])]), \
patch("frozen_bdn_control.verify", return_value="frozen"), \
patch("frozen_bdn_control.subprocess.run", side_effect=execute):
if invalid:
with self.assertRaisesRegex(SystemExit, "launches failed"):
main()
else:
main()
self.assertEqual(len(calls), 4)
outcomes = json.loads((output / "outcomes.json").read_text())
self.assertEqual("allocationError" in outcomes[1], invalid is not None)
self.assertEqual(outcomes[3]["callbackBytes"], 72)
self.assertTrue((output / f"4-{'candidate' if same_image else 'baseline'}-objects.jsonl").exists())
if same_image:
self.assertEqual([item["side"] for item in outcomes], ["candidate"] * 4)
self.assertEqual(outcomes[3]["runtime"], "10.0.14")
self.assertIn("Same-image negative control", json.loads((output / "protocol.json").read_text())["limits"])

def test_exact_callbacks_reject_other_benchmark_cases_before_launch(self):
for case in ("scoped-dispatch", "log-composed", "queue-native"):
with self.subTest(case=case), tempfile.TemporaryDirectory() as directory, \
patch("sys.argv", ["control", directory, str(Path(directory) / "results"),
"--allocation-profiler", "profiler.so", "--case", case]), \
patch("frozen_bdn_control.verify") as verify_input, \
patch("frozen_bdn_control.subprocess.run") as execute:
with self.assertRaises(SystemExit):
main()
verify_input.assert_not_called()
execute.assert_not_called()

def test_invalid_input_prevents_every_process_launch(self):
with tempfile.TemporaryDirectory() as directory, \
patch("sys.argv", ["control", directory, str(Path(directory) / "results")]), \
Expand Down
84 changes: 84 additions & 0 deletions .github/scripts/test_native_tail_allocations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import copy
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest

from read_native_tail_allocations import read


def report():
events = [(5, 8), (6, 8), (1, 0), (15, 8), (16, 8), (15, 16), (16, 16), (2, 0)]
return ([{'kind': 'engine-event', 'id': identity, 'thread': 42, 'operations': operations}
for identity, operations in events]
+ [{'kind': 'native-engine-tail', 'nativeOperations': 16, 'iterations': 2, 'stopped': True},
{'kind': 'type', 'classId': 1, 'type': 'Message', 'objects': 3, 'bytes': 72},
{'kind': 'coverage', 'objects': 3, 'bytes': 72, 'failures': 0}])


class NativeTailReportTests(unittest.TestCase):
def check(self, rows, operations=16):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'objects.jsonl'
path.write_text('\n'.join(map(json.dumps, rows)))
return read(path, operations)

def test_preserves_every_event_and_uses_final_iteration_denominator(self):
actual = self.check(report())
self.assertEqual(len(actual['events']), 8)
self.assertEqual(actual['tail']['nativeOperations'], 16)
self.assertEqual(actual['coverage']['objects'], 3)

def test_rejects_missing_ambiguous_and_unmatched_boundaries_or_counts(self):
mutations = [lambda r: r.pop(7), lambda r: r.pop(2), lambda r: r.pop(5),
lambda r: r[6].update(operations=8), lambda r: r[6].update(thread=99),
lambda r: r.insert(8, copy.copy(r[3])), lambda r: r.insert(8, copy.copy(r[8])),
lambda r: r[8].update(stopped=False), lambda r: r[8].update(nativeOperations=8),
lambda r: r[8].update(iterations=3), lambda r: r[-1].update(failures=1),
lambda r: r[-1].update(bytes=73), lambda r: r[4].update(operations=-8),
lambda r: r[3].update(id=17), lambda r: r.reverse()]
for mutate in mutations:
rows = report()
mutate(rows)
with self.subTest(rows=rows), self.assertRaises(ValueError):
self.check(rows)
with self.assertRaisesRegex(ValueError, 'denominator'):
self.check(report(), 24)


@unittest.skipUnless(os.environ.get('TEST_NATIVE_PROFILER'), 'Native profiler fixture paths not supplied')
class NativeTailFixtureTests(unittest.TestCase):
def execute(self, count, mode):
evidence = Path(os.environ['TEST_NATIVE_OUTPUT'])
evidence.mkdir(parents=True, exist_ok=True)
path = (evidence / f'tail-{mode}-{count}.jsonl').resolve()
environment = dict(os.environ, CORECLR_ENABLE_PROFILING='1',
CORECLR_PROFILER='{32B7EF07-25E8-4AC7-B011-9A4321D702C8}',
CORECLR_PROFILER_PATH=str(Path(os.environ['TEST_NATIVE_PROFILER']).resolve()),
RELAYER_ALLOCATION_BDN_TAIL='1', RELAYER_ALLOCATION_OUTPUT=str(path))
execution = subprocess.run(['dotnet', '--roll-forward', 'Major', os.environ['TEST_NATIVE_FIXTURE'], str(count), mode],
capture_output=True, text=True, env=environment, timeout=60)
(evidence / f'tail-{mode}-{count}.log').write_text(execution.stdout + execution.stderr)
self.assertEqual(execution.returncode, 0, execution.stderr)
return path

def test_exact_final_tail_counts_exclude_timed_work_earlier_tails_and_post_stop(self):
for count in (1, 1024, 16384):
actual = read(self.execute(count, 'tail'), 8)
self.assertEqual(actual['tail']['iterations'], 2)
for name in ('FixtureMessage', 'FixtureTypes+Box`1[FixtureMessage]'):
rows = [row for row in actual['types'] if row['type'] == name]
self.assertEqual(len(rows), 1, actual['types'])
self.assertEqual(rows[0]['objects'], count)
self.assertEqual(rows[0]['bytes'], count * 24)

def test_missing_boundaries_and_events_after_stop_fail_closed(self):
for mode in ('missing-stop', 'missing-benchmark', 'extra-event'):
with self.subTest(mode=mode), self.assertRaises(ValueError):
read(self.execute(1024, mode), 8)


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