//! The pass over EVERY held database: one call a page, a section a database, //! and a file left closed when its note can speak for it. use std::collections::BTreeMap; use std::sync::{Arc, Mutex}; use cotton_store::protocol::types::{ CottonOp, ExchangeRequest, ExchangeResponse, ExchangeSectionsRequest, ExchangeSectionsResponse, SectionAnswer, SectionRefusal, SectionRefused, }; use super::*; use crate::connection::held::HeldNotes; use crate::test_support::{accepted, open_replica_for, queue_one_change_for, temp_layout}; const NOW: &str = "2026-09-08T10:00:00.000Z"; const A: &str = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; const B: &str = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; const C: &str = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; /// A server holding several files: it answers ONLY the one call that carries /// every section, and remembers how far each file has seen each author. #[derive(Default)] struct Server { calls: Vec>, seen: BTreeMap>, /// Writes of another device, handed to the next section that asks. news: BTreeMap>, refuses: Option<(&'static str, &'static str)>, /// Answer every section "more to come" (`has_more`), as a catch-up does. more: bool, /// Fail every call after this many answered (a page's ceiling running /// out mid catch-up). answers: Option, /// The box the pass runs under, read on every call: what the pass says /// it is doing while its page is in the air. watching: Option, doing: Vec>, } impl crate::transport::RefusalAware for Server { fn last_refusal(&self) -> Option { None } } impl cotton_store::exchange::SyncTransport for Server { fn exchange(&mut self, request: &ExchangeRequest) -> Result { panic!( "one call per cycle, never one per database — {} was asked alone", request.workspace_id ); } fn exchange_many( &mut self, request: &ExchangeSectionsRequest, ) -> Result { if let Some(watching) = &self.watching { self.doing.push(watching.what_it_is_doing()); } if self.answers.is_some_and(|answers| self.calls.len() >= answers) { return Err("the page's ceiling ran out".to_string()); } self.calls.push(request.sections.clone()); let mut sections = Vec::new(); for section in &request.sections { let database = section.workspace_id.clone(); if let Some((refused, code)) = self.refuses { if refused == database { sections.push(SectionAnswer::Refused(SectionRefused { workspace_id: database, refused: SectionRefusal { code: code.to_string(), message: "this device was revoked".to_string(), extra: serde_json::Map::new(), }, })); continue; } } let seen = self.seen.entry(database.clone()).or_insert_with(|| { BTreeMap::from([( "origin".to_string(), format!("origin:cotton_workspaces:{database}"), )]) }); for op in §ion.ops { let at = seen.entry(op.device_id.clone()).or_default(); if *at < op.hlc { *at = op.hlc.clone(); } } let mut answer = accepted(section, self.more); answer.schema_version = Some(cotton_store::schema::ddl::SCHEMA_VERSION); answer.cursors = section.cursors.clone(); answer.ops = self.news.remove(&database).unwrap_or_default(); for op in &answer.ops { answer.cursors.insert(op.device_id.clone(), op.hlc.clone()); seen.insert(op.device_id.clone(), op.hlc.clone()); } answer.seen = seen.clone(); sections.push(SectionAnswer::Answered(answer)); } Ok(ExchangeSectionsResponse { sections }) } } /// A device holding three databases, each its own file, and the opens a pass /// asked for. struct Device { _dir: tempfile::TempDir, files: BTreeMap>>, opens: Mutex>, notes: HeldNotes, } impl Device { fn holding(databases: &[&str]) -> Device { let (dir, layout) = temp_layout(); let files = databases .iter() .map(|database| { let replica = open_replica_for(&layout, dir.path(), database); ((*database).to_string(), Arc::new(Mutex::new(replica))) }) .collect(); let notes = HeldNotes::beside(&dir.path().join("connection.json")); Device { _dir: dir, files, opens: Mutex::new(Vec::new()), notes, } } fn ids(&self) -> Vec { self.files.keys().cloned().collect() } fn pass(&self, server: &mut Server) -> Vec { self.opens.lock().expect("the log").clear(); let opener = |database: &str| -> Result, String> { self.opens.lock().expect("the log").push(database.to_string()); let file: Arc = self.files[database].clone(); Ok(file) }; run_cycle_many(&self.ids(), &opener, &self.notes, &|_| false, server, NOW).expect("the call landed") } fn opens(&self) -> Vec { self.opens.lock().expect("the log").clone() } fn queue(&self, database: &str, title: &str) { queue_one_change_for(&self.files[database].lock().expect("the file"), database, title); self.notes.note_write(database).expect("noted"); } fn pending(&self, database: &str) -> i64 { cotton_store::outbox::pending_count(&self.files[database].lock().expect("the file").driver) .expect("a count") } fn has_todo(&self, database: &str, id: &str) -> bool { self.files[database] .lock() .expect("the file") .driver .get( "SELECT id FROM cotton_todos WHERE id = ?", &[rusqlite::types::Value::Text(id.to_string())], ) .expect("reads") .is_some() } } /// Another device's todo in `database`. fn theirs(database: &str, row_id: &str, hlc: &str) -> CottonOp { let mut patch = serde_json::Map::new(); patch.insert("workspace_id".to_string(), database.into()); patch.insert("title".to_string(), "From the other side".into()); patch.insert("status".to_string(), "open".into()); patch.insert("created_at".to_string(), NOW.into()); patch.insert("updated_at".to_string(), NOW.into()); crate::test_support::peer_create( &format!("01J00000000000000000{row_id:0>6}"), "cotton_todos", row_id, patch, hlc, "device:b", ) } /// RULE: A sync cycle makes one exchange call carrying a section for every database the device holds, never one call per database. #[test] fn one_exchange_carries_every_held_files_section() { let device = Device::holding(&[A, B, C]); device.queue(A, "a todo in a"); device.queue(C, "a todo in c"); let mut server = Server::default(); let passes = device.pass(&mut server); let first: Vec<&str> = server.calls[0] .iter() .map(|section| section.workspace_id.as_str()) .collect(); assert_eq!(first, [A, B, C], "the first call names every held database"); assert!(server.calls[0][0].ops.len() >= 2, "a's queue rode in its section"); assert!(server.calls[0][1].ops.is_empty(), "b had nothing to hand over"); assert!(server.calls.len() <= EXCHANGE_PAGES as usize); for pass in &passes { let report = pass.outcome.as_ref().expect("every database's pass finished"); assert!(!report.behind, "{} is caught up", pass.database); } assert_eq!(passes[0].outcome.as_ref().expect("a").pushed, 2); // the author's fact, then the change assert_eq!(passes[1].outcome.as_ref().expect("b").pushed, 0); for database in [A, B, C] { assert_eq!(device.pending(database), 0, "{database}'s queue drained"); } } /// RULE: An idle database is spoken for by its note and its file is not opened by the cycle; only an answer that changes something opens it. #[test] fn idle_database_is_not_opened_by_the_cycle() { let device = Device::holding(&[A, B, C]); let mut server = Server::default(); // No notes yet: the first pass opens every file, and leaves a note each. device.pass(&mut server); assert_eq!(device.opens(), [A, B, C]); // Nothing changed anywhere: one call, three sections, no file opened. let calls = server.calls.len(); let passes = device.pass(&mut server); assert_eq!(device.opens(), Vec::::new(), "an idle database costs no open"); assert_eq!(server.calls.len(), calls + 1, "one call for the whole pass"); assert_eq!(server.calls[calls].len(), 3); assert!(server.calls[calls].iter().all(|section| section.ops.is_empty())); for pass in &passes { assert!(!pass.opened); let report = pass.outcome.as_ref().expect("an idle pass is a finished one"); assert_eq!((report.pulled, report.pushed, report.behind), (0, 0, false)); } // A write queued in b opens b and nothing else. device.queue(B, "a todo in b"); device.pass(&mut server); assert_eq!(device.opens(), [B]); assert_eq!(device.pending(B), 0); // News for c opens c — for the fold — and nothing else. server .news .insert(C.to_string(), vec![theirs(C, "t1", "1700000000001:0000:device:b")]); let passes = device.pass(&mut server); assert_eq!(device.opens(), [C]); assert!(device.has_todo(C, "t1"), "the news was folded into c"); assert_eq!(passes[2].outcome.as_ref().expect("c").pulled, 1); // And every file is idle again. device.pass(&mut server); assert_eq!(device.opens(), Vec::::new()); } /// RULE: A section the server refuses fails only its own database; the other databases of the same call still fold and the refused one keeps its queue. #[test] fn a_refused_section_stops_only_its_own_database() { let device = Device::holding(&[A, B]); device.queue(A, "a todo in a"); device.queue(B, "a todo in b"); let queued = device.pending(B); let mut server = Server { refuses: Some((B, "device_revoked")), ..Server::default() }; let passes = device.pass(&mut server); assert_eq!(passes[0].outcome.as_ref().expect("a still syncs").pushed, 2); // the author's fact, then the change assert_eq!(device.pending(A), 0); match passes[1].outcome.as_ref().expect_err("b was refused") { CycleFailure::TerminalDevice { code, .. } => assert_eq!(code, "device_revoked"), other => panic!("b's refusal is the device's, by its code: {other:?}"), } assert_eq!(device.pending(B), queued, "b's writes stay queued"); assert!( device.notes.idle_section(B).is_none(), "a refused database is not spoken for as idle" ); } /// A section answered for another database than the one asked is not folded. #[test] fn a_section_answered_for_another_database_is_not_taken() { struct Swapped(Server); impl crate::transport::RefusalAware for Swapped { fn last_refusal(&self) -> Option { None } } impl cotton_store::exchange::SyncTransport for Swapped { fn exchange(&mut self, request: &ExchangeRequest) -> Result { self.0.exchange(request) } fn exchange_many( &mut self, request: &ExchangeSectionsRequest, ) -> Result { let mut answer = self.0.exchange_many(request)?; answer.sections.reverse(); Ok(answer) } } let device = Device::holding(&[A, B]); let mut server = Swapped(Server::default()); server .0 .news .insert(B.to_string(), vec![theirs(B, "t1", "1700000000001:0000:device:b")]); device.opens.lock().expect("the log").clear(); let opener = |database: &str| -> Result, String> { let file: Arc = device.files[database].clone(); Ok(file) }; let passes = run_cycle_many(&device.ids(), &opener, &device.notes, &|_| false, &mut server, NOW).expect("the call"); for pass in &passes { let failure = pass.outcome.as_ref().expect_err("a misrouted answer"); assert!(matches!(failure, CycleFailure::Transient { .. }), "{failure:?}"); } assert!(!device.has_todo(A, "t1"), "b's row was not folded into a"); } // RULE: A database the device already has open answers for itself whatever its note says, so a write that landed after the note was written still leaves on the next pass. #[test] fn an_open_file_answers_for_itself_whatever_its_note_says() { let device = Device::holding(&[A, B]); let mut server = Server::default(); device.pass(&mut server); assert!(device.notes.read(B).expect("b's note").idle(), "the first pass left b idle"); // A write in b the note never heard of. queue_one_change_for(&device.files[B].lock().expect("the file"), B, "a todo in b"); let opener = |database: &str| -> Result, String> { device.opens.lock().expect("the log").push(database.to_string()); let file: Arc = device.files[database].clone(); Ok(file) }; let calls = server.calls.len(); run_cycle_many(&device.ids(), &opener, &device.notes, &|id| id == B, &mut server, NOW) .expect("the call landed"); assert_eq!(device.pending(B), 0, "b's write left although its note said idle"); assert!( server.calls[calls].iter().any(|section| section.workspace_id == B && !section.ops.is_empty()), "b's section carried its write" ); } /// RULE: A pass that folded at least one page from the Mac is an ANSWER even when a later page fails: its section reports what it folded, `behind`, so the home line stays "Syncing" through a long catch-up — only a section the Mac never answered is unanswered (the 13 Oct catch-up after the 136 move read "not reachable" while rows were arriving). #[test] fn a_pass_that_folded_a_page_is_an_answer_when_a_later_page_fails() { let device = Device::holding(&[A, B]); let mut server = Server { more: true, answers: Some(1), ..Server::default() }; server .news .insert(A.to_string(), vec![theirs(A, "t1", "1700000000001:0000:device:b")]); let passes = device.pass(&mut server); assert_eq!(server.calls.len(), 1, "one page landed, the second failed in the air"); assert!(device.has_todo(A, "t1"), "the folded page stays folded"); for pass in &passes { assert!( matches!(pass.outcome, Err(CycleFailure::Transient { .. })), "{} carries the failure, so the loop backs off", pass.database ); let folded = pass.folded.as_ref().expect("the page that landed is reported"); assert!(folded.behind, "{} is still behind", pass.database); } assert_eq!(passes[0].folded.as_ref().expect("a").pulled, 1); // The line a screen reads: answered by the folded page, never offline. let mut line = super::super::line::HomeLine::default(); let minute = 60_000; for at in 0..40 { let report = super::super::Reported::of(passes[0].folded.as_ref().expect("a")); line.answered( super::super::line::Answered { sent: report.handed as u64, received: report.passed as u64, unsent: report.unsent, owed_at_start: Some(400_000), remaining: Some(cotton_core::constants::BEHIND_BY_CAP), behind: report.behind, }, at * minute, ); assert_eq!(line.standing(at * minute).state, super::super::line::State::Syncing); } // A pass the Mac never answered is still a failure, said as one. let mut silent = Server { answers: Some(0), ..Server::default() }; let opener = |database: &str| -> Result, String> { let file: Arc = device.files[database].clone(); Ok(file) }; assert!(run_cycle_many(&device.ids(), &opener, &device.notes, &|_| false, &mut silent, NOW).is_err()); } /// RULE: A pass says where it stands under its box — the page it is asking for while it is in the air, then the page it is folding with its rows, size and tables — and nothing once it is over, so a pass the loop stops waiting for after 120 s names the page it was on (each page it folded before has kept its cursor) (architect, 13 Oct 2026). #[test] fn a_pass_says_which_page_it_is_on_and_what_the_page_holds() { let device = Device::holding(&[A]); let time_box = TimeBox::open(); let mut server = Server { watching: Some(time_box.clone()), ..Server::default() }; server.news.insert(A.to_string(), vec![theirs(A, "t1", "1700000000001:0000:device:b")]); let opener = |database: &str| -> Result, String> { let file: Arc = device.files[database].clone(); Ok(file) }; run_cycle_many_within(&device.ids(), &opener, &device.notes, &|_| false, &mut server, NOW, &time_box) .expect("the call landed"); assert_eq!(server.doing[0].as_deref(), Some("asking for page 1 of 1 database(s)")); assert_eq!(time_box.what_it_is_doing(), None, "a finished pass is doing nothing"); let mix = ops_mix(&[theirs(A, "t1", "1700000000001:0000:device:b"), theirs(A, "t2", "1700000000002:0000:device:b")]); assert!(mix.starts_with("2 rows, 0.0 MB: cotton_todos 2"), "{mix}"); }