1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/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())