Cotton code
202 lines · 10.0 KB · PythonRaw
#!/usr/bin/env python3"""One run of scripts/perf/scroll.sh, as a table: for each list flung, theCore Animation commits over one 120 Hz frame per 10 s of flinging, thelongest and the p99 commit, the app's frame meter's late frames per 10 s andits worst frame (`DevFrames`, one line a second), the folds and blooms the fanlogged while the list was flung, and the app's own code the CPU Profilercaught most often meanwhile. Writes scroll.json and report.md beside the runand exits 1 when a list had a commit over a frame (291 row F: target zero;any hitch over one frame is a finding) or when its flings never folded thefan, which would mean the run measured a list standing still.A commit is the app's own time handing a frame to the render server; theframe meter counts a frame late past one and a half of its turn. Neither isthe phone's compositor, so a figure here is read against the same figurebefore a change, on the same simulator runtime."""import collectionsimport jsonimport osimport reimport sysfrom datetime import datetimefrom pathlib import Pathsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from report import FRAME_MAX_MS, commits, percentile, resolved, rows, trace_start, within  # noqa: E402PER_SECONDS = 10.0# The app's own binaries: a sample's innermost frame in one of these is code# a change here can move.OWN = ('CottonHomePreview', 'CottonUI', 'CottonKit')def marks(run):    """{tool: (start, end)} from the sweep's printed marks, settle aside."""    found = {}    for line in (run / 'sweep.log').read_text(errors='replace').splitlines():        m = re.search(r'scroll-sweep: mark (\w+) (start|end) ([0-9.]+)', line)        if m:            found.setdefault(m.group(1), {})[m.group(2)] = float(m.group(3))    return {tool: (edges['start'], edges['end']) for tool, edges in found.items()            if tool != 'settle' and {'start', 'end'} <= edges.keys()}def order(run):    """The tools in the order they were flung."""    seen = []    for line in (run / 'sweep.log').read_text(errors='replace').splitlines():        m = re.search(r'scroll-sweep: mark (\w+) start', line)        if m and m.group(1) != 'settle' and m.group(1) not in seen:            seen.append(m.group(1))    return seendef frame_lines(run):    """(wall s, place, turn ms, frames, late, worst ms) from the frame meter."""    out = []    path = run / 'dev-frames.log'    if not path.exists():        return out    # The place is the navigator's tile, `<database id>\x1f<tile key>`; the    # separator is whitespace to a regex, so the place is read up to the    # next field and only its key is kept.    for line in path.read_text(errors='replace').splitlines():        m = re.match(r'([0-9.]+) place=(.*?) seconds=[0-9.]+ turn_ms=([0-9.]+) frames=(\d+) late=(\d+) '                     r'late_ms=[0-9.]+ worst_ms=([0-9.]+)', line)        if m:            out.append((float(m.group(1)), m.group(2).split('\x1f')[-1], float(m.group(3)), int(m.group(4)), int(m.group(5)),                        float(m.group(6))))    return outdef folds(run):    """(wall s, 'collapsed' | 'bloomed') of every fold the fan logged. The    simulator's log stream stamps each line in this Mac's local time."""    out = []    path = run / 'fan.log'    if not path.exists():        return out    for line in path.read_text(errors='replace').splitlines():        m = re.match(r'(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d+).*fold: (collapsed|bloomed)', line)        if m:            out.append((datetime.strptime(m.group(1), '%Y-%m-%d %H:%M:%S.%f').timestamp(), m.group(2)))    return outdef own_samples(run, start):    """(wall s, symbol, main) of every CPU Profiler sample whose stack holds    the app's own code: the innermost such frame, and whether it was on the    main thread."""    out = []    path = run / 'cpu-profile.xml'    if not path.exists():        return out    for row in rows(path):        time, thread, stack = row.get('time'), row.get('thread'), row.get('stack')        if time is None or not (time.text or '').isdigit() or stack is None:            continue        frames = [resolved(f) for f in stack if f.tag == 'frame']        # The app's entry point is under every main-thread sample; it says        # only that the time went to SwiftUI or UIKit, so it is not counted.        own = [f for f in frames if any(resolved(b).attrib.get('name', '').startswith(OWN)                                       for b in f if b.tag == 'binary')               and not re.search(r'(^main|UIApplicationDelegate\.main\(\)|\$main\(\))$', f.attrib.get('name', ''))]        if not own:            continue        main = thread is not None and 'Main Thread' in (resolved(thread).attrib.get('fmt', ''))        out.append((start + int(time.text) / 1e9, own[0].attrib.get('name', ''), main))    return outdef report(run):    spans = marks(run)    tools = order(run)    start = trace_start(run)    all_commits = commits(run, start)    meter = frame_lines(run)    fan = folds(run)    cpu = own_samples(run, start)    trace = Path((run / 'trace-name.txt').read_text().strip()).name    runtime = (run / 'runtime.txt').read_text().strip() if (run / 'runtime.txt').exists() else ''    device = (run / 'device.txt').read_text().strip() if (run / 'device.txt').exists() else ''    settings = (run / 'settings.txt').read_text().strip() if (run / 'settings.txt').exists() else ''    results = []    for tool in tools:        # A sweep that stopped part way (the UI query timed out on a stuck        # list) still reports the lists it finished.        if tool not in spans:            print(f'{tool}: not measured — the sweep never finished its flings')            continue        span = spans[tool]        seconds = span[1] - span[0]        scale = PER_SECONDS / seconds if seconds > 0 else 0        work = [ms for _, ms in within(all_commits, span)]        # The commits' own pace while the list runs (a gap past 100 ms is the        # list at rest between flings): about 8.3 ms at 120 Hz, 16.7 at 60.        starts = [at for at, _ in within(all_commits, span)]        pace = [(b - a) * 1000 for a, b in zip(starts, starts[1:]) if (b - a) * 1000 < 100]        over = [ms for ms in work if ms > FRAME_MAX_MS]        # A meter line covers the second before its stamp: one stamped inside        # the span is a second of flinging.        lines = [line for line in meter if span[0] < line[0] <= span[1] + 0.5]        meter_seconds = len(lines)        late = sum(line[4] for line in lines)        folded = [kind for at, kind in fan if span[0] <= at <= span[1]]        hot = collections.Counter(symbol for at, symbol, main in cpu if span[0] <= at <= span[1] and main)        results.append({            'tool': tool, 'seconds': round(seconds, 2), 'commits': len(work),            'over_frame': len(over), 'over_frame_per_10s': round(len(over) * scale, 1),            'longest_ms': round(max(work), 2) if work else None,            'p99_ms': round(percentile(work, 0.99), 2) if work else None,            'commit_pace_ms': round(percentile(pace, 0.5), 2) if pace else None,            'meter_seconds': meter_seconds, 'meter_frames': sum(line[3] for line in lines),            'meter_late': late,            'meter_late_per_10s': round(late * PER_SECONDS / meter_seconds, 1) if meter_seconds else None,            'meter_worst_ms': max((line[5] for line in lines), default=None),            'meter_turn_ms': percentile([line[2] for line in lines], 0.5),            'meter_places': sorted({line[1] for line in lines}),            'collapsed': folded.count('collapsed'), 'bloomed': folded.count('bloomed'),            'hot': hot.most_common(8),        })    ok = bool(results) and all(r['over_frame'] == 0 and r['collapsed'] >= 1 for r in results)    out = {'run': str(run), 'trace': trace, 'device': device, 'runtime': runtime, 'settings': settings,           'frame_ms': FRAME_MAX_MS, 'tools': results, 'ok': ok}    (run / 'scroll.json').write_text(json.dumps(out, indent=2) + '\n')    show = lambda v: '—' if v is None else str(v)    text = [f'scroll perf · iOS {runtime or "unknown"} · {device} · {settings} · trace {trace}', '',            f'| list | s | commits | > {FRAME_MAX_MS} ms | per 10 s | longest ms | p99 ms | meter late /10 s '            '| meter worst ms | meter turn ms | commit pace ms | folds / blooms |',            '|---|---|---|---|---|---|---|---|---|---|---|---|']    for r in results:        text.append(f"| {r['tool']} | {r['seconds']:.1f} | {r['commits']} | {r['over_frame']} | {r['over_frame_per_10s']} "                    f"| {show(r['longest_ms'])} | {show(r['p99_ms'])} | {show(r['meter_late_per_10s'])} "                    f"| {show(r['meter_worst_ms'])} | {show(r['meter_turn_ms'])} | {show(r['commit_pace_ms'])} "                    f"| {r['collapsed']} / {r['bloomed']} |")    text.append('')    # A display link that is not asked for more ticks at 60 Hz on a ProMotion    # phone, and the simulator may draw at 60 Hz on any host: a turn of 16.7    # ms says the meter's late frames are frames over 25 ms, not over 12.5.    turns = [r['meter_turn_ms'] for r in results if r['meter_turn_ms']]    if turns and max(turns) > 10:        text.append(f'the frame meter ticked every {max(turns):.2f} ms, not 8.33: its "late" is a frame over '                    f'{1.5 * max(turns):.1f} ms; the commit columns hold the 120 Hz budget')    for r in results:        if r['hot']:            text.append(f"{r['tool']}: main thread in the app's own code — "                        + '; '.join(f'{symbol} ×{count}' for symbol, count in r['hot']))    if not meter:        text.append('no frame meter lines (dev-frames.log missing: the build lacked COTTON_DEV or the copy failed)')    text.append('')    text.append('ok: no commit over a frame and every list folded the fan' if ok                else 'FINDING: a commit over one 120 Hz frame, or a list whose flings never folded the fan')    body = '\n'.join(text) + '\n'    (run / 'report.md').write_text(body)    print(body, end='')    return 0 if ok else 1if __name__ == '__main__':    sys.exit(report(Path(sys.argv[1])))