Cotton code
335 lines · 12.9 KB · RustRaw
//! A read never queues behind a write on this device.//!//! The owner's rule: an offline-first app never makes a screen wait on a sync//! write. The sync fold holds the replica's WRITER for a batch at a time, so a//! read that took the writer's mutex sat behind every fold — a list that//! answers in milliseconds drew a spinner for as long as the fold ran. Reads//! run on the controller's own read-only connection instead//! (`ClientController::with_file`), which sees the last committed snapshot//! and takes no lock a writer holds.//!//! Two tests: a fast guard, and an `#[ignore]`d measurement that builds a big//! synthetic file and prints how long `records.list` takes cold, warm and//! while a write transaction is open. Run the measurement with//!//! ```text//! cargo test --release -p cotton-ffi --lib read_connection_tests::measure -- --ignored --nocapture//! ```//!//! Every row is synthetic ([nothing-real-ever-goes-in-cotton-s-public-tree]).use std::sync::mpsc;use std::sync::Arc;use std::time::{Duration, Instant};use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use crate::shell::client::phone_tests::attached;use crate::shell::client::ClientController;const TODAY: &str = "2026-10-03";/// `records.list` exactly as the app sends it (`CoreRecords.listRequest`).fn list(client: &ClientController, table: &str) -> Value {    crate::phone::records::call(        client,        "records.list",        &json!({ "table": table, "page": 0, "limit": 50, "today": TODAY }),    )    .unwrap_or_else(|error| panic!("records.list {table} refused: {error:?}"))}fn total(answer: &Value) -> i64 {    answer["total"]        .as_i64()        .expect("records.list answers a total")}/// Fill the replica file with `todos` todos and `notes` notes in ONE/// transaction on a connection of its own, before the controller attaches.fn fill(client: &ClientController, todos: usize, notes: usize) {    let path = client.layout().replica(crate::fixture::WORKSPACE);    let db = cotton_store::driver::Driver::open(&path).expect("the replica opens");    db.transaction(|db| {        let conn = db.connection();        let mut todo = conn.prepare(            "INSERT INTO cotton_todos (id, workspace_id, title, due_at, created_at, updated_at) \             VALUES (?1, ?2, ?3, ?4, ?5, ?5)",        )?;        for n in 0..todos {            let at = format!("2026-{:02}-{:02}T09:00:00.000Z", 1 + n % 12, 1 + n % 28);            todo.execute(rusqlite::params![                format!("todo-bulk-{n:07}"),                crate::fixture::WORKSPACE,                format!("Synthetic task number {n}"),                at,                at,            ])?;        }        let mut note = conn.prepare(            "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at) \             VALUES (?1, ?2, 'note', ?3, ?4, ?5, ?5)",        )?;        for n in 0..notes {            let at = format!("2026-{:02}-{:02}T09:00:00.000Z", 1 + n % 12, 1 + n % 28);            note.execute(rusqlite::params![                format!("note-bulk-{n:07}"),                crate::fixture::WORKSPACE,                format!("Synthetic note {n}"),                format!("A synthetic paragraph, the {n}th of its kind, about nothing at all."),                at,            ])?;        }        Ok(())    })    .expect("the bulk insert");    db.checkpoint_truncate().expect("the checkpoint");}/// What a sync fold looks like from outside: the WRITER, locked, inside an/// open write transaction, until `release` says go. `held` fires once the/// transaction has written its first row, so the caller knows SQLite's write/// lock is taken and not merely the mutex.fn hold_a_write(    client: &ClientController,    held: mpsc::Sender<()>,    release: mpsc::Receiver<()>,) -> std::thread::JoinHandle<()> {    static FOLDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);    let fold = FOLDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);    let replica = client.replica().expect("an attached replica");    std::thread::spawn(move || {        let replica = replica.lock().expect("the writer");        replica            .driver            .transaction(|db| {                let mut n = 0u64;                loop {                    db.run(                        "INSERT INTO cotton_todos (id, workspace_id, title, created_at, updated_at) \                         VALUES (?, ?, 'Folded in by a sync', '2026-10-03T09:00:00.000Z', \                         '2026-10-03T09:00:00.000Z')",                        &[                            SqlValue::Text(format!("todo-fold-{fold}-{n:07}")),                            SqlValue::Text(crate::fixture::WORKSPACE.to_string()),                        ],                    )?;                    if n == 0 {                        let _ = held.send(());                    }                    n += 1;                    match release.try_recv() {                        Ok(()) | Err(mpsc::TryRecvError::Disconnected) => return Ok(()),                        Err(mpsc::TryRecvError::Empty) => {}                    }                }            })            .expect("the fold commits");    })}#[test]fn a_list_answers_while_a_sync_write_holds_the_writer() {    let (_dir, client) = attached();    let before = total(&list(&client, "todo"));    let (held_tx, held_rx) = mpsc::channel();    let (release_tx, release_rx) = mpsc::channel();    let writer = hold_a_write(&client, held_tx, release_rx);    held_rx.recv().expect("the write transaction is open");    // The read runs on a thread of its own so a regression FAILS rather than    // hanging the suite: before the read connection, this call waited on the    // writer's mutex for as long as the transaction stayed open — here, for    // ever, because the transaction ends only when the read has answered.    let reader = Arc::clone(&client);    let (answer_tx, answer_rx) = mpsc::channel();    std::thread::spawn(move || {        let _ = answer_tx.send(total(&list(&reader, "todo")));    });    let during = answer_rx.recv_timeout(Duration::from_secs(20));    release_tx.send(()).expect("the writer is still waiting");    writer.join().expect("the writer thread");    let during = during        .expect("records.list waited on the writer: a read must never queue behind a sync write");    assert_eq!(        during, before,        "a read during an open write sees the last COMMITTED file, not the fold's half"    );    assert!(        total(&list(&client, "todo")) > before,        "and the read after the commit sees the fold — a fresh snapshot per read"    );}#[test]fn a_read_sees_this_device_s_own_write_at_once() {    let (_dir, client) = attached();    let before = total(&list(&client, "todo"));    crate::phone::records::call(        &client,        "records.create",        &json!({ "table": "todo", "data": { "title": "Read me back" } }),    )    .expect("the write");    assert_eq!(total(&list(&client, "todo")), before + 1);}/// RULE: a board's tiles read side by side — a database keeps a pool of read connections and a read takes any free one, so 26 tiles never queue behind one lock.////// One reader behind one mutex made Home a line: every tile's first page/// waited for the one before it, and the slowest count held every list under/// it (architect, 11 Oct 2026). Each read here holds its connection for a/// while; under one lock the most ever in flight would be one.#[test]fn a_board_of_26_tiles_never_serialises_its_reads_behind_one_lock() {    use std::sync::atomic::{AtomicUsize, Ordering};    const TILES: usize = 26;    let (_dir, client) = attached();    let in_flight = Arc::new(AtomicUsize::new(0));    let most = Arc::new(AtomicUsize::new(0));    let start = Arc::new(std::sync::Barrier::new(TILES));    let tiles: Vec<_> = (0..TILES)        .map(|_| {            let (client, in_flight, most, start) =                (Arc::clone(&client), Arc::clone(&in_flight), Arc::clone(&most), Arc::clone(&start));            std::thread::spawn(move || {                start.wait();                client                    .with_file(|_| {                        let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;                        most.fetch_max(now, Ordering::SeqCst);                        std::thread::sleep(Duration::from_millis(40));                        in_flight.fetch_sub(1, Ordering::SeqCst);                        Ok(())                    })                    .expect("a tile's read");            })        })        .collect();    for tile in tiles {        tile.join().expect("a tile");    }    assert_eq!(        most.load(Ordering::SeqCst),        cotton_client::replica::READERS_PER_DATABASE,        "26 tiles asking at once read on every connection of the pool at once"    );}/// RULE: shutting a client down never takes a read connection — with every/// connection of the pool held by a read that will not finish, `detach` still/// returns at once. On 12 Oct 2026 two standbys could not quit while reads/// held every connection (standbyhang); the shutdown must not be one more/// reader in that queue.#[test]fn shutdown_does_not_wait_for_a_read_connection() {    let (_dir, client) = attached();    let held = cotton_client::replica::READERS_PER_DATABASE;    let (inside, all_in) = mpsc::channel();    let (release, released) = mpsc::channel::<()>();    let released = Arc::new(std::sync::Mutex::new(released));    let readers: Vec<_> = (0..held)        .map(|_| {            let (client, inside, released) =                (Arc::clone(&client), inside.clone(), Arc::clone(&released));            std::thread::spawn(move || {                let _ = client.with_file(|_| {                    inside.send(()).unwrap();                    let _ = released.lock().unwrap().recv();                    Ok(())                });            })        })        .collect();    for _ in 0..held {        all_in.recv_timeout(Duration::from_secs(10)).expect("every connection held");    }    let (done, detached) = mpsc::channel();    let shutting = Arc::clone(&client);    std::thread::spawn(move || {        shutting.detach();        done.send(()).unwrap();    });    let answer = detached.recv_timeout(Duration::from_secs(5));    for _ in 0..held {        release.send(()).unwrap();    }    for reader in readers {        reader.join().expect("a reader");    }    answer.expect("detach returned while every read connection was held");}/// The measurement. Not a guard — it prints numbers — so it is `#[ignore]`d/// and run by hand, in release, when the read path changes.#[test]#[ignore = "a measurement over 200k synthetic rows; run by hand with --release --ignored"]fn measure() {    const ROWS: usize = 100_000;    const HOLD: Duration = Duration::from_secs(2);    let (_dir, client) = attached();    let started = Instant::now();    fill(&client, ROWS, ROWS);    println!(        "filled {ROWS} todos + {ROWS} notes in {:?}",        started.elapsed()    );    for table in ["todo", "note"] {        // A fresh controller per table, so "cold" is the first question this        // controller is asked: the attach, the reader's open, the first plan.        let fresh = Arc::new(            ClientController::new(                client.layout().clone(),                Arc::new(crate::events::EventBus::new()),                Some("Asia/Kolkata".to_string()),                None,            )            .with_seams(                Arc::new(cotton_client::seams::FixedClock::default_start()),                Arc::new(cotton_client::seams::SeededRandom::default()),            ),        );        let started = Instant::now();        let answer = list(&fresh, table);        let cold = started.elapsed();        assert!(total(&answer) >= ROWS as i64, "{table}: {}", total(&answer));        let mut warm = Vec::new();        for _ in 0..5 {            let started = Instant::now();            list(&fresh, table);            warm.push(started.elapsed());        }        warm.sort();        let (held_tx, held_rx) = mpsc::channel();        let (release_tx, release_rx) = mpsc::channel();        let writer = hold_a_write(&fresh, held_tx, release_rx);        held_rx.recv().expect("the write transaction is open");        let opened = Instant::now();        let releaser = std::thread::spawn(move || {            std::thread::sleep(HOLD);            let _ = release_tx.send(());        });        let started = Instant::now();        list(&fresh, table);        let during = started.elapsed();        releaser.join().expect("the releaser");        writer.join().expect("the writer");        println!(            "records.list {table:<5} cold {cold:>10.2?}  warm(median of 5) {:>10.2?}  \             during a {HOLD:?} write tx {during:>10.2?} (read started {:.2?} into the tx)",            warm[2],            started.duration_since(opened),        );        drop(fresh);    }}