#!/usr/bin/env python3"""Inside pages, timed on a simulator from the phone's own file (lanethreadload, 16 Oct 2026). pages.py fixture <household> <state> a phone's state off a seeded household pages.py run <sim> <app> <state> <out> [--times N] pages.py times <open.log> the table, off a run's log pages.py walk <state> <household> <headless> 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) intothe folder layout a phone opens (`client/connection.json`,`client/<database>/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 `<state>/routes.json`.`run` installs the built Cotton Dev app on the simulator, puts the state inits data folder, launches it and opens each route, Homebetween, `--times` rounds (default 5) — the app opens them itself(`-page-walk`), so no system dialog is timed — while `log stream` keeps the pageclock's lines (`PageClock`: subsystem com.cottondb.page, category open).`times` prints, per route, the median and slowest milliseconds from the pushto the record drawn (`record`), the chat's messages drawn (`messages`) andeverything read (`settled`).Synthetic data only: the household is `cotton-headless seed`'s invention andthe app is Cotton Dev; nothing here reads or opens the owner's files."""import jsonimport reimport shutilimport sqlite3import statisticsimport subprocessimport sysimport timefrom pathlib importPathBUNDLE = "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 elseNonedef fixture(household: Path, state: Path) -> None: files = sorted(household.glob("files/*/*/life.db"))ifnot files:raiseSystemExit(f"no database files under {household}/files — seed it with cotton-headless seed")ifnot (household / ".cotton-headless.lock").exists() andnot (household / "registry.db").exists():raiseSystemExit(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.ifnot (state / MARK).is_file():raiseSystemExit(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 isnot 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"["notin p andnot 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/<udid>/data/Containers/Data/Application/<uuid>.ifnot re.search(r"/CoreSimulator/Devices/[0-9A-F-]{36}/data/Containers/Data/Application/[0-9A-F-]{36}$", str(data)):raiseSystemExit(f"not a simulator app container: {data}")if folder.is_symlink():raiseSystemExit(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 = 0while time.time() < deadline and"walk: done"notin (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 outdef 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} -" + " " * 11for mark in MARKS) print(f"{route[:48]:<48} {cells}") (log.parent / "pages.json").write_text(json.dumps(summary, indent=2))return summarydef main(argv):if len(argv) >= 3and argv[0] == "fixture": fixture(Path(argv[1]).expanduser().resolve(), Path(argv[2]).expanduser().resolve())elif len(argv) >= 5and argv[0] == "run": times = int(argv[argv.index("--times") + 1]) if"--times"in argv else5 run(argv[1], Path(argv[2]), Path(argv[3]).resolve(), Path(argv[4]).resolve(), times)elif len(argv) >= 4and argv[0] == "walk": walk_routes(Path(argv[1]).resolve(), Path(argv[2]).expanduser().resolve(), argv[3])elif len(argv) >= 2and argv[0] == "times": table(Path(argv[1]))else:raiseSystemExit(__doc__)if __name__ == "__main__": main(sys.argv[1:])