Cotton code
191 lines · 8.7 KB · RustRaw
//! Home, the Tools board and Today never wait on the shared read pool.//!//! On 16 Oct 2026 TestFlight 289 drew only Me and Tools on the owner's Personal//! database: the fan's card set, the Tools board and Today read through the//! same four read connections the long reads hold (a list over the 9 GB file,//! Devices, Articles), every one held for 10–30 s, so Home's read refused at//! 30 s ("every read connection of this file is busy") and the fan fell to its//! two chrome cards (readpool). Every row is synthetic.use std::sync::mpsc;use std::sync::{Arc, Mutex};use std::time::Duration;use serde_json::{json, Value};use crate::shell::client::phone_tests::attached;use crate::shell::client::ClientController;/// Hold every connection of the shared pool with a read that does not end/// until the returned sender is dropped — the long reads of a fresh install.fn starve(client: &Arc<ClientController>) -> (mpsc::Sender<()>, Vec<std::thread::JoinHandle<()>>) {    let held = cotton_client::replica::READERS_PER_DATABASE;    let (inside, all_in) = mpsc::channel();    let (release, released) = mpsc::channel::<()>();    let released = Arc::new(Mutex::new(released));    let readers = (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");    }    (release, readers)}/// `ask` on its own thread, answered within `within` or `None`.fn answered(    client: &Arc<ClientController>,    ask: fn(&ClientController) -> Result<Value, String>,    within: Duration,) -> Option<Result<Value, String>> {    let (done, answer) = mpsc::channel();    let client = Arc::clone(client);    std::thread::spawn(move || {        let _ = done.send(ask(&client));    });    answer.recv_timeout(within).ok()}/// `read.<name>` exactly as the app asks it.fn read(client: &ClientController, name: &str, args: Value) -> Result<Value, String> {    let entry = crate::phone::reads::read_for(&format!("read.{name}")).expect("a read the app asks");    let Value::Object(args) = args else { unreachable!("arguments are an object") };    crate::phone::answer_read(client, entry, &args)}/// RULE: Home's card set and its Tools board (`read.home`), the catalogue its/// board is drawn from (`definitions.catalogue`) and Today (`read.day`)/// answer while every connection of the shared read pool is held by a long/// read — they read on the pool's short lane, which no list or walk of the/// file ever holds. The reason: on 16 Oct 2026 TestFlight 289 drew only Me/// and Tools on the owner's real file because `read.home` queued 30 s behind four/// long reads (HomeSync's copy list walking the media catalogue) and was/// refused (readpool).#[test]fn home_tools_and_today_answer_while_long_reads_hold_the_pool() {    let (_dir, client) = attached();    let (release, readers) = starve(&client);    let within = Duration::from_secs(3);    let asks: [(&str, fn(&ClientController) -> Result<Value, String>); 3] = [        ("read.home", |client| read(client, "home", json!({}))),        ("definitions.catalogue", |client| {            crate::phone::catalogue::call(client, &json!({})).map_err(|error| format!("{error:?}"))        }),        ("read.day", |client| {            crate::phone::databases::read_all_in(client, "read.day", &json!({ "date": "2026-10-16" }))                .map_err(|error| format!("{error:?}"))        }),    ];    let answers: Vec<_> = asks.iter().map(|(name, ask)| (*name, answered(&client, *ask, within))).collect();    drop(release);    for reader in readers {        reader.join().expect("a long reader");    }    for (name, answer) in answers {        let answer = answer.unwrap_or_else(|| panic!("{name} waited past {within:?} on the starved read pool"));        answer.unwrap_or_else(|error| panic!("{name} refused while the pool was held: {error}"));    }}/// RULE: a read that is not short, run on the short lane, is cut at the/// lane's safety cap inside its statement and answers the typed could-not-read/// line (`could_not_read`, `why: too_long`) — Home never waits on behind it/// (architect, 16 Oct 2026 21:22 and 21:58 IST; readpool).#[test]fn a_long_read_on_the_short_lane_is_cut_with_the_typed_line() {    let (_dir, client) = attached();    let _ = cotton_client::replica::take_read_refusal();    // The cap starts when the reader is lent, after a cold connection opens.    // Measure the statement governed by it. Including attachment/connection    // setup makes this cap check depend on disk and scheduler contention.    let mut began = None;    let walked = crate::shell::client::on_short_lane(crate::shell::client::ShortRead::Home, || {        client.with_file(|file| {            began = Some(std::time::Instant::now());            file.driver                .get(                    "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT COUNT(*) AS c FROM n",                    &[],                )                .map(|_| ())                .map_err(|error| error.to_string())        })    });    let took = began.expect("the short read reached its statement").elapsed();    let reason = walked.expect_err("an endless read on the short lane answered");    assert!(        took < cotton_client::replica::SHORT_READ_DEADLINE + Duration::from_secs(1),        "cut after {took:?}"    );    let typed = crate::methods::could_not_read("read.home", crate::methods::MethodError::new("unreadable", reason));    assert_eq!(typed.code, crate::methods::COULD_NOT_READ);    assert_eq!(typed.details["why"], "too_long");}/// RULE: the short lane is reserved BY NAME for read.home,/// definitions.catalogue and read.day and nothing else — the reservation is/// what keeps long reads out of the lane Home reads on, so no other method/// names a short read, and only `take_reader` (which a `ShortRead` alone/// switches) takes a short connection anywhere in the crates (architect,/// 16 Oct 2026 21:58 IST; readpool).#[test]fn the_short_lane_is_reserved_by_name() {    use crate::shell::client::ShortRead;    let reserved: Vec<&str> = ShortRead::ALL.iter().map(|read| read.method()).collect();    assert_eq!(reserved, ["read.home", "definitions.catalogue", "read.day"]);    for method in ["records.list", "read.devices", "read.sync_state", "definitions.board", "read.toolOrder"] {        assert_eq!(ShortRead::named(method), None, "{method} is not a short read");    }    let crates = cotton_store::manifest_dir().parent().expect("the crates folder").to_path_buf();    let crates = crates.as_path();    let mut takers = Vec::new();    let mut stack = vec![crates.to_path_buf()];    while let Some(dir) = stack.pop() {        for entry in std::fs::read_dir(&dir).expect("a crates folder reads") {            let path = entry.expect("an entry").path();            let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default();            if path.is_dir() {                if name != "target" && !name.starts_with('.') {                    stack.push(path);                }                continue;            }            if !name.ends_with(".rs") || name.ends_with("_tests.rs") {                continue;            }            let source = std::fs::read_to_string(&path).expect("a source reads");            if source.contains(".take_short()") {                takers.push(path.strip_prefix(crates).unwrap_or(&path).display().to_string());            }        }    }    assert_eq!(takers, ["cotton-ffi/src/shell/client.rs"], "only take_reader takes a short connection");}/// RULE: a short read over SHORT_READ_SLOW is logged on the device as a/// finding with its duration and still answers — never a refusal — so the/// household walk gives the real numbers (architect, 16 Oct 2026 21:58 IST).#[test]fn a_slow_short_read_is_logged_and_answers() {    use crate::shell::client::{on_short_lane, ShortRead};    let answered = on_short_lane(ShortRead::Day, || {        std::thread::sleep(cotton_client::replica::SHORT_READ_SLOW + Duration::from_millis(50));        "answered"    });    assert_eq!(answered, "answered");    let logged = crate::shell::diagnostics::slow_reads();    assert!(        logged.iter().any(|read| read.name.contains("read.day") && read.name.starts_with("short lane over")            && u128::from(read.ms) >= cotton_client::replica::SHORT_READ_SLOW.as_millis()),        "{logged:?}"    );}