471 lines · 33.3 KB · RustRaw
//! `shell.list`'s cost over a large synthetic copy: a page costs its page,//! a whole-read section kind its aggregate. Run release://! `cargo test --release -p cotton-ffi --lib shell_list::tests::bench -- --ignored --nocapture`.use super::*;use std::time::{Duration, Instant};/// A bound text for a probe's statement.struct SqlValueProbe;impl SqlValueProbe { fn text(value: &str) -> rusqlite::types::Value { rusqlite::types::Value::Text(value.to_string()) }}const MONEY: usize = 50_000;const SIDE: usize = 5_000;/// Owed's first ask, phase by phase: the ask made again on a file moved on/// (nothing kept), each phase's time, the serialising at the FFI edge.fn phased(handle: &CottonHandle, first: &Value, cold: Duration) { let _ = crate::methods::dispatch(handle, "records.create", &json!({"table": "note", "timezone": "Asia/Kolkata", "data": {"title": "Moves the file on"}})); super::phases_begin(); let began = Instant::now(); let answer = crate::methods::dispatch(handle, "shell.list", &json!({"table": "money_owed", "timezone": "Asia/Kolkata", "today": TODAY})).expect("Owed reads"); let asked = began.elapsed(); let phases = super::phases_take(); let began = Instant::now(); let said = serde_json::to_string(&answer).expect("serialised"); let serialise = began.elapsed(); let rows: usize = first["sections"].as_array().into_iter().flatten().map(|section| section["rows"].as_array().map_or(0, Vec::len)).sum(); eprintln!("Owed first ask by phase ({} rows, {rows} on page 1, first {cold:?}, again on a moved file {asked:?}):", first["count"]); for (name, took) in phases { eprintln!(" {name:<12} {took:?}"); } eprintln!(" {:<12} {serialise:?} ({} bytes)", "serialise", said.len()); // The store's cut read and its heads, each alone. for (name, heads, limit) in [("store cut, no heads", false, 2_000_000), ("store heads alone", true, 1)] { let began = Instant::now(); crate::methods::dispatch(handle, "records.list", &json!({"table": "money_owed", "page": 0, "limit": limit, "light": true, "cut": !heads, "heads": heads, "columns": ["counterparty_person_id", "occurred_on", "description"], "timezone": "Asia/Kolkata", "today": TODAY})).expect("records.list"); eprintln!(" {name:<20} {:?}", began.elapsed()); }}fn timed(handle: &CottonHandle, request: Value) -> (Value, Duration) { let began = Instant::now(); let answer = list(handle, request); (answer, began.elapsed())}/// Rows cloned from one made row in SQL, `count` of them: each column keeps/// the template's value unless `set` gives an expression over `i` (0..count)/// or `day` (the row's day, two years back from TODAY). A timestamp column/// set to `@moment` takes the day at 10:00 in the template's own encoding.////// The rows go in by SQL, so they mint no op and the write names nothing;/// a write that names nothing sends no `data` event (6e7adc094c). Every real/// row write mints its op and names its table, so the clone says its table/// moved as a write naming more rows than it lists does (`rows` null): what/// a kept read holds over the table is read whole again.pub(super) fn cloned(handle: &CottonHandle, table: &str, template: &str, count: usize, set: &[(&str, &str)]) { let template = template.replace('\'', "''"); handle.client().write_rows("bench.clone", &mut |ctx| { let db = ctx.db(); let columns: Vec<String> = db.all(&format!("PRAGMA table_info({table})"), &[]).map_err(|e| e.to_string())? .iter().filter_map(|row| row.text("name").map(str::to_string)).collect(); let select: Vec<String> = columns.iter().map(|column| match set.iter().find(|(key, _)| key == column) { Some((_, "@moment")) => format!("CASE typeof(t.{column}) WHEN 'integer' THEN CAST(strftime('%s', n.day || ' 04:30:00') AS INTEGER) * 1000 ELSE n.day || 'T04:30:00.000Z' END"), Some((_, expression)) => expression.to_string(), None => format!("t.{column}"), }).collect(); let sql = format!( "WITH RECURSIVE n(i, day) AS (SELECT 0, '{TODAY}' UNION ALL SELECT i + 1, date('{TODAY}', '-' || ((i + 1) % 700) || ' days') FROM n WHERE i + 1 < {count}) \ INSERT INTO {table} ({}) SELECT {} FROM n, {table} t WHERE t.id = '{template}'", columns.join(", "), select.join(", ")); db.exec(&sql).map_err(|e| e.to_string())?; Ok(Value::Null) }).unwrap_or_else(|error| panic!("{table} cloned: {error}")); handle.events().emit(crate::events::EventKind::Data, json!({ "tables": [table], "rows": null, "origin": "write" }));}/// The synthetic copy: 50k money rows between you and 200 people over two/// years, 5k people, 5k notes, 5k mail threads.fn copy(handle: &CottonHandle) { let began = Instant::now(); let person = make(handle, "person", json!({"full_name": "Template Person", "language": "en"})); cloned(handle, "cotton_people", &person, SIDE, &[ ("id", "printf('bench-person-%05d', i)"), ("full_name", "char(65 + (i * 7) % 26) || printf('nvented Person %05d', i)"), ]); let money = make(handle, "transaction", json!({"description": "Template spend", "occurred_on": TODAY, "amount_minor": 100, "currency": "INR", "direction": "out", "status": "actual", "moves_money": false, "counterparty_person_id": "bench-person-00000"})); cloned(handle, "cotton_money_transactions", &money, MONEY, &[ ("id", "printf('bench-money-%06d', i)"), ("occurred_on", "n.day"), ("description", "printf('Invented spend %06d', i)"), ("amount_minor", "100 + i"), ("direction", "CASE i % 3 WHEN 0 THEN 'in' ELSE 'out' END"), ("counterparty_person_id", "printf('bench-person-%05d', i % 200)"), ]); let note = make(handle, "note", json!({"title": "Template note", "body": "Invented"})); cloned(handle, "cotton_notes", ¬e, SIDE, &[ ("id", "printf('bench-note-%05d', i)"), ("title", "printf('Invented note %05d', i)"), ("updated_at", "@moment"), ("created_at", "@moment"), ]); handle.client().write_rows("bench.threads", &mut |ctx| { let moment = "CASE typeof(t.created_at) WHEN 'integer' THEN CAST(strftime('%s', n.day || ' 04:30:00') AS INTEGER) * 1000 ELSE n.day || 'T04:30:00.000Z' END"; ctx.db().exec(&format!( "WITH RECURSIVE n(i, day) AS (SELECT 0, '{TODAY}' UNION ALL SELECT i + 1, date('{TODAY}', '-' || ((i + 1) % 700) || ' days') FROM n WHERE i + 1 < {SIDE}) \ INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, created_at, updated_at, sender_address, sender_kind) \ SELECT printf('bench-thread-%05d', i), t.workspace_id, printf('bench-%05d', i), printf('Invented subject %05d', i), {moment}, {moment}, 1, t.created_at, t.updated_at, 'invented@example.com', 'person' FROM n, cotton_notes t WHERE t.id = 'bench-note-00000'" )).map_err(|e| e.to_string())?; Ok(Value::Null) }).unwrap_or_else(|error| panic!("threads: {error}")); eprintln!("the copy: {MONEY} money rows, {SIDE} people, notes and mail threads, made in {:?}", began.elapsed());}#[test]#[ignore = "a release measure over 65k synthetic rows"]fn fifty_thousand_rows() { let (_dir, handle) = phone(); copy(&handle); let (first, page_one) = timed(&handle, json!({"table": "transaction"})); assert!(first["count"].as_u64().is_some_and(|count| count as usize >= MONEY), "{}", first["count"]); let (twenty, page_twenty) = timed(&handle, json!({"table": "transaction", "cursor": 19 * PAGE})); assert_eq!(twenty["sections"][0]["rows"].as_array().map(Vec::len), Some(PAGE)); let total = first["count"].as_u64().unwrap() as usize; let (last, page_last) = timed(&handle, json!({"table": "transaction", "cursor": total - PAGE})); assert_eq!(last["next"], Value::Null); eprintln!("plain list, {MONEY} rows: page 1 {page_one:?}, page 20 {page_twenty:?}, last {page_last:?}"); // Ceilings loose for the box's load (targets: page 20 under 50 ms). assert!(page_twenty < Duration::from_millis(150), "page 20 of {MONEY} costs its page: {page_twenty:?}"); for (kind, table) in [("group", "money_owed"), ("index", "person"), ("months", "note"), ("by_day", "email_thread")] { let began = Instant::now(); let answer = match crate::methods::dispatch(&handle, "shell.list", &json!({"table": table, "timezone": "Asia/Kolkata", "today": TODAY})) { Ok(answer) => answer, Err(error) => { eprintln!("{kind} ({table}): refused in {:?}: {error:?}", began.elapsed()); continue; } }; let cold = began.elapsed(); if table == "money_owed" { phased(&handle, &answer, cold); } let (_, warm) = timed(&handle, json!({"table": table})); let (_, deep) = timed(&handle, json!({"table": table, "cursor": 19 * PAGE})); let sections = answer["sections"].as_array().map(Vec::len).unwrap_or(0); eprintln!("{kind} ({table}, {} rows, {sections} sections on page 1): first ask {cold:?}, again {warm:?}, page 20 {deep:?}", answer["count"]); // A background move finishing after the copy moves the file on, and the // cut is read again: the better of the two warm asks is the kept one's. assert!(warm.min(deep) < Duration::from_millis(400), "{kind}: a kept cut reads only its page: {warm:?}, {deep:?}"); } // The narrow cut's pages are the whole-row cut's, row for row. for table in ["money_owed", "person", "note"] { for cursor in [0, 19 * PAGE] { let narrow = super::unclocked(list(&handle, json!({"table": table, "cursor": cursor}))); let wide = super::unclocked(super::read_wide(|| list(&handle, json!({"table": table, "cursor": cursor})))); assert_eq!(narrow, wide, "{table} at {cursor}: the narrow cut's page is the whole-row cut's over {MONEY} rows"); } } eprintln!("narrow cut: Owed, People and Notes pages equal the whole-row cut's"); // Owed's heads were checked here until TABLE DROP 1 retired Money; these measures still build its rows and are kept // only for history (ignored).}/// One ask repeated, for a profiler: `SHELL_LIST_PROFILE=<table>[,<cursor>]`.#[test]#[ignore = "a profiler's loop"]fn profile_one_ask() { let asked = std::env::var("SHELL_LIST_PROFILE").unwrap_or_else(|_| "transaction,950".into()); let (table, cursor) = asked.split_once(',').map(|(table, cursor)| (table.to_string(), cursor.parse::<usize>().unwrap_or(0))).unwrap_or((asked.clone(), 0)); let (_dir, handle) = phone(); copy(&handle); let began = Instant::now(); for _ in 0..20 { list(&handle, json!({"table": table, "cursor": cursor})); } eprintln!("{table} at {cursor}: {:?} an ask", began.elapsed() / 20);}/// The reads one ask makes, each timed alone.#[test]#[ignore = "a profiler's loop"]fn profile_reads() { let (_dir, handle) = phone(); copy(&handle); let reads = [ ("page 20", json!({"table": "transaction", "page": 950, "limit": 50, "timezone": "Asia/Kolkata", "today": TODAY})), ("page 20 ids", json!({"table": "transaction", "ids": (950..1000).map(|at| format!("bench-money-{at:06}")).collect::<Vec<_>>(), "timezone": "Asia/Kolkata", "today": TODAY})), ("bin count", json!({"table": "bin", "count_only": true, "where": {"table": "transaction"}})), ("bin where", json!({"table": "bin", "limit": 1, "where": {"table": "transaction"}})), ("count", json!({"table": "transaction", "count_only": true})), ("people page 0", json!({"table": "person", "page": 0, "limit": 50, "timezone": "Asia/Kolkata", "today": TODAY})), ("people 5000", json!({"table": "person", "page": 0, "limit": 5000, "timezone": "Asia/Kolkata", "today": TODAY})), ("notes 5000", json!({"table": "note", "page": 0, "limit": 5000, "timezone": "Asia/Kolkata", "today": TODAY})), ("people light", json!({"table": "person", "page": 0, "limit": 5000, "light": true, "timezone": "Asia/Kolkata", "today": TODAY})), ("notes light", json!({"table": "note", "page": 0, "limit": 5000, "light": true, "timezone": "Asia/Kolkata", "today": TODAY})), ("owed light", json!({"table": "money_owed", "page": 0, "limit": 5000, "light": true, "heads": false, "timezone": "Asia/Kolkata", "today": TODAY})), ("owed page", json!({"table": "money_owed", "page": 950, "limit": 50, "heads": false, "timezone": "Asia/Kolkata", "today": TODAY})), ("owed heads", json!({"table": "money_owed", "page": 0, "limit": 1, "light": true, "timezone": "Asia/Kolkata", "today": TODAY})), ]; for (name, args) in reads { let began = Instant::now(); let mut said = String::new(); for _ in 0..5 { said = match crate::methods::dispatch(&handle, "records.list", &args) { Ok(answer) => format!("total {} rows {}", answer["total"], answer["records"].as_array().map(Vec::len).unwrap_or(0)), Err(error) => format!("{error:?}").chars().take(160).collect(), }; } eprintln!("{name:<14} {:?} {said}", began.elapsed() / 5); }}/// One money write's cost on a 20,000-row book between you and 200 people/// over two years: a create, an amount edit, a narration edit, a date edit/// and a delete, each timed alone. Run release:/// `cargo test --release -p cotton-ffi --lib shell_list::tests::bench::one_write -- --ignored --nocapture`.#[test]#[ignore = "a release measure over 20k synthetic money rows"]fn one_write_on_twenty_thousand_rows() { const BOOK: usize = 20_000; let (_dir, handle) = phone(); let began = Instant::now(); let person = make(&handle, "person", json!({"full_name": "Template Person", "language": "en"})); cloned(&handle, "cotton_people", &person, 200, &[("id", "printf('bench-person-%05d', i)"), ("full_name", "printf('Invented Person %05d', i)")]); let money = make(&handle, "transaction", json!({"description": "Template spend", "occurred_on": TODAY, "amount_minor": 100, "currency": "INR", "direction": "out", "status": "actual", "moves_money": false, "counterparty_person_id": "bench-person-00000"})); cloned(&handle, "cotton_money_transactions", &money, BOOK, &[ ("id", "printf('00000000-0000-4000-8000-%012d', i)"), ("occurred_on", "n.day"), ("description", "printf('Invented spend %06d', i)"), ("amount_minor", "100 + i"), ("direction", "CASE i % 3 WHEN 0 THEN 'in' ELSE 'out' END"), ("counterparty_person_id", "printf('bench-person-%05d', i % 200)"), ]); // The clone is raw rows: one write works the book out whole once. let _ = make(&handle, "transaction", json!({"description": "Warm", "occurred_on": TODAY, "amount_minor": 1, "currency": "INR", "direction": "out", "status": "actual", "moves_money": false, "counterparty_person_id": "bench-person-00001"})); eprintln!("the book: {BOOK} money rows, made and worked out in {:?}", began.elapsed()); let call = |method: &str, request: Value| { let began = Instant::now(); crate::methods::dispatch(&handle, method, &request).unwrap_or_else(|error| panic!("{method}: {error:?}")); began.elapsed() }; let mut times = Vec::new(); for round in 0..3 { let create = call("records.create", json!({"table": "transaction", "timezone": "Asia/Kolkata", "data": {"description": format!("Invented {round}"), "occurred_on": "2026-01-10", "amount_minor": 500, "currency": "INR", "direction": "out", "status": "actual", "moves_money": false, "counterparty_person_id": "bench-person-00007"}})); let id = format!("00000000-0000-4000-8000-{:012}", 1000 + round); let amount = call("records.update", json!({"table": "transaction", "id": id, "patch": {"amount_minor": 777}})); let narration = call("records.update", json!({"table": "transaction", "id": id, "patch": {"description": "Renamed"}})); let date = call("records.update", json!({"table": "transaction", "id": id, "patch": {"occurred_on": "2025-03-01"}})); let delete = call("records.delete", json!({"table": "transaction", "id": format!("00000000-0000-4000-8000-{:012}", 2000 + round)})); // What any write costs on this phone, with no money pass: the floor. let note = call("records.create", json!({"table": "note", "timezone": "Asia/Kolkata", "data": {"title": format!("Invented note {round}"), "body": "Invented"}})); eprintln!("round {round}: create {create:?}, amount {amount:?}, narration {narration:?}, date {date:?}, delete {delete:?}; a note {note:?}"); times.push((create, amount, narration, date, delete)); }}/// Owed's first ask alone, for timing probes.#[test]#[ignore = "a profiler's loop"]fn profile_owed_first() { let (_dir, handle) = phone(); copy(&handle); let _ = crate::methods::dispatch(&handle, "records.create", &json!({"table": "transaction", "timezone": "Asia/Kolkata", "data": {"description": "Warm", "occurred_on": TODAY, "amount_minor": 1, "currency": "INR", "direction": "out", "status": "actual", "moves_money": false, "counterparty_person_id": "bench-person-00001"}})); let ask = |cursor: usize| { let began = Instant::now(); crate::methods::dispatch(&handle, "shell.list", &json!({"table": "money_owed", "timezone": "Asia/Kolkata", "today": TODAY, "cursor": cursor})).expect("Owed reads"); began.elapsed() }; let moved = || { let _ = crate::methods::dispatch(&handle, "records.create", &json!({"table": "note", "timezone": "Asia/Kolkata", "data": {"title": "Moves the file on"}})); }; for round in 0..3 { // The whole-row cut (before this lane) and the narrow cut, each a first ask. moved(); let wide = super::read_wide(|| ask(0)); moved(); let narrow = ask(0); let kept = ask(0); let deep = ask(19 * PAGE); eprintln!("Owed round {round}: first ask whole-row cut {wide:?}, narrow cut {narrow:?}; kept {kept:?}, page 20 {deep:?}"); } // Owed's reads, each alone: the narrow cut, the heads, the page's rows. let read = |name: &str, args: Value| { let began = Instant::now(); for _ in 0..3 { crate::methods::dispatch(&handle, "records.list", &args).unwrap_or_else(|error| panic!("{name}: {error:?}")); } eprintln!("{name:<16} {:?}", began.elapsed() / 3); }; // The cut's statement and its variants, each timed alone (a probe). handle.client().read_rows("bench.plans", &mut |ctx| { let db = ctx.read.driver(); let ws = SqlValueProbe::text(ctx.workspace_id); let soft = "(t.counterparty_person_id IS NOT NULL AND EXISTS (SELECT 1 FROM cotton_people _soft WHERE _soft.id = t.counterparty_person_id AND _soft.trashed_at IS NULL AND _soft.archived_at IS NULL))"; let projected = format!("CASE WHEN {soft} THEN t.counterparty_person_id END"); let variants = [ ("as read", format!("SELECT id, occurred_on, description, {projected} AS p FROM cotton_money_transactions t WHERE workspace_id = ? AND trashed_at IS NULL AND {soft} AND status = 'actual' ORDER BY occurred_on DESC, updated_at DESC, id ASC")), ("no projection", format!("SELECT id, occurred_on, description, counterparty_person_id FROM cotton_money_transactions t WHERE workspace_id = ? AND trashed_at IS NULL AND {soft} AND status = 'actual' ORDER BY occurred_on DESC, updated_at DESC, id ASC")), ("no updated tie", format!("SELECT id, occurred_on, description, {projected} AS p FROM cotton_money_transactions t WHERE workspace_id = ? AND trashed_at IS NULL AND {soft} AND status = 'actual' ORDER BY occurred_on DESC, id ASC")), ("no order", format!("SELECT id, occurred_on, description, {projected} AS p FROM cotton_money_transactions t WHERE workspace_id = ? AND trashed_at IS NULL AND {soft} AND status = 'actual'")), ("no soft", "SELECT id, occurred_on, description, counterparty_person_id FROM cotton_money_transactions t WHERE workspace_id = ? AND trashed_at IS NULL AND counterparty_person_id IS NOT NULL AND status = 'actual' ORDER BY occurred_on DESC, updated_at DESC, id ASC".to_string()), ("ids only", format!("SELECT id, {projected} AS p FROM cotton_money_transactions t WHERE workspace_id = ? AND trashed_at IS NULL AND {soft} AND status = 'actual' ORDER BY occurred_on DESC, updated_at DESC, id ASC")), ("page 950 dated", format!("SELECT * FROM cotton_money_transactions t INDEXED BY idx_cotton_money_transactions_workspace_date WHERE workspace_id = ? AND trashed_at IS NULL AND {soft} AND status = 'actual' ORDER BY occurred_on DESC, updated_at DESC, id ASC LIMIT 51 OFFSET 950")), ("page 950", format!("SELECT * FROM cotton_money_transactions t WHERE workspace_id = ? AND trashed_at IS NULL AND {soft} AND status = 'actual' ORDER BY occurred_on DESC, updated_at DESC, id ASC LIMIT 51 OFFSET 950")), ]; for (name, sql) in &variants { let began = Instant::now(); let n = db.all(sql, std::slice::from_ref(&ws)).map_err(|e| e.to_string())?.len(); let took = began.elapsed(); let plan: Vec<String> = db.all(&format!("EXPLAIN QUERY PLAN {sql}"), std::slice::from_ref(&ws)).map_err(|e| e.to_string())? .iter().filter_map(|row| row.text("detail").map(str::to_string)).collect(); eprintln!("SQL {name:<15} {took:?} {n} rows | {}", plan.join(" ; ")); } Ok(Value::Null) }).expect("plans"); read("owed narrow cut", json!({"table": "money_owed", "page": 0, "limit": 2_000_000, "light": true, "cut": true, "heads": false, "columns": ["counterparty_person_id", "occurred_on", "description"], "timezone": "Asia/Kolkata", "today": TODAY})); read("owed light cut", json!({"table": "money_owed", "page": 0, "limit": 2_000_000, "light": true, "heads": false, "columns": ["counterparty_person_id", "occurred_on", "description"], "timezone": "Asia/Kolkata", "today": TODAY})); read("owed heads", json!({"table": "money_owed", "page": 0, "limit": 1, "light": true, "timezone": "Asia/Kolkata", "today": TODAY})); read("owed page 50", json!({"table": "money_owed", "page": 950, "limit": 50, "heads": false, "timezone": "Asia/Kolkata", "today": TODAY}));}/// The bench's decks: a label, its table, the table whose row a move of/// this table writes, the column the move changes, a row id to move.struct Bench { label: &'static str, table: &'static str, deck: Value, moves: &'static str, column: &'static str, row: String,}/// The rows the bench's other decks read: 5k todos, 5k events, 5k books.fn more_copy(handle: &CottonHandle) -> (String, String, Option<String>) { let todo = make(handle, "todo", json!({"title": "Template todo", "due_at": "2026-11-05T12:00:00+05:30"})); cloned(handle, "cotton_todos", &todo, SIDE, &[("id", "printf('bench-todo-%05d', i)"), ("title", "printf('Invented todo %05d', i)"), ("due_at", "@moment")]); let event = make(handle, "event", json!({"title": "Template event", "starts_at": "2026-11-09T10:00:00+05:30"})); cloned(handle, "cotton_events", &event, SIDE, &[("id", "printf('bench-event-%05d', i)"), ("title", "printf('Invented event %05d', i)"), ("starts_at", "@moment")]); // A book's store table is the package's: found by the made row. let book = crate::methods::dispatch(handle, "records.create", &json!({"table": "book", "data": {"title": "Template book", "author": "A. Writer", "status": "reading"}, "timezone": "Asia/Kolkata"})).ok() .and_then(|made| made["id"].as_str().or_else(|| made["record"]["id"].as_str()).map(str::to_string)); let books = book.as_ref().and_then(|book| { let mut found = None; handle.client().read_rows("bench.book", &mut |ctx| { let db = ctx.read.driver(); for row in db.all("SELECT name FROM sqlite_master WHERE type = 'table'", &[]).map_err(|e| e.to_string())? { let Some(name) = row.text("name") else { continue }; let sql = format!("SELECT 1 AS hit FROM \"{name}\" WHERE id = ?"); if db.all(&sql, &[SqlValueProbe::text(book)]).is_ok_and(|rows| !rows.is_empty()) { found = Some(name.to_string()); } } Ok(Value::Null) }).ok()?; found }); if let (Some(book), Some(books)) = (&book, &books) { cloned(handle, books, book, SIDE, &[("id", "printf('bench-book-%05d', i)"), ("title", "printf('Invented book %05d', i)")]); } (todo, event, books.map(|_| "bench-book-00007".to_string()))}fn asked(handle: &CottonHandle, method: &str, request: &Value) -> (Value, Duration, u64) { let mut request = request.clone(); request["timezone"] = json!("Asia/Kolkata"); request["today"] = json!(TODAY); let steps = cotton_store::Driver::thread_steps(); let began = Instant::now(); let answer = crate::methods::dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}")); (answer, began.elapsed(), cotton_store::Driver::thread_steps() - steps)}/// Each deck's four asks for shell.list and shell.deck: the first (nothing/// kept), kept with nothing moved, kept after a row of another table moved,/// kept after a row of this table moved. Run release:/// `cargo test --release -p cotton-ffi --lib shell_list::tests::bench::kept_asks -- --ignored --nocapture`.#[test]#[ignore = "a release measure over 80k synthetic rows"]fn kept_asks() { let (_dir, handle) = phone(); copy(&handle); let (_, _, book) = more_copy(&handle); // The rows a move writes: made, so their ids are the store's own. let mover = |table: &str, data: Value| make(&handle, table, data); let mut benches = vec![ Bench { label: "Todos", table: "todo", deck: json!({"table": "todo"}), moves: "todo", column: "title", row: mover("todo", json!({"title": "Invented mover", "due_at": "2026-11-05T12:00:00+05:30"})) }, Bench { label: "People", table: "person", deck: json!({"table": "person"}), moves: "person", column: "full_name", row: mover("person", json!({"full_name": "Invented Mover", "language": "en"})) }, Bench { label: "Notes", table: "note", deck: json!({"table": "note"}), moves: "note", column: "title", row: mover("note", json!({"title": "Invented mover", "body": "Invented"})) }, Bench { label: "Calendar", table: "event", deck: json!({"table": "event"}), moves: "event", column: "title", row: mover("event", json!({"title": "Invented mover", "starts_at": "2026-11-09T10:00:00+05:30"})) }, Bench { label: "Owed", table: "money_owed", deck: json!({"table": "money_owed"}), moves: "transaction", column: "description", row: mover("transaction", json!({"description": "Invented mover", "occurred_on": TODAY, "amount_minor": 100, "currency": "INR", "direction": "out", "status": "actual", "moves_money": false, "counterparty_person_id": "bench-person-00001"})) }, ]; let other_note = mover("note", json!({"title": "Invented other", "body": "Invented"})); let other_person = mover("person", json!({"full_name": "Invented Other", "language": "en"})); if book.is_some() { let row = mover("book", json!({"title": "Invented mover", "author": "A. Writer", "status": "reading"})); benches.push(Bench { label: "Books", table: "book", deck: json!({"table": "book"}), moves: "book", column: "title", row }); } let mut round = 0; let mut move_row = |handle: &CottonHandle, table: &str, column: &str, id: &str| { round += 1; crate::methods::dispatch(handle, "records.update", &json!({"table": table, "id": id, "patch": {column: format!("Moved {round}")}, "timezone": "Asia/Kolkata"})) .unwrap_or_else(|error| panic!("{table} {id} moves: {error:?}")); }; eprintln!("{:<10} {:<6} {:<6} {:>12} {:>12} {:>12} {:>12} (steps: kept / other / this)", "deck", "method", "read", "first", "kept", "other moved", "this moved"); for bench in &benches { for (method, request, before) in [("shell.list", json!({"table": bench.table}), true), ("shell.list", json!({"table": bench.table}), false), ("shell.deck", bench.deck.clone(), true), ("shell.deck", bench.deck.clone(), false)] { let asked = |handle: &CottonHandle, method: &str, request: &Value| if before { crate::methods::shell_kept::unkept(|| asked(handle, method, request)) } else { asked(handle, method, request) }; let other = if bench.moves == "note" { ("person", "full_name", other_person.as_str()) } else { ("note", "title", other_note.as_str()) }; super::kept::forget(); crate::methods::shell_kept::forget(); crate::methods::shell_order::forget(); crate::methods::shell_plan::forget(); let (first, cold, _) = asked(&handle, method, &request); let (kept, warm, warm_steps) = asked(&handle, method, &request); assert_eq!(super::unclocked(first.clone()), super::unclocked(kept), "{} {method}: a kept answer is the first's", bench.label); move_row(&handle, other.0, other.1, other.2); let (_, aside, aside_steps) = asked(&handle, method, &request); move_row(&handle, bench.moves, bench.column, &bench.row); let (moved, here, here_steps) = asked(&handle, method, &request); super::kept::forget(); crate::methods::shell_kept::forget(); crate::methods::shell_order::forget(); crate::methods::shell_plan::forget(); let (fresh, _, _) = asked(&handle, method, &request); assert_eq!(super::unclocked(moved), super::unclocked(fresh), "{} {method}: the answer after a move is a fresh read's", bench.label); eprintln!("{:<10} {:<6} {:<6} {:>12?} {:>12?} {:>12?} {:>12?} ({warm_steps} / {aside_steps} / {here_steps}; {} counted)", bench.label, &method[6..], if before { "before" } else { "after" }, cold, warm, aside, here, first["count"]); } }}/// Where one Owed page's steps go: the page as the deck reads it, without/// its group heads, and as a light read; the count alone. Run release:/// `cargo test --release -p cotton-ffi --lib shell_list::tests::bench::owed_page_steps -- --ignored --nocapture`.#[test]#[ignore = "a release measure over 65k synthetic rows"]fn owed_page_steps() { let (_dir, handle) = phone(); copy(&handle); let base = json!({"table": "money_owed", "timezone": "Asia/Kolkata", "today": TODAY, "page": 0, "limit": 50}); let mut asks = vec![("page", base.clone())]; let mut no_heads = base.clone(); no_heads["heads"] = json!(false); asks.push(("page, no heads", no_heads.clone())); let mut light = no_heads.clone(); light["light"] = json!(true); light["columns"] = json!(["description"]); asks.push(("light page, no heads", light)); let mut cut = no_heads.clone(); cut["light"] = json!(true); cut["columns"] = json!([]); cut["cut"] = json!(true); cut["limit"] = json!(50_000); asks.push(("ids cut, all rows", cut)); let ids: Vec<Value> = crate::methods::dispatch(&handle, "records.list", &json!({"table": "money_owed", "timezone": "Asia/Kolkata", "today": TODAY, "limit": 50, "heads": false})) .expect("a page")["records"].as_array().unwrap().iter().map(|row| row["id"].clone()).collect(); let mut among = no_heads.clone(); among["among"] = json!(ids); asks.push(("among 50, no heads", among)); let mut pivots = no_heads.clone(); pivots["among"] = json!(ids); pivots["light"] = json!(true); pivots["columns"] = json!([]); pivots["cut"] = json!(true); asks.push(("among 50 ids cut", pivots)); for (name, ask) in asks { let (_, took, steps) = asked(&handle, "records.list", &ask); eprintln!("{name:<22} {steps:>10} steps {took:?}"); }}/// A list after one of its rows moved, phase by phase with each phase's/// steps, and whether its kept cut was patched: Owed, Todos, People, Notes./// Run release:/// `cargo test --release -p cotton-ffi --lib shell_list::tests::bench::owed_after_a_write -- --ignored --nocapture`.#[test]#[ignore = "a release measure over 80k synthetic rows"]fn owed_after_a_write() { let (_dir, handle) = phone(); copy(&handle); more_copy(&handle); let lists = [ ("money_owed", "transaction", "description", json!({"description": "Invented mover", "occurred_on": TODAY, "amount_minor": 100, "currency": "INR", "direction": "out", "status": "actual", "moves_money": false, "counterparty_person_id": "bench-person-00001"})), ("todo", "todo", "title", json!({"title": "Invented mover", "due_at": "2026-11-05T12:00:00+05:30"})), ("person", "person", "full_name", json!({"full_name": "Invented Mover", "language": "en"})), ("note", "note", "title", json!({"title": "Invented mover", "body": "Invented"})), ]; for (list, table, column, data) in lists { let mover = make(&handle, table, data); let ask = json!({"table": list}); asked(&handle, "shell.list", &ask); for round in 0..2 { crate::methods::dispatch(&handle, "records.update", &json!({"table": table, "id": mover, "patch": {column: format!("Moved {round}")}, "timezone": "Asia/Kolkata"})).expect("moves"); let patched = super::patched(); super::phases_begin(); super::phase_steps_take(); let (_, took, steps) = asked(&handle, "shell.list", &ask); let phases = super::phases_take(); let counted = super::phase_steps_take(); eprintln!("{list} round {round}: {steps} steps {took:?}, patched {}", super::patched() - patched); for (name, took) in phases { let steps = counted.iter().find(|(held, _)| *held == name).map_or(0, |(_, steps)| *steps); eprintln!(" {name:<12} {took:>14?} {steps:>9} steps"); } } }}