#!/usr/bin/env python3 """Inside pages, timed on a simulator from the phone's own file (lane threadload, 16 Oct 2026). pages.py fixture a phone's state off a seeded household pages.py run [--times N] pages.py times the table, off a run's log pages.py walk every tool's root and one record of each kind `fixture` copies every database file of a `cotton-headless seed` household (`--size lists`: a chat of 2,000 messages, 5,000 photos, 3,000 people) into the folder layout a phone opens (`client/connection.json`, `client//replica.db`), joined to a server that does not exist (`https://synthetic.invalid`): the phone reads its own file and nothing else. It names one record of each kind the run opens in `/routes.json`. `run` installs the built Cotton Dev app on the simulator, puts the state in its data folder, launches it and opens each route, Home between, `--times` rounds (default 5) β€” the app opens them itself (`-page-walk`), so no system dialog is timed β€” while `log stream` keeps the page clock's lines (`PageClock`: subsystem com.cottondb.page, category open). `times` prints, per route, the median and slowest milliseconds from the push to the record drawn (`record`), the chat's messages drawn (`messages`) and everything read (`settled`). Synthetic data only: the household is `cotton-headless seed`'s invention and the app is Cotton Dev; nothing here reads or opens the owner's files. """ import json import re import shutil import sqlite3 import statistics import subprocess import sys import time from pathlib import Path BUNDLE = "com.cottondb.cotton.dev" SCHEME = "cottondev" MARKS = ["record", "messages", "settled"] # The file a fixture state carries, so a re-run replaces only its own folder. MARK = ".pages-state" def one(db, sql): row = db.execute(sql).fetchone() return row[0] if row else None def fixture(household: Path, state: Path) -> None: files = sorted(household.glob("files/*/*/life.db")) if not files: raise SystemExit(f"no database files under {household}/files β€” seed it with cotton-headless seed") if not (household / ".cotton-headless.lock").exists() and not (household / "registry.db").exists(): raise SystemExit(f"{household} is not a cotton-headless household") if state.exists(): # Only a state this script made (its marker) is replaced, never a # folder a caller named by mistake. if not (state / MARK).is_file(): raise SystemExit(f"{state} exists and is not a pages.py state (no {MARK}); remove it yourself") shutil.rmtree(state) client = state / "client" databases = [] for path in files: with sqlite3.connect(path) as db: workspace, owner, kind = db.execute("SELECT id, owner_user_id, kind FROM cotton_workspaces").fetchone() databases.append((path, workspace, owner, kind)) personal = next(d for d in databases if d[3] == "personal") places = [d for d in databases if d is not personal] for path, workspace, _, _ in databases: target = client / workspace / "replica.db" target.parent.mkdir(parents=True, exist_ok=True) with sqlite3.connect(path) as source, sqlite3.connect(target) as copy: source.backup(copy) (state / MARK).write_text("made by scripts/perf/pages.py fixture\n") (client / "connection.json").write_text(json.dumps(dict( mode="remote", baseUrl="https://synthetic.invalid", workspaceId=personal[1], ownerId=personal[2], connectedAt="2026-10-16T00:00:00.000Z", places=[dict(id=d[1], name=f"Synthetic project {i}", available=True, unavailableSince=None) for i, d in enumerate(places)]))) with sqlite3.connect(personal[0]) as db: routes = { "thread": one(db, "SELECT thread_id FROM cotton_msg_messages GROUP BY thread_id ORDER BY count(*) DESC LIMIT 1"), "person": one(db, "SELECT id FROM cotton_people WHERE archived_at IS NULL ORDER BY updated_at DESC LIMIT 1"), "note": one(db, "SELECT id FROM cotton_notes WHERE kind = 'note' AND trashed_at IS NULL ORDER BY updated_at DESC LIMIT 1"), "album": one(db, "SELECT a.id FROM cotton_media_albums a JOIN cotton_media_album_items i ON i.album_id = a.id " "WHERE a.trashed_at IS NULL GROUP BY a.id ORDER BY count(*) DESC LIMIT 1"), "email": one(db, "SELECT id FROM cotton_email_threads WHERE trashed_at IS NULL ORDER BY email_count DESC LIMIT 1"), } paths = { "thread": "/messages/{}", "person": "/people/person/{}", "note": "/notes/note/{}", "album": "/photos/album/{}", "email": "/email/{}", } named = {kind: paths[kind].format(id) for kind, id in routes.items() if id} (state / "routes.json").write_text(json.dumps(named, indent=2)) print(json.dumps(named, indent=2)) def walk_routes(state: Path, household: Path, headless: str) -> None: """The offline walk's routes: every root the app names (no record id, no action), then one record of each kind whose definition names a record route, its id the first its list answers. Replaces `routes.json`.""" root = Path(__file__).resolve().parents[2] text = (root / "apps/cotton/Sources/CottonMailbox/Route.swift").read_text() patterns = re.findall(r'^ "(/[^"]*)",$', text, flags=re.M) roots = [p for p in patterns if "[" not in p and not re.search(r"/(new|import|add|capture|take)$", p) and p != "/"] calls, routes = [], {} for path in sorted((root / "crates/cotton-core/definitions").glob("*.json")): definition = json.loads(path.read_text()) route = definition.get("record_route") or "" if "[id]" in route: calls.append({"name": definition["id"], "method": "records.list", "args": {"table": definition["id"], "page": 0, "limit": 1}}) routes[definition["id"]] = route out = subprocess.run([headless, "time", "--calls", json.dumps(calls), "--times", "1", "--data-dir", str(household)], capture_output=True, text=True) records = {} for line in out.stdout.splitlines(): if line.startswith("{"): timed = json.loads(line) if timed.get("ids"): records[timed["name"]] = routes[timed["name"]].replace("[id]", timed["ids"][0]) named = {f"root {r}": r for r in roots} named.update({f"record {k}": v for k, v in sorted(records.items())}) (state / "routes.json").write_text(json.dumps(named, indent=2)) print(f"{len(roots)} roots, {len(records)} records") def simctl(*args, check=True): return subprocess.run(["xcrun", "simctl", *args], check=check, capture_output=True, text=True) def run(sim: str, app: Path, state: Path, out: Path, times: int) -> None: routes = json.loads((state / "routes.json").read_text()) out.mkdir(parents=True, exist_ok=True) simctl("terminate", sim, BUNDLE, check=False) simctl("install", sim, str(app)) simctl("privacy", sim, "grant", "all", BUNDLE, check=False) data = Path(simctl("get_app_container", sim, BUNDLE, "data").stdout.strip()) folder = data / "Library/Application Support/Cotton" # The app's own data folder inside a simulator's container, and nothing # else: CoreSimulator/Devices//data/Containers/Data/Application/. if not re.search(r"/CoreSimulator/Devices/[0-9A-F-]{36}/data/Containers/Data/Application/[0-9A-F-]{36}$", str(data)): raise SystemExit(f"not a simulator app container: {data}") if folder.is_symlink(): raise SystemExit(f"{folder} is a symlink") if folder.exists(): shutil.rmtree(folder) folder.mkdir(parents=True) shutil.copytree(state / "client", folder / "client") log = out / "open.log" stream = subprocess.Popen( ["xcrun", "simctl", "spawn", sim, "log", "stream", "--level", "info", "--style", "compact", "--predicate", 'subsystem == "com.cottondb.page" AND category == "open"'], stdout=open(log, "w"), stderr=subprocess.DEVNULL) try: # The app opens each route itself (`PageWalk`): a deep link from # outside raises the system's "Open in…?" and times the dialog. simctl("launch", sim, BUNDLE, "-page-walk", ",".join(routes.values()), "-page-walk-rounds", str(times)) deadline = time.time() + 60 + times * len(routes) * 6 shot = 0 while time.time() < deadline and "walk: done" not in (text := log.read_text()): # Each page of the first round, as it stood 2.5 s after its push. if shot < len(routes) and text.count(" asked") > shot: time.sleep(2.5) subprocess.run(["xcrun", "simctl", "io", sim, "screenshot", str(out / f"page-{shot}.png")], capture_output=True) shot += 1 time.sleep(0.3) subprocess.run(["xcrun", "simctl", "io", sim, "screenshot", str(out / "end.png")], capture_output=True) finally: stream.terminate() stream.wait() table(log) ASKED = re.compile(r"open: (\S+) asked") MARK = re.compile(r"open: (\S+) (\w+) (\d+) ms") def opens(lines): out = [] for line in lines: if m := ASKED.search(line): out.append({"route": m.group(1)}) elif (m := MARK.search(line)) and out and out[-1]["route"] == m.group(1): out[-1].setdefault(m.group(2), int(m.group(3))) return out def table(log: Path) -> dict: by_route = {} for opened in opens(log.read_text().splitlines()): by_route.setdefault(opened["route"], []).append(opened) summary = {} for route, runs in by_route.items(): row = {} for mark in MARKS: values = [r[mark] for r in runs if mark in r] if values: row[mark] = {"median": statistics.median(values), "max": max(values), "n": len(values)} summary[route] = row cells = " ".join( f"{mark} {row[mark]['median']:>5.0f} (max {row[mark]['max']:>5.0f})" if mark in row else f"{mark} -" + " " * 11 for mark in MARKS) print(f"{route[:48]:<48} {cells}") (log.parent / "pages.json").write_text(json.dumps(summary, indent=2)) return summary def main(argv): if len(argv) >= 3 and argv[0] == "fixture": fixture(Path(argv[1]).expanduser().resolve(), Path(argv[2]).expanduser().resolve()) elif len(argv) >= 5 and argv[0] == "run": times = int(argv[argv.index("--times") + 1]) if "--times" in argv else 5 run(argv[1], Path(argv[2]), Path(argv[3]).resolve(), Path(argv[4]).resolve(), times) elif len(argv) >= 4 and argv[0] == "walk": walk_routes(Path(argv[1]).resolve(), Path(argv[2]).expanduser().resolve(), argv[3]) elif len(argv) >= 2 and argv[0] == "times": table(Path(argv[1])) else: raise SystemExit(__doc__) if __name__ == "__main__": main(sys.argv[1:])