#!/usr/bin/env python3 """Summarize Old Fella frame delays within a complete scrolling interval.""" import argparse import json import math from pathlib import Path import re import subprocess import sys import xml.etree.ElementTree as ET class InvalidTrace(ValueError): pass def export(trace, suffix, xpath=None): output = trace.with_suffix(suffix) command = ["xcrun", "xctrace", "export", "--input", str(trace)] command += ["--xpath", xpath] if xpath else ["--toc"] command += ["--output", str(output)] result = subprocess.run(command, capture_output=True, text=True, timeout=240) if result.returncode != 0: detail = result.stderr.strip() or result.stdout.strip() raise InvalidTrace(f"The trace export failed: {detail}") try: return ET.parse(output).getroot(), output except (ET.ParseError, OSError) as error: raise InvalidTrace(f"The trace export is not valid XML: {output}") from error def table_rows(root, name, required): nodes = [node for node in root.findall("node") if node.find("schema") is not None and node.find("schema").get("name") == name] if len(nodes) != 1: raise InvalidTrace(f"The trace must contain one {name} table.") node = nodes[0] columns = [column.findtext("mnemonic") for column in node.find("schema").findall("col")] if not set(required).issubset(columns): raise InvalidTrace(f"The {name} table is missing required columns.") identifiers = {element.get("id"): element for element in root.iter() if element.get("id")} def resolve(element): visited = set() while element.get("ref"): reference = element.get("ref") if reference in visited or reference not in identifiers: raise InvalidTrace(f"The {name} table contains an invalid XML reference.") visited.add(reference) element = identifiers[reference] return element rows = [] for row in node.findall("row"): if len(row) != len(columns): raise InvalidTrace(f"The {name} table contains an incomplete row.") rows.append({column: resolve(value) for column, value in zip(columns, row)}) return rows def value(element): return element.get("fmt", element.text or "") def number(element): try: result = int(element.text) except (TypeError, ValueError) as error: raise InvalidTrace("The trace contains an incomplete timestamp or duration.") from error return result def process_name(element): return re.sub(r" \(\d+\)$", "", value(element)) def recording_run(toc, minimum_seconds): runs = toc.findall("run") if len(runs) != 1: raise InvalidTrace("The trace must contain exactly one recording run.") run = runs[0] try: trace_seconds = float(run.findtext("info/summary/duration")) except (TypeError, ValueError) as error: raise InvalidTrace("The trace has no recording duration.") from error if not math.isfinite(trace_seconds) or trace_seconds < minimum_seconds: raise InvalidTrace("The recording is shorter than the requested scrolling interval.") app_processes = [process.attrib for process in run.findall("processes/process") if process.get("name") == "OldFella"] if not app_processes: raise InvalidTrace("The trace contains no Old Fella process.") return trace_seconds, app_processes def summarize(toc, intervals, frames, hitches, minimum_seconds): trace_seconds, app_processes = recording_run(toc, minimum_seconds) matching = [row for row in table_rows( intervals, "OSSignpostIntervals", ("start", "duration", "name", "subsystem", "process", "end-process") ) if value(row["name"]) == "OldFellaScrollProfile" and value(row["subsystem"]) == "com.oldfella.profiling"] if len(matching) != 1: raise InvalidTrace("The trace must contain one complete OldFellaScrollProfile interval.") interval = matching[0] if interval["process"].tag != "process" or interval["end-process"].tag != "process": raise InvalidTrace("The scrolling interval is missing its start or end event.") if value(interval["process"]) != value(interval["end-process"]): raise InvalidTrace("The scrolling interval starts and ends in different processes.") if process_name(interval["process"]) != "OldFellaUITests-Runner": raise InvalidTrace("The scrolling interval did not come from the Old Fella scrolling driver.") start = number(interval["start"]) duration = number(interval["duration"]) end = start + duration if start < 0 or duration < minimum_seconds * 1e9: raise InvalidTrace("The scrolling interval is shorter than the requested duration.") if end > round(trace_seconds * 1e9) + 1_000_000: raise InvalidTrace("The scrolling interval extends beyond the recording.") frame_rows = table_rows(frames, "hitches-frame-lifetimes", ("start", "duration")) captured_frames = [row for row in frame_rows if number(row["start"]) < end and number(row["start"]) + number(row["duration"]) > start] if not captured_frames: raise InvalidTrace("The scrolling interval contains no frame records. Do not report zero hitches.") delays = [] for row in table_rows(hitches, "hitches", ("start", "duration", "process", "is-system")): if process_name(row["process"]) != "OldFella" or number(row["is-system"]) != 0: continue hitch_start = number(row["start"]) hitch_duration = number(row["duration"]) overlap = min(hitch_start + hitch_duration, end) - max(hitch_start, start) if overlap <= 0: continue delays.append({ "start_seconds": hitch_start / 1e9, "duration_ms": hitch_duration / 1e6, "delay_within_interval_ms": overlap / 1e6, "process": value(row["process"]), "description": value(row["narrative-description"]) if "narrative-description" in row else "", }) delays.sort(key=lambda row: row["start_seconds"]) return { "valid": True, "process_name": "OldFella", "app_processes": app_processes, "trace_duration_seconds": trace_seconds, "minimum_scroll_seconds": minimum_seconds, "interval": { "name": "OldFellaScrollProfile", "start_seconds": start / 1e9, "end_seconds": end / 1e9, "elapsed_seconds": duration / 1e9, "driver_process": value(interval["process"]), }, "capture_frame_records_in_interval": len(captured_frames), "frame_record_scope": "These records cover captured display surfaces. They are not an app frame count or an FPS measurement.", "hitch_count": len(delays), "total_delay_ms": sum(row["delay_within_interval_ms"] for row in delays), "max_delay_ms": max((row["delay_within_interval_ms"] for row in delays), default=0), "delay_scope": "Only Old Fella hitches that overlap the scrolling interval are included. Boundary durations are clipped to that interval.", "hitches": delays, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("trace", type=Path) parser.add_argument("--seconds", type=float, required=True, metavar="MINIMUM") args = parser.parse_args() if not math.isfinite(args.seconds) or args.seconds <= 0: parser.error("--seconds must be a finite number greater than zero.") trace = args.trace.resolve() if trace.suffix != ".trace" or not trace.is_dir(): parser.error("Supply a completed .trace directory.") summary_path = trace.with_suffix(".summary.json") try: toc, toc_path = export(trace, ".toc.xml") recording_run(toc, args.seconds) tables = {} artifacts = {"toc": str(toc_path)} for schema, suffix in (("OSSignpostIntervals", ".intervals.xml"), ("hitches-frame-lifetimes", ".frames.xml"), ("hitches", ".hitches.xml")): tables[schema], path = export( trace, suffix, f'/trace-toc/run[@number="1"]/data/table[@schema="{schema}"]' ) artifacts[schema] = str(path) summary = summarize(toc, tables["OSSignpostIntervals"], tables["hitches-frame-lifetimes"], tables["hitches"], args.seconds) summary.update({"trace": str(trace), "exports": artifacts}) summary_path.write_text(json.dumps(summary, indent=2) + "\n") print(f"OldFella: {summary['hitch_count']} hitches, total delay {summary['total_delay_ms']:.2f} ms, " f"maximum delay {summary['max_delay_ms']:.2f} ms, " f"scrolling interval {summary['interval']['elapsed_seconds']:.2f} s.") print(f"Saved the summary: {summary_path}") except (InvalidTrace, OSError, subprocess.TimeoutExpired) as error: summary_path.write_text(json.dumps({"valid": False, "trace": str(trace), "error": str(error)}, indent=2) + "\n") print(f"Cannot measure this trace: {error}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": sys.exit(main())