diff --git a/changelog.d/daemon-adopt-read-buffers.md b/changelog.d/daemon-adopt-read-buffers.md new file mode 100644 index 000000000..79945416e --- /dev/null +++ b/changelog.d/daemon-adopt-read-buffers.md @@ -0,0 +1,3 @@ +## Changed + +- The desktop daemon uses smaller read buffers when turning on sync for a folder of existing notes. diff --git a/runtime/crates/daemon/examples/adopt_rehearsal.rs b/runtime/crates/daemon/examples/adopt_rehearsal.rs index cdc52c377..6f3fa6344 100644 --- a/runtime/crates/daemon/examples/adopt_rehearsal.rs +++ b/runtime/crates/daemon/examples/adopt_rehearsal.rs @@ -3,15 +3,18 @@ //! can kill -9 the adopter at any point and check that a rerun converges. //! //! ```text -//! logsvc --listen 127.0.0.1:7741 --testkit-cp conformance --insecure-test-keys & +//! mdbn-log-server --listen 127.0.0.1:7741 --testkit-cp conformance --insecure-test-keys & //! export MDBASE_ENV=test MDBASE_SECRET_BACKEND=insecure-test-file //! adopt_rehearsal setup --log http://127.0.0.1:7741 --dir --docs 3000 [--cloud] +//! adopt_rehearsal read --dir # time the inventory and bucket read passes //! adopt_rehearsal adopt --dir [--exit-when-done] # kill -9 it, run again //! adopt_rehearsal verify --dir //! ``` //! //! Secrets live in the insecure test file store under ``; the example refuses -//! to run without both test variables (never the OS keychain). +//! to use the OS keychain. For optimized measurements, build the example with +//! `--release --config 'profile.release.package.mdbn-daemon.debug-assertions=true'` +//! so its test secret backend is available. #![allow(clippy::disallowed_methods, clippy::disallowed_types)] use std::collections::BTreeMap; @@ -95,6 +98,40 @@ async fn main() { p.private ); } + "read" => { + use mdbn_daemon::adopt::FolderSource; + use mdbn_platform_native::{NativePlatform, OpenOptions}; + use mdbn_replica::AdoptSource; + use mdbn_replica::replica::gen0::{Gen0Writer, bucket_bits}; + use mdbn_wire::common::B16; + let p = plan(&dir); + let platform = NativePlatform::open(dir.join("a"), &OpenOptions::default()).unwrap(); + let mut source = FolderSource::new(std::rc::Rc::new(platform), Default::default()); + let start = Instant::now(); + let mut read = |path: &str| source.read(path).unwrap().expect("seeded Markdown file"); + let bytes = p + .records + .iter() + .map(|(_, path)| read(path).len() as u64) + .sum(); + let inventory_ms = ms(start); + let writer = Gen0Writer::new(B16(p.collection), bucket_bits(bytes), false, false); + let mut records = p.adopt().records; + records.sort_unstable_by_key(|(id, _)| (writer.bucket_of(id), *id)); + let start = Instant::now(); + let mut max_capacity = 0u64; + for bucket in records.chunk_by(|a, b| writer.bucket_of(&a.0) == writer.bucket_of(&b.0)) + { + let docs: Vec<_> = bucket.iter().map(|(_, path)| read(path)).collect(); + let capacity = docs.iter().map(|doc| doc.capacity() as u64).sum(); + max_capacity = max_capacity.max(capacity); + } + println!( + "READ inventory_ms={inventory_ms} buckets_ms={} records={} bytes={bytes} max_bucket_capacity={max_capacity}", + ms(start), + p.records.len() + ); + } "adopt" => { let p = plan(&dir); let rt = scenario::open( @@ -198,6 +235,6 @@ async fn main() { assert_eq!((st.holds, st.unresolved), (0, 0)); rt.stop().await; } - _ => panic!("usage: adopt_rehearsal setup|adopt|verify --dir ..."), + _ => panic!("usage: adopt_rehearsal setup|read|adopt|verify --dir ..."), } } diff --git a/runtime/crates/daemon/src/adopt.rs b/runtime/crates/daemon/src/adopt.rs index 09fae6eef..652890055 100644 --- a/runtime/crates/daemon/src/adopt.rs +++ b/runtime/crates/daemon/src/adopt.rs @@ -30,6 +30,7 @@ pub const SCHEMA_VERSION: u32 = 1; /// Larger files are left to ordinary ingest after the base (the replica's own /// record-size admission is far below this). const MAX_READ: u32 = 16 * 1024 * 1024; +const FIRST_READ: u32 = 16 * 1024; /// The mode adopt creates the log in. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -155,17 +156,26 @@ impl AdoptSource for FolderSource

{ if rel.is_root() { return Ok(None); } - // One bounded read of the opened regular file: a file larger than the - // cap is refused by what was read, not by an earlier stat. - match now(self.platform.read_range(&rel, 0, MAX_READ + 1)) { - Ok(b) if b.len() as u64 <= u64::from(MAX_READ) => Ok(String::from_utf8(b).ok()), - Ok(_) => Ok(None), - Err(e) if e.kind == FsErrorKind::Other || e.kind == FsErrorKind::Busy => { - Err(format!("read: {:?}", e.kind)) + // A range reader can reserve the entire requested length. Start small; + // a short read proves EOF on that one confined file handle. Each retry + // rereads from zero so replacements cannot splice two files together. + // 16 KiB, 256 KiB, 4 MiB, then the admission limit plus its EOF probe. + let mut limit = FIRST_READ; + loop { + match now(self.platform.read_range(&rel, 0, limit)) { + Ok(mut bytes) if bytes.len() < limit as usize => { + // The sealer retains a bucket of documents at once. + bytes.shrink_to_fit(); + return Ok(String::from_utf8(bytes).ok()); + } + Ok(_) if limit < MAX_READ + 1 => limit = (limit * 16).min(MAX_READ + 1), + Ok(_) => return Ok(None), + Err(e) if e.kind == FsErrorKind::Other || e.kind == FsErrorKind::Busy => { + return Err(format!("read: {:?}", e.kind)); + } + // Gone, a link or unreadable: left to ordinary ingest after the base. + Err(_) => return Ok(None), } - // Gone, not a regular file, a link, or not ours to read: left to - // ordinary ingest after the base. - Err(_) => Ok(None), } } } @@ -221,6 +231,33 @@ mod tests { assert!(p.fs.log().iter().any(|l| l.contains("read_range n/a.md"))); } + #[test] + fn filled_ranges_reread_the_current_file_from_zero_and_enforce_the_cap() { + use mdbn_store_file::platform::{CaseSensitivity, ReplaceStrategy}; + use mdbn_store_file::testing::MemPlatform; + for size in [1, FIRST_READ, FIRST_READ + 1, MAX_READ, MAX_READ + 1] { + let p = Rc::new(MemPlatform::new( + ReplaceStrategy::Exchange, + CaseSensitivity::Sensitive, + )); + p.fs.write_in_place("note.md", &vec![b'x'; FIRST_READ as usize]) + .unwrap(); + p.fs.before_op(1, move |fs| { + fs.write_in_place("note.md", &vec![b'y'; size as usize]) + .unwrap(); + }); + let mut source = FolderSource::new(p, AdoptRecords::default()); + let doc = source.read("note.md").unwrap(); + if size <= MAX_READ { + let doc = doc.unwrap(); + assert_eq!(doc.len(), size as usize); + assert!(doc.bytes().all(|b| b == b'y')); + } else { + assert_eq!(doc, None); + } + } + } + #[cfg(unix)] #[test] fn folder_source_never_follows_a_link_out_of_the_folder() {