Cotton code
372 lines · 17.8 KB · PythonRaw
#!/usr/bin/env python3"""The fan's budgets from one run of scripts/perf/fan.sh: reads the run folder(sweep marks, the xctrace export, usage and footprint samples, the fan's log,cold starts), prints the table, writes fan.json beside it and exits 1 when afigure is over its budget.The budgets are the owner's (fanperf brief, 15 Oct 2026): frame work whileturning — no frame over 8.3 ms, p99 under 6 ms; at rest — no Core Animationcommit, no CPU beyond the floor; page pictures within fan.md's bound (about150 KB each, compressed) and no growth across 100 turns; energy impact Lowover a minute of swiping; cold start to the fan's first frame no slower thanthe grid Home's, measured alternately on the same simulator and build (fan3part 0: pagespeed's own grid Home starts in 2.2–2.3 s on one Mac's iOS 27simulator, where the 942 ms it once measured does not hold)."""import jsonimport osimport reimport statisticsimport sysimport xml.etree.ElementTree as ETfrom datetime import datetimefrom pathlib import Pathsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from simulator import RUNTIME  # noqa: E402# ── Budgets ────────────────────────────────────────────────────────────────FRAME_MAX_MS = 8.3          # one 120 Hz frameFRAME_P99_MS = 6.0REST_COMMITS = 0            # Core Animation commits while the fan restsREST_CPU_PCT = 0.5          # the floor an idle process is chargedPICTURE_KB_EACH = 150       # fan.md: ~150 KB of compressed picture per tileGROWTH_MB = 2.0             # footprint after 100 turns over before them# Energy impact Low: Activity Monitor's score reads Low below about 20, a fifth# of one busy core. usage.py reads the energy the process is charged# (ri_energy_nj) instead of top's score (top is setuid; a lane's seatbelt# refuses it), and one busy core on the signing Mac is charged 6.6 W, so a fifth of# it is 1.3 W (fanperf2, 15 Oct 2026).ENERGY_LOW_MW = 1300.0# A budget known to be over, with the number last measured: it stays red —# never passed, never hidden — and its row and its guard say KNOWN and that# number (architect, 15 Oct 2026). Remove the entry when the figure is back# under budget. growth.py reads it too.KNOWN = {}# One run's growth: a footprint sample minus another, 2 s apart samples# swing 4-5 MB on the simulator (fanperf2, 15 Oct 2026). Reported here; the# budget is growth.py's over many runs.GROWTH_ONE_RUN = 'growth over the turns, one run (report only)'COLD_MS = 942               # pagespeed's cold start to Home's first frame, for referenceCOLD_OVER_GRID_PCT = 5.0    # the fan's cold start over the grid Home's, at most# A gap this long between two commits is the fan at rest between swipes, not a frame.IDLE_GAP_MS = 100def turns_made(run):    """The turns the growth phase made (run-simulator.sh writes them)."""    path = run / 'turns.txt'    return int(path.read_text().strip()) if path.exists() else 100def growth(run):    """The footprint after the growth phase's turns over the one before them,    as (MB, before, after), or None without samples."""    found = marks(run)    feet = footprints(run)    turns_span = window(found, 'turns')    before = [mb for at, mb in feet if turns_span[0] - 4 <= at <= turns_span[0] + 1]    after = [mb for at, mb in feet if found[('turns', 'end')] <= at <= found[('after', 'end')]]    return (after[-1] - before[0], before[0], after[-1]) if before and after else Nonedef marks(run):    found = {}    for line in (run / 'sweep.log').read_text(errors='replace').splitlines():        m = re.search(r'fan-sweep: mark (\w+) (start|end) ([0-9.]+)', line)        if m:            found[(m.group(1), m.group(2))] = float(m.group(3))    return founddef window(found, phase, until=None):    return found[(phase, 'start')], found[(until or phase, 'end')]IDS = {}def resolved(element):    """The element a `ref` names, or the element itself."""    return IDS.get(element.attrib['ref'], element) if 'ref' in element.attrib else elementdef rows(path):    """The rows of one exported xctrace table, each a list of (mnemonic,    element) with every `ref` resolved to the element it names."""    root = ET.parse(path).getroot()    ids = IDS    ids.clear()    for element in root.iter():        if 'id' in element.attrib:            ids[element.attrib['id']] = element    schema = root.find('.//schema')    if schema is None:        return []    columns = [col.findtext('mnemonic') for col in schema.findall('col')]    out = []    for row in root.iter('row'):        cells = []        for element in row:            if 'ref' in element.attrib:                element = ids.get(element.attrib['ref'], element)            cells.append(element)        out.append(dict(zip(columns, cells)))    return outdef trace_start(run):    toc = ET.parse(run / 'toc.xml').getroot()    text = toc.findtext('.//run/info/summary/start-date')    return datetime.fromisoformat(text.replace('Z', '+00:00')).timestamp()def commits(run, start):    """(wall start s, duration ms) of every Core Animation commit."""    out = []    for row in rows(run / 'commits.xml'):        begin, duration = row.get('start'), row.get('duration')        if begin is None or duration is None or not (begin.text or '').isdigit():            continue        out.append((start + int(begin.text) / 1e9, int(duration.text) / 1e6))    return sorted(out)def samples(run, start):    """(wall time s, thread id, symbol) of every CPU Profiler sample; the    symbol is the innermost frame in the app's own code when there is one,    else the innermost frame."""    out = []    path = run / 'cpu-profile.xml'    if not path.exists():        return out    for row in rows(path):        time, thread, backtrace = row.get('time'), row.get('thread'), row.get('stack')        if time is None or not (time.text or '').isdigit():            continue        tid = thread.findtext('tid') if thread is not None else None        symbol = ''        if backtrace is not None:            frames = [resolved(f) for f in backtrace if f.tag == 'frame']            own = [f for f in frames if any(resolved(b).attrib.get('name', '').startswith(('CottonHomePreview', 'CottonUI', 'CottonKit'))                                           for b in f if b.tag == 'binary')]            pick = (own or frames)[:1]            symbol = pick[0].attrib.get('name', '') if pick else ''        out.append((start + int(time.text) / 1e9, tid, symbol))    return outdef within(items, span, at=lambda item: item[0]):    low, high = span    return [item for item in items if low <= at(item) <= high]def percentile(values, share):    if not values:        return None    ordered = sorted(values)    return ordered[min(len(ordered) - 1, int(round(share * (len(ordered) - 1))))]def usage_samples(run):    """(wall s, cpu %, energy mW, idle wakeups /s) from usage.py, one a second."""    out = []    for line in (run / 'usage.txt').read_text(errors='replace').splitlines():        parts = line.split()        if len(parts) == 5:            try:                wall, cpu, idle, _interrupt, energy = map(float, parts)            except ValueError:                continue            out.append((wall, cpu, energy, idle))    return outdef footprints(run):    out = []    scale = {'KB': 1 / 1024, 'MB': 1, 'GB': 1024}    for line in (run / 'footprint.txt').read_text(errors='replace').splitlines():        parts = line.split()        if len(parts) == 3 and parts[2] in scale:            out.append((float(parts[0]), float(parts[1]) * scale[parts[2]]))    return outdef fan_log(run):    turns, pictures = [], None    for line in (run / 'fan.log').read_text(errors='replace').splitlines():        m = re.search(r'turn: (\d+) tiles, (\d+) frames, budget ([0-9.]+) ms, longest ([0-9.]+) ms, p95 ([0-9.]+) ms, late (\d+)', line)        if m:            turns.append({'frames': int(m.group(2)), 'budget': float(m.group(3)), 'longest': float(m.group(4)),                          'p95': float(m.group(5)), 'late': int(m.group(6))})        m = re.search(r'pictures: (\d+) tiles, (\d+) kept, (\d+) KB compressed, (\d+) decoded, (\d+) KB decoded', line)        if m:            pictures = {'tiles': int(m.group(1)), 'kept': int(m.group(2)), 'compressed_kb': int(m.group(3)),                        'decoded': int(m.group(4)), 'decoded_kb': int(m.group(5))}    return turns, picturesdef colds(run, name='cold.txt'):    out = []    path = run / name    if not path.exists():        return out    for line in path.read_text(errors='replace').splitlines():        line = line.strip()        if line:            try:                out.append(float(json.loads(line)['cold_ms']))            except (ValueError, KeyError):                continue    return outdef report(run):    found = marks(run)    start = trace_start(run)    all_commits = commits(run, start)    all_samples = samples(run, start)    usage = usage_samples(run)    feet = footprints(run)    turns, pictures = fan_log(run)    trace = Path((run / 'trace-name.txt').read_text().strip()).name    # The runtime the run was measured on. A budget passes only on the owner's    # (simulator.RUNTIME): the fan's memory is a different story on iOS 27.    runtime = (run / 'runtime.txt').read_text().strip() if (run / 'runtime.txt').exists() else ''    owners = (runtime + '.').startswith(RUNTIME + '.')    figures = []    def figure(name, value, budget, ok, unit, note=''):        figures.append({'budget_name': name, 'value': value, 'budget': budget, 'ok': bool(ok) and owners, 'unit': unit,                        'note': note, 'trace': trace, 'runtime': runtime, 'known': KNOWN.get(name, '')})    figure('runtime', runtime or None, RUNTIME, True, 'iOS',           f"the owner's phone runs iOS {RUNTIME}; no budget passes on another runtime")    # (a) Frame work while turning: each commit's duration is the app's own    # time handing a frame to the render server.    turn = window(found, 'turn')    work = [ms for _, ms in within(all_commits, turn)]    starts = [at for at, _ in within(all_commits, turn)]    gaps = [(b - a) * 1000 for a, b in zip(starts, starts[1:]) if (b - a) * 1000 < IDLE_GAP_MS]    worst = max(work) if work else None    p99 = percentile(work, 0.99)    figure('frame work max', worst, FRAME_MAX_MS, worst is not None and worst <= FRAME_MAX_MS, 'ms',           f'{len(work)} commits in {turn[1] - turn[0]:.0f} s of turning')    figure('frame work p99', p99, FRAME_P99_MS, p99 is not None and p99 < FRAME_P99_MS, 'ms')    turn_lines = [t for t in turns]    # Every figure is of the one process the trace followed.    traced = (run / 'app-pid.txt').read_text().strip()    pids = set(re.findall(r'CottonHomePreview\[(\d+)', (run / 'fan.log').read_text(errors='replace')))    figure('one app process', len(pids), 1, pids <= {traced}, 'processes',           f'traced {traced}; the fan logged from {", ".join(sorted(pids)) or "none"}')    # A run whose swipes never turned the fan measures nothing: refuse it.    figure('turns logged', len(turn_lines), 1, len(turn_lines) >= 1, 'turns',           'the fan logs one line per turn; none means the swipes missed the deck')    late = sum(t['late'] for t in turn_lines)    longest = max((t['longest'] for t in turn_lines), default=None)    figure('late frames (fan log)', late, 0, True, 'frames',           f"longest interval {longest} ms over {len(turn_lines)} turns; commit gap p99 {percentile(gaps, 0.99)} ms — report only: the simulator's own compositor paces these")    # (a') Frame work while the fan folds into the circle and blooms out of    # it (fancollapse): the same 120 Hz frame, over a run that did fold.    if ('fold', 'start') in found:        fold = window(found, 'fold')        fold_work = [ms for _, ms in within(all_commits, fold)]        folds = len(re.findall(r'fold: (?:collapsed|bloomed)', (run / 'fan.log').read_text(errors='replace')))        fold_worst = max(fold_work) if fold_work else None        figure('fold frame work max', fold_worst, FRAME_MAX_MS,               folds >= 2 and fold_worst is not None and fold_worst <= FRAME_MAX_MS, 'ms',               f'{len(fold_work)} commits over {folds} folds and blooms in {fold[1] - fold[0]:.0f} s'               + ('' if folds >= 2 else ' — the scrolls never folded the fan'))    # (b) At rest.    rest = window(found, 'rest')    rest_commits = within(all_commits, rest)    figure('rest commits', len(rest_commits), REST_COMMITS, len(rest_commits) <= REST_COMMITS, 'commits',           f'{(rest[1] - rest[0]):.0f} s with the fan showing')    rest_usage = within(usage, (rest[0] + 1, rest[1]))    cpu = statistics.fmean(t[1] for t in rest_usage) if rest_usage else None    wakeups = statistics.fmean(t[3] for t in rest_usage) if rest_usage else None    figure('rest CPU', cpu, REST_CPU_PCT, cpu is not None and cpu <= REST_CPU_PCT, '%',           f'idle wakeups {wakeups:.1f}/s' if wakeups is not None else '')    rest_samples = within(all_samples, rest)    # The main thread is the process's first: the lowest thread id sampled.    tids = [int(s[1]) for s in all_samples if (s[1] or '').isdigit()]    main_tid = str(min(tids)) if tids else None    main = [s for s in rest_samples if s[1] == main_tid]    leaves = {}    for _, _, leaf in main:        leaves[leaf] = leaves.get(leaf, 0) + 1    busiest = ', '.join(f'{name} ×{count}' for name, count in sorted(leaves.items(), key=lambda kv: -kv[1])[:3])    figure('rest main-thread samples', len(main), 0, len(main) == 0, 'samples', busiest)    # (b') A record risen over the fan, at rest: the same rule.    if ('record', 'start') in found:        held = window(found, 'record')        held_commits = within(all_commits, held)        figure('record rest commits', len(held_commits), REST_COMMITS, len(held_commits) <= REST_COMMITS, 'commits',               f'{(held[1] - held[0]):.0f} s with a record over the fan')        held_usage = within(usage, (held[0] + 1, held[1]))        held_cpu = statistics.fmean(t[1] for t in held_usage) if held_usage else None        figure('record rest CPU', held_cpu, REST_CPU_PCT, held_cpu is not None and held_cpu <= REST_CPU_PCT, '%')        held_main = [s for s in within(all_samples, held) if s[1] == main_tid]        names = {}        for _, _, leaf in held_main:            names[leaf] = names.get(leaf, 0) + 1        figure('record rest main-thread samples', len(held_main), 0, len(held_main) == 0, 'samples',               ', '.join(f'{name} ×{count}' for name, count in sorted(names.items(), key=lambda kv: -kv[1])[:3]))    # (c) Memory.    if pictures:        bound = PICTURE_KB_EACH * pictures['tiles']        figure('page pictures', pictures['compressed_kb'], bound, pictures['compressed_kb'] <= bound, 'KB',               f"{pictures['tiles']} tiles kept compressed; {pictures['decoded']} decoded, {pictures['decoded_kb']} KB")    else:        figure('page pictures', None, PICTURE_KB_EACH * 30, False, 'KB', 'the fan never logged its pictures line')    grown = growth(run)    figure(GROWTH_ONE_RUN, grown and grown[0], GROWTH_MB, True, 'MB',           (f'footprint {grown[1]:.0f} → {grown[2]:.0f} MB over {turns_made(run)} turns; the budget is growth.py\'s '            'median of five runs' if grown else 'no footprint samples'))    # (d) Energy over a minute of swiping.    energy = window(found, 'energy')    swiping = within(usage, energy)    impact = statistics.fmean(t[2] for t in swiping) if swiping else None    swipe_cpu = statistics.fmean(t[1] for t in swiping) if swiping else None    figure('energy impact', impact, ENERGY_LOW_MW, impact is not None and impact < ENERGY_LOW_MW, 'mW',           f'CPU {swipe_cpu:.1f}% mean over {energy[1] - energy[0]:.0f} s' if swipe_cpu is not None else '')    # (e) Cold start.    cold = colds(run)    grid = colds(run, 'cold-grid.txt')    median = statistics.median(cold) if cold else None    grid_median = statistics.median(grid) if grid else None    limit = grid_median * (1 + COLD_OVER_GRID_PCT / 100) if grid_median is not None else None    figure('cold start', median, round(limit, 1) if limit is not None else None,           median is not None and limit is not None and median <= limit, 'ms',           f"fan median of {len(cold)}: {', '.join(f'{c:.0f}' for c in cold)}; grid Home "           + (f"{grid_median:.0f} ms ({', '.join(f'{c:.0f}' for c in grid)})" if grid else 'not measured')           + f"; limit the grid's + {COLD_OVER_GRID_PCT:.0f}%")    # The figure itself is reported, not guarded, on the simulator (architect,    # 15 Oct 2026): the phone's own cold start from MetricKit is the owner's.    figure('cold start, absolute (report only)', median, COLD_MS, True, 'ms',           f"pagespeed's {COLD_MS} ms for reference; the simulator's linker takes most of it")    device = (run / 'device.txt').read_text().strip() if (run / 'device.txt').exists() else ''    result = {'run': str(run), 'trace': trace, 'device': device, 'runtime': runtime, 'figures': figures,              'ok': all(f['ok'] for f in figures)}    (run / 'fan.json').write_text(json.dumps(result, indent=2) + '\n')    lines = [f'fan perf · iOS {runtime or "unknown"} · {device} · trace {trace}', '',             '| budget | figure | limit | ok | note |', '|---|---|---|---|---|']    for f in figures:        value = '—' if f['value'] is None else (f"{f['value']:.2f}" if isinstance(f['value'], float) else str(f['value']))        lines.append(f"| {f['budget_name']} | {value} {f['unit']} | {f['budget']} | {'✓' if f['ok'] else '✗ KNOWN' if f['known'] else '✗'} | {f['note']}{' — ' + f['known'] if f['known'] and not f['ok'] else ''} |")    text = '\n'.join(lines) + '\n'    (run / 'report.md').write_text(text)    print(text, end='')    return 0 if result['ok'] else 1if __name__ == '__main__':    sys.exit(report(Path(sys.argv[1])))