//! How long the core takes, from `open` to the first screen's answer, for//! Story, Days and Notes over invented data of a real size (100 scenes of 40//! lines; a few hundred to-dos and events; 1,000 notes), signed out and//! signed in to an object that cannot be reached. Every name and row is//! invented.//!//! **The budget.** The first screen is drawn from the phone's own copy with//! nothing awaited from the network: the open, the gate's first `open`//! answer and the app's first read together stay under//! [`FIRST_CONTENT_BUDGET_MS`] on the machine running the tests, judged by the//! fastest of up to three launches of fresh copies held in memory where the//! machine allows (a loaded box stalls one open's file work; a regression is//! slow on every copy). A phone is//! slower than a Mac by about three times on this work, so 1.5 s here is//! about half a second's core work on an iPhone 15 — and a regression that//! waits on a network call (whose ceiling is seconds) or rescans a table per//! row fails it at once. `COTTON_LAUNCH_SPEED_REPORT=1` prints the phases.use std::time::{Duration, Instant};use serde_json::{json, Value};usecrate::handle::{CottonHandle, OpenConfig, OpenMode};usecrate::methods::dispatch;/// The core's whole share of a cold launch, open to first content, on the/// machine running the tests (see the module header).const FIRST_CONTENT_BUDGET_MS: u128 = 1_500;const ZONE: &str = "Asia/Kolkata";const TODAY: &str = "2026-11-20";/// An object that never answers: a launch must not wait on it.const UNREACHABLE: &str = "https://launch-speed.invalid";fn manifest(flavour: &str) -> Value {let name = match flavour {"story" => "Cotton Story","days" => "Cotton Days", _ => "Cotton Notes", };letmut manifest = crate::fixture::own_app_manifest(flavour, name); manifest["business"]["server"] = json!({ "real": UNREACHABLE, "dev": UNREACHABLE }); manifest}fn open(dir: &std::path::Path, flavour: &str) -> CottonHandle {CottonHandle::open(OpenConfig { mode: OpenMode::Phone { container_path: dir.to_string_lossy().to_string(), previous_container_path: None }, app_version: Some("1.0.0 (1)".to_string()), time_zone: Some(ZONE.to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(manifest(flavour)), }) .expect("an open core")}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value { dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}/// `shell.home` asked as the phone asks it, until the gate says `open`.fn gate_open(handle: &CottonHandle) {let deadline = Instant::now() + Duration::from_secs(60);loop {let answer = ask(handle, "shell.home", json!({ "device_name": "An invented phone" }));if answer["gate"]["stage"] == "open" {return; } assert!(Instant::now() < deadline, "the gate never opened: {answer}"); std::thread::sleep(Duration::from_millis(5)); }}fn seed(handle: &CottonHandle, flavour: &str) {match flavour {"story" => {// One invented script of 100 scenes of 40 lines, every third a// line spoken, each scene written whole as the old app wrote it// and laid into lines by the first read below.let story = ask(handle, "story.start", json!({ "title": "An Invented Script" }))["story"].as_str().unwrap().to_string();for scene in0..100 {let id = ask(handle, "story.scene.new", json!({ "story": story }))["scene"].as_str().unwrap().to_string();letmut body = String::new();for line in0..40 {if line % 3 == 1 {let who = ["ASHA", "BRAM", "CYRA"][(scene + line) % 3]; body.push_str(&format!("{who}\nScene {scene}, line {line}: nothing anyone ever said.\n\n")); } else { body.push_str(&format!("Scene {scene}, line {line}: the invented room is quiet.\n\n")); } } ask(handle, "story.scene.write", json!({ "id": id, "heading": format!("INT. INVENTED ROOM {scene} - NIGHT"), "body": body })); } first_read(handle, "story"); }"days" => {for n in0..300 {let words = match n % 3 {0 => format!("Invented errand {n}"),1 => format!("Invented meeting {n} at 3pm"), _ => format!("Invented call {n} tomorrow"), };let day = chrono::NaiveDate::from_ymd_opt(2026, 11, 1).unwrap() + chrono::Duration::days((n % 60) as i64);let place = if n % 7 == 0 { "sometime" } else { "days" }; ask(handle, "days.add", json!({ "words": words, "timezone": ZONE, "today": TODAY, "where": place, "dayInView": day.to_string() })); } } _ => {for n in0..1_000 {let made = ask(handle, "notes.new", json!({}));let id = made["id"].as_str().unwrap().to_string(); ask(handle, "notes.edit", json!({ "id": id, "text": format!("Invented note {n}\nA second line of invented words about nothing in particular, number {n}.") })); } } }}/// The app's first screen, as each phone asks for it.fn first_read(handle: &CottonHandle, flavour: &str) -> usize {match flavour {"story" => {let list = ask(handle, "story.list", json!({}));let scenes = ask(handle, "story.scenes", json!({})); list["stories"].as_array().map_or(0, Vec::len) + scenes["rows"].as_array().map_or(0, Vec::len) }"days" => {let span = ask(handle, "days.span", json!({ "timezone": ZONE, "today": TODAY, "from": "2026-11-13", "to": "2026-11-27" }));let sometime = ask(handle, "days.sometime", json!({})); span["days"].as_array().map_or(0, Vec::len) + sometime["rows"].as_array().map_or(0, Vec::len) } _ => { ask(handle, "notes.themes", json!({})); ask(handle, "notes.settings", json!({})); ask(handle, "notes.list", json!({}))["rows"].as_array().map_or(0, Vec::len) } }}#[derive(Debug, Default)]structPhases { open: u128,/// The shipped catalogue both phones read before their first screen. catalogue: u128, connect: u128,/// `shell.lines` and `read.boot`, which Android asks before the gate. lines: u128, boot: u128, gate: u128, read: u128,}implPhases {fn total(&self) -> u128 {self.open + self.catalogue + self.connect + self.lines + self.boot + self.gate + self.read }}/// One launch: open, the personal connect a signed-in phone makes first,/// the gate, the first read.fn launch(dir: &std::path::Path, flavour: &str, signed_in: bool) -> (Phases, usize) {letmut phases = Phases::default();let at = Instant::now();let handle = open(dir, flavour); phases.open = at.elapsed().as_millis();let at = Instant::now(); ask(&handle, "definitions.catalogue", json!({ "shipped": true })); phases.catalogue = at.elapsed().as_millis();if signed_in {let at = Instant::now();let held = cotton_client::connection::ConnectionFile::at(handle.client().layout().connection_json()).read().expect("a connection");let _ = dispatch( &handle,"personal.connect", &json!({ "server": UNREACHABLE, "databaseId": held.workspace_id, "credential": "invented-credential", "deviceName": "An invented phone", "appVersion": "1.0.0 (1)" }), ); phases.connect = at.elapsed().as_millis(); } else {// Signed out, the shells stand the phone on its own copy first (Android Session.launch, iOS// PersonalObject.launch): it is part of every signed-out open.let at = Instant::now(); ask(&handle, "personal.standLocal", json!({ "signedOut": true })); phases.connect = at.elapsed().as_millis(); }let at = Instant::now(); ask(&handle, "shell.lines", json!({})); phases.lines = at.elapsed().as_millis();let at = Instant::now(); ask(&handle, "read.boot", json!({})); phases.boot = at.elapsed().as_millis();let at = Instant::now(); gate_open(&handle); phases.gate = at.elapsed().as_millis();let at = Instant::now();let rows = first_read(&handle, flavour); phases.read = at.elapsed().as_millis(); drop(handle); (phases, rows)}/// A phone's data folder holding `flavour`'s invented data, made through the/// app's own calls and closed.fn seeded(flavour: &str) -> tempfile::TempDir {let dir = tempfile::tempdir().expect("a container");let handle = open(dir.path(), flavour); gate_open(&handle); seed(&handle, flavour); drop(handle); dir}/// The seeded copy as a signed-in phone holds it: its object's copy, the/// connection naming an object that cannot be reached, the copy marked as/// pulled for this kit.fn as_signed_in(dir: &std::path::Path) {let layout = cotton_client::layout::Layout::new(dir);let connection = cotton_client::connection::ConnectionFile::at(layout.connection_json());let held = connection.read().expect("a connection");let database = held.workspace_id.clone().expect("a database");let kit = cotton_core::kit::AppKit::at(layout.root()).expect("the kit").map(std::sync::Arc::new); cotton_client::transport::object::mark_copy_kit(&layout.replica(&database), kit.as_deref()).expect("marked"); connection .write(cotton_client::connection::StoredConnection { mode: cotton_client::connection::ConnectionMode::Remote, base_url: UNREACHABLE.to_string(), owner_id: held.owner_id.clone().or_else(|| Some("owner-invented".to_string())), ..held }) .expect("the connection");}/// Where a timed launch's copy lives: memory-backed storage where the machine/// has it (Linux's /dev/shm), else the usual temporary folder. The budget is the/// core's work and any wait on the network; the shared CI box's disk is neither/// (rust-main 17622 and the box at load 70, 25 Nov 2026: every process fully/// stalled on I/O 12-18% of the time, one cold open 9.9 s, the reads 13-49 ms).fn launch_container() -> tempfile::TempDir {let shm = std::path::Path::new("/dev/shm");if shm.is_dir() {ifletOk(dir) = tempfile::tempdir_in(shm) {return dir; } } tempfile::tempdir().expect("a container")}fn measure(flavour: &str) {let dir = seeded(flavour);// `COTTON_LAUNCH_SPEED_KEEP=<folder>` keeps each app's invented data// folder there, signed out, for a simulator or an emulator to open.ifletSome(keep) = std::env::var_os("COTTON_LAUNCH_SPEED_KEEP") {let into = std::path::Path::new(&keep).join(flavour);let _ = std::fs::remove_dir_all(&into);let copied = std::process::Command::new("cp").arg("-R").arg(dir.path()).arg(&into).status().expect("cp runs"); assert!(copied.success(), "the invented folder could not be kept at {}", into.display()); }let report = std::env::var("COTTON_LAUNCH_SPEED_REPORT").is_ok();// Each attempt launches a fresh copy of the seeded folder: cold (the// first open after the folder was written), warm (the next), then signed// in. A launch is judged by its fastest attempt, up to ATTEMPTS: a// regression (a network wait, a rescan per row) is slow on every attempt,// while a box at load 36 stalled one cold open's file work to 2.2 s// (rust-main 17622, 24 Nov 2026). The budget itself is unchanged.const ATTEMPTS: usize = 3;letmut tries: [Vec<Phases>; 3] = [Vec::new(), Vec::new(), Vec::new()];letmut rows = 0;for _ in0..ATTEMPTS {let copy = launch_container();let copied = std::process::Command::new("cp").arg("-R").arg(format!("{}/.", dir.path().display())).arg(copy.path()).status().expect("cp runs"); assert!(copied.success(), "the seeded folder could not be copied to {}", copy.path().display());let (cold, cold_rows) = launch(copy.path(), flavour, false);let (warm, _) = launch(copy.path(), flavour, false); assert!(cold_rows > 0, "{flavour}: the first read found nothing"); rows = cold_rows; as_signed_in(copy.path());let (signed, signed_rows) = launch(copy.path(), flavour, true); assert!(signed_rows > 0, "{flavour} signed in: the first read found nothing");for (kept, phases) in tries.iter_mut().zip([cold, warm, signed]) { kept.push(phases); }if tries.iter().all(|kept| kept.iter().any(|phases| phases.total() <= FIRST_CONTENT_BUDGET_MS)) {break; } }let fastest = |kept: &[Phases]| kept.iter().min_by_key(|phases| phases.total()).expect("an attempt").total();let [cold_tries, warm_tries, signed_tries] = &tries;if report {let (cold, warm, signed) = (fastest(cold_tries), fastest(warm_tries), fastest(signed_tries));// The first read alone, best of ten on the open copy: a figure a loaded machine does not blur.let handle = open(dir.path(), flavour); gate_open(&handle);let best = (0..10).map(|_| {let at = std::time::Instant::now(); first_read(&handle, flavour); at.elapsed().as_millis() }).min().unwrap_or_default(); eprintln!("launch-speed {flavour}: first read, best of 10: {best} ms"); eprintln!("launch-speed {flavour}: rows {rows}, fastest of {} attempts\n signed out cold = {cold} ms {cold_tries:?}\n signed out warm = {warm} ms {warm_tries:?}\n signed in (object unreachable) = {signed} ms {signed_tries:?}", cold_tries.len()); }for (what, kept) in [("signed out, cold", cold_tries), ("signed out, warm", warm_tries), ("signed in, object unreachable", signed_tries)] { assert!( fastest(kept) <= FIRST_CONTENT_BUDGET_MS,"{flavour} {what}: the core took {} ms at best from open to first content over {} attempts ({kept:?}); the budget is {FIRST_CONTENT_BUDGET_MS} ms", fastest(kept), kept.len() ); }}#[test]fn story_reaches_first_content_inside_the_budget() { measure("story");}#[test]fn days_reaches_first_content_inside_the_budget() { measure("days");}#[test]fn notes_reaches_first_content_inside_the_budget() { measure("notes");}