Cotton code
320 lines · 15.4 KB · RustRaw
use super::*;use std::io::Read;use std::net::TcpListener;const S: Schedule = Schedule { wake_s: 300, sweep_s: 3600, backoff_s: 300, backoff_max_s: 3600 };fn state() -> State {    State::default()}/// RULE (meetings-mac-job, 20 Nov 2026): a failure backs off five minutes, doubling, never more than an hour.#[test]fn backoff_doubles_to_an_hour() {    let waits: Vec<i64> = (1..=7).map(|n| backoff(n, &S)).collect();    assert_eq!(waits, [300, 600, 1200, 2400, 3600, 3600, 3600]);    assert_eq!(backoff(u32::MAX, &S), 3600, "no overflow");}/// RULE: a wake inside a back-off waits; once it is past, the job runs again.#[test]fn a_backoff_holds_the_wake_until_it_passes() {    let mut st = state();    failed(&mut st, 1_000, &S, "the object did not answer".into(), None);    assert_eq!((st.failures, st.next_try), (1, Some(1_300)));    assert!(matches!(gate(&st, 1_100, &S, false, false), Gate::Wait(w) if w.contains("backing off after 1 failure")));    assert_eq!(gate(&st, 1_300, &S, false, false), Gate::Sweep, "never run: the sweep is due");    failed(&mut st, 1_300, &S, "again".into(), None);    assert_eq!(st.next_try, Some(1_900));}/// RULE: a next try further away than the longest back-off (a clock set back) does not hold the job.#[test]fn a_clock_set_back_does_not_freeze_the_job() {    let st = State { failures: 2, next_try: Some(100_000), last_run: Some(90_000), ..state() };    assert_eq!(gate(&st, 1_000, &S, false, false), Gate::Sweep, "now before the last run: the sweep is due");}/// RULE: a build holding this Mac defers the wake: transcription never fights a build.#[test]fn a_build_defers_the_wake() {    let st = State { last_run: Some(0), ..state() };    assert_eq!(gate(&st, 10, &S, true, false), Gate::Wait("a build holds this Mac".into()));}/// RULE: within the sweep's hour a wake runs only when the probe sees something new; past it, it sweeps.#[test]fn the_sweep_and_the_probe() {    let st = State { last_run: Some(1_000), version: Some(40), ..state() };    assert_eq!(gate(&st, 1_000 + 3_599, &S, false, false), Gate::Probe);    assert_eq!(gate(&st, 1_000 + 3_600, &S, false, false), Gate::Sweep);    assert!(!changed(&st, Some(40), 0), "nothing changed");    assert!(changed(&st, Some(41), 1), "a recording arrived");    assert!(changed(&st, Some(3), 0), "the object's version went back: a new database");    assert!(changed(&state(), Some(3), 0), "a first run");}/// RULE: a run asked for by hand skips the back-off and the build's wait.#[test]fn a_run_by_hand_goes_now() {    let st = State { failures: 3, next_try: Some(5_000), last_run: Some(4_000), ..state() };    assert_eq!(gate(&st, 4_001, &S, true, true), Gate::Sweep);}/// RULE: a run that goes through clears the back-off and keeps the version it started from.#[test]fn success_clears_the_backoff() {    let mut st = State { failures: 4, next_try: Some(9), failed: Some("x".into()), version: Some(2), ..state() };    succeeded(&mut st, 50, Some(7), Counts { transcribed: 2, ..Counts::default() });    assert_eq!((st.failures, st.next_try, st.failed.clone(), st.version, st.last_ok), (0, None, None, Some(7), Some(50)));    succeeded(&mut st, 60, None, Counts::default());    assert_eq!(st.version, Some(7), "an answer without a version keeps the last");}/// RULE: one run at a time: a second taker of the lock is told no, and the lock goes with the run.#[test]fn one_run_at_a_time() {    let home = tempfile::tempdir().unwrap();    let first = lock(home.path()).unwrap();    assert!(first.is_some());    assert!(lock(home.path()).unwrap().is_none(), "a second run stops");    drop(first);    assert!(lock(home.path()).unwrap().is_some(), "free again once the run ends");}/// RULE: a build slot whose holder is alive is busy; a dead holder's, or no slot, is not.#[test]fn a_build_slot_is_busy_only_while_its_holder_lives() {    let dir = tempfile::tempdir().unwrap();    let slot = dir.path().join("build.lock");    assert!(!build_busy(&slot));    std::fs::create_dir(&slot).unwrap();    assert!(build_busy(&slot), "being taken: no pid yet, just made");    std::fs::write(slot.join("pid"), "999999").unwrap();    assert!(!build_busy(&slot), "its holder is gone");    std::fs::write(slot.join("pid"), std::process::id().to_string()).unwrap();    assert!(build_busy(&slot));    std::fs::remove_dir_all(&slot).unwrap();    let second = PathBuf::from(format!("{}.slot-2", slot.display()));    std::fs::create_dir(&second).unwrap();    std::fs::write(second.join("pid"), std::process::id().to_string()).unwrap();    assert!(build_busy(&slot), "the second slot counts too");}/// RULE: the log rotates at its size and keeps three old files, the newest `.1`.#[test]fn the_log_rotates() {    let dir = tempfile::tempdir().unwrap();    let log = Log { path: dir.path().join("job.log"), max: 200, keep: 3 };    for n in 0..40 {        log.say(&format!("line {n:02} {}", "x".repeat(40)));    }    let names: Vec<String> = {        let mut v: Vec<String> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();        v.sort();        v    };    assert_eq!(names, ["job.log", "job.log.1", "job.log.2", "job.log.3"]);    let newest = std::fs::read_to_string(dir.path().join("job.log")).unwrap();    assert!(newest.contains("line 39"));    assert!(std::fs::metadata(dir.path().join("job.log.1")).unwrap().len() >= 200);}/// RULE: the log says ids, outcomes, counts and seconds: a reason that is not a plain code is never written as it came.#[test]fn the_log_holds_no_meeting_content() {    let d = Drained {        meeting: "m-1\nSita said the garden plan".into(),        status: "failed".into(),        why: Some("the engine stopped: Sita's words".into()),        lines: 0,        speakers: 0,        took: None,    };    let line = drained_line(&d);    assert_eq!(line, "meeting m-1Sitasaidthegardenplan failed (other)");    let ready = Drained { meeting: "abc".into(), status: "ready".into(), why: None, lines: 12, speakers: 3, took: Some(crate::meetings::Took { audio_s: 38.7, wall_s: 9.25, windows: 2, ..Default::default() }) };    assert_eq!(drained_line(&ready), "meeting abc ready lines=12 speakers=3 audio=38.7s took=9.2s windows=2");    let s = Summarised { meeting: "abc".into(), done: false, why: Some("model_missing".into()), actions: 0, took: None };    assert_eq!(summarised_line(&s), "meeting abc not_summarised (model_missing)");    assert_eq!(code(Some("engine_failed")), "engine_failed");    assert_eq!(code(Some("Engine failed")), "other");    assert_eq!(one_line("first\nsecond"), "first");}// ── a whole wake, against a stub object and a stub engine ──────────────────struct Rig {    _dir: tempfile::TempDir,    cfg: Config,}/// A config over a temp folder: a device credential, a models folder and an/// engine whose `check` answers `models_ok`.fn rig(base: &str, models_ok: bool) -> Rig {    let dir = tempfile::tempdir().unwrap();    let root = dir.path();    std::fs::create_dir_all(root.join("repo/scripts/meetings")).unwrap();    std::fs::create_dir_all(root.join("models")).unwrap();    let answer = if models_ok { "{'ok': True, 'models': {}, 'folder': f, 'missing': []}" } else { "{'ok': False, 'models': {}, 'folder': f, 'missing': ['parakeet-tdt-0.6b-ultra-int8']}" };    std::fs::write(root.join("repo/scripts/meetings/engine.py"), format!("import json, os\nf = os.environ.get('MEETINGS_MODELS', '')\nprint(json.dumps({answer}))\n")).unwrap();    std::fs::write(root.join("device-token"), "ctd_synthetic_never_printed\n").unwrap();    let cfg = Config {        base: base.into(),        device_id: "mac-synthetic".into(),        token_file: root.join("device-token"),        key_file: None,        python: "python3".into(),        models: root.join("models"),        repo: root.join("repo"),        languages: vec![],        summaries: true,        summary_model: None,        llama_server: None,        most: 20,        schedule: S,        build_lock: Some(root.join("no-build.lock")),        home: root.join("home"),        log: root.join("logs/meetings-job.log"),    };    Rig { _dir: dir, cfg }}/// A one-thread object answering every `/v1/sync` with `version` and `rows` empty rows, counting the asks.fn stub_object(version: i64, rows: usize) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {    let listener = TcpListener::bind("127.0.0.1:0").unwrap();    let base = format!("http://{}", listener.local_addr().unwrap());    let asked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));    let count = asked.clone();    std::thread::spawn(move || {        for stream in listener.incoming() {            let Ok(mut stream) = stream else { continue };            let mut buf = [0u8; 4096];            let n = stream.read(&mut buf).unwrap_or(0);            let head = String::from_utf8_lossy(&buf[..n]).to_string();            let body = if head.starts_with("GET /v1/sync") {                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);                let rows: Vec<Value> = (0..rows).map(|i| serde_json::json!({ "table": "meetings_meeting", "id": format!("r{i}"), "blob": "sealed" })).collect();                serde_json::json!({ "version": version, "rows": rows }).to_string()            } else {                "{}".into()            };            let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());        }    });    (base, asked)}fn log_of(cfg: &Config) -> String {    std::fs::read_to_string(&cfg.log).unwrap_or_default()}/// RULE: a Mac without its device credential refuses before it asks anything, and says which.#[test]fn a_missing_sign_in_refuses_and_says_which() {    let r = rig("http://127.0.0.1:9", true);    std::fs::remove_file(&r.cfg.token_file).unwrap();    let woke = wake(&r.cfg, false);    assert!(matches!(&woke, Woke::Refused(f) if f.kind == "sign_in"), "{woke:?}");    assert_eq!(woke.exit(), 3);    let st = State::load(&r.cfg.state_path());    assert_eq!(st.failures, 1);    let (line, ok) = status_line(&r.cfg, &st, true, signed_in(&r.cfg), models_held(&r.cfg), now());    assert!(!ok);    assert!(line.starts_with("meetings job: refused · not signed in: ") && line.ends_with("device-token holds no device credential (sign this Mac in with seal-device)"), "{line}");    // An assistant's token is no sign-in either, and is never said.    std::fs::write(&r.cfg.token_file, "ctn_assistant_secret").unwrap();    let why = signed_in(&r.cfg).unwrap_err().said();    assert!(why.contains("an assistant's token") && !why.contains("ctn_assistant_secret"), "{why}");}/// RULE: missing models refuse the run (before any claim) and the status line names them.#[test]fn missing_models_refuse_and_say_which() {    let (base, _) = stub_object(5, 1);    let r = rig(&base, false);    let woke = wake(&r.cfg, false);    assert!(matches!(&woke, Woke::Refused(f) if f.kind == "models" && f.why.contains("parakeet-tdt-0.6b-ultra-int8")), "{woke:?}");    let st = State::load(&r.cfg.state_path());    let (line, _) = status_line(&r.cfg, &st, true, signed_in(&r.cfg), models_held(&r.cfg), now());    assert!(line.starts_with("meetings job: refused · models missing: this Mac lacks parakeet-tdt-0.6b-ultra-int8"), "{line}");    assert!(log_of(&r.cfg).contains("refused: models missing"));    // Said once: the next wake (forced past the back-off) does not say it again.    let _ = wake(&r.cfg, true);    assert_eq!(log_of(&r.cfg).matches("refused:").count(), 1);}/// RULE: within the hour, a wake whose probe sees nothing new ends there: no models check, no device, no log line.#[test]fn nothing_new_is_a_quiet_wake() {    let (base, asked) = stub_object(40, 0);    let r = rig(&base, false);    std::fs::create_dir_all(&r.cfg.home).unwrap();    State { last_run: Some(now() - 60), version: Some(40), last_ok: Some(now() - 60), ..state() }.save(&r.cfg.state_path()).unwrap();    assert_eq!(wake(&r.cfg, false), Woke::Quiet);    assert_eq!(asked.load(std::sync::atomic::Ordering::SeqCst), 1, "one probe");    assert_eq!(log_of(&r.cfg), "", "nothing said");    let st = State::load(&r.cfg.state_path());    assert_eq!(st.failures, 0, "the models were never looked at");}/// RULE: an object that does not answer is a failure that backs off, said in the status line.#[test]fn an_unreachable_object_backs_off() {    let r = rig("http://127.0.0.1:9", true);    let woke = wake(&r.cfg, false);    assert!(matches!(&woke, Woke::Failed(w) if w.starts_with("the object did not answer")), "{woke:?}");    let st = State::load(&r.cfg.state_path());    assert_eq!(st.failures, 1);    let (line, ok) = status_line(&r.cfg, &st, true, Ok(()), Ok(()), now());    assert!(!ok);    assert!(line.starts_with("meetings job: backing off · 1 failure: the object did not answer"), "{line}");    // The next wake inside the back-off asks nothing and says it once.    assert_eq!(wake(&r.cfg, false), Woke::Quiet);    assert_eq!(wake(&r.cfg, false), Woke::Quiet);    assert_eq!(log_of(&r.cfg).matches("backing off").count(), 1);}/// RULE: a wake while another run holds the job stops at once and changes nothing.#[test]fn a_second_wake_stops_at_the_lock() {    let r = rig("http://127.0.0.1:9", true);    let held = lock(&r.cfg.home).unwrap();    assert_eq!(wake(&r.cfg, true), Woke::Quiet);    assert!(log_of(&r.cfg).contains("another run holds the job"));    assert!(!r.cfg.state_path().exists(), "no state written by the stopped wake");    drop(held);}/// RULE: the status line says when the job last ran and how often it wakes, and an unloaded job is not ready.#[test]fn the_ready_status_line() {    let r = rig("http://127.0.0.1:9", true);    let st = State { last_ok: Some(now()), last_counts: Some(Counts { transcribed: 2, failed: 1, left: 0, summarised: 2 }), ..state() };    let (line, ok) = status_line(&r.cfg, &st, true, Ok(()), Ok(()), now());    assert!(ok);    assert!(line.starts_with("meetings job: ready · last run ") && line.ends_with("(2 transcribed, 1 failed, 2 summarised) · wakes every 5 min, sweeps hourly"), "{line}");    let (line, ok) = status_line(&r.cfg, &state(), false, Ok(()), Ok(()), now());    assert!(!ok);    assert_eq!(line, "meetings job: not loaded · pnpm -s meetings:job:install loads it");    let (line, _) = status_line(&r.cfg, &state(), true, Ok(()), Ok(()), now());    assert_eq!(line, "meetings job: ready · not run yet · wakes every 5 min, sweeps hourly");}/// RULE: the config the installer (the meetings job script) writes reads, its defaults filled.#[test]fn the_installers_config_reads() {    let body = r#"{"base":"https://cottondb-dev.example","device_id":"mac-1","token_file":"/x/token","key_file":null,        "python":"/v/bin/python3","models":"/m","repo":"/r","languages":["en","hi"],"summaries":false,        "summary_model":null,"llama_server":null,"most":20,        "schedule":{"wake_s":300,"sweep_s":3600,"backoff_s":300,"backoff_max_s":3600},        "home":"/h","log":"/l/cotton-meetings-job.log"}"#;    let cfg: Config = serde_json::from_str(body).unwrap();    assert_eq!(cfg.languages, ["en", "hi"]);    assert!(!cfg.summaries);    assert_eq!(cfg.schedule, S);    assert_eq!(cfg.engine().script, PathBuf::from("/r/scripts/meetings/engine.py"));    let least: Config = serde_json::from_str(r#"{"base":"b","device_id":"d","token_file":"t","python":"p","models":"m","repo":"r","home":"h","log":"l"}"#).unwrap();    assert!(least.summaries && least.most == 20 && least.schedule == Schedule::default());}