diff --git a/crates/pdfs-cli/src/main.rs b/crates/pdfs-cli/src/main.rs index b0e4bd3..40632e2 100644 --- a/crates/pdfs-cli/src/main.rs +++ b/crates/pdfs-cli/src/main.rs @@ -3608,6 +3608,18 @@ fn cmd_diagnostics() -> Result<()> { } if let Some(sync) = &d.sync { println!("sync engine: {}", sync_engine_line(sync)); + for trace in &sync.traces { + let how = if trace.ended.is_empty() { + "running" + } else { + trace.ended.as_str() + }; + println!( + " folder {} pass ({how}, {}): {trace}", + trace.folder_id, + human_secs(trace.elapsed_ms / 1000), + ); + } } if d.inflight.is_empty() { println!("in-flight requests: none"); diff --git a/crates/pdfs-core/src/control.rs b/crates/pdfs-core/src/control.rs index 20e4eb6..e3a0471 100644 --- a/crates/pdfs-core/src/control.rs +++ b/crates/pdfs-core/src/control.rs @@ -2360,6 +2360,111 @@ pub struct SyncEngineState { pub pass_idle_secs: u64, /// Passes that ended in a panic since the daemon started. pub panics: u64, + /// Where the running pass, and the last pass over each folder, spent their + /// time. Empty from a daemon that predates the field. + #[serde(default)] + pub traces: Vec, +} + +/// Where one sync pass spent its time, in a [`SyncEngineState`]. +/// +/// A pass over a large folder used to say only that it started and, hours +/// later, that it was cut short. Nothing said whether the hours went into the +/// local walk, listing Drive, unlocking node keys or uploading +/// (`docs/BUGS.md` B294). +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct SyncPassTrace { + pub folder_id: i64, + /// How the pass ended: `finished`, `cut short`, `abandoned`, `failed` or + /// `panicked`. Empty while it is still running. + pub ended: String, + /// How long the pass ran, or has run so far. + pub elapsed_ms: u64, + /// The stages of the pass, in order. + pub phases: Vec, + /// Calls to Drive, and the work applied per kind. + pub calls: Vec, + /// How many items each stage handled. + pub counts: Vec, + /// The folder on Drive whose listing took longest, and how long, in ms. + pub slowest_listing: Option<(String, u64)>, +} + +/// One line for the journal and `pdfs diagnostics`: `remote walk 2h10m, +/// local walk 41m05s; read nodes full 480000x/1h50m (max 3.0s); nodes full +/// 480000; slowest listing "a/b" 9.0s`. Stages and calls that never happened +/// are left out. +impl std::fmt::Display for SyncPassTrace { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut parts = Vec::new(); + let phases: Vec = self + .phases + .iter() + .map(|s| format!("{} {}", s.name, human_ms(s.total_ms))) + .collect(); + if !phases.is_empty() { + parts.push(phases.join(", ")); + } + let calls: Vec = self + .calls + .iter() + .map(|s| { + format!( + "{} {}x/{} (max {})", + s.name, + s.count, + human_ms(s.total_ms), + human_ms(s.max_ms) + ) + }) + .collect(); + if !calls.is_empty() { + parts.push(calls.join(", ")); + } + let counts: Vec = self + .counts + .iter() + .map(|c| format!("{} {}", c.name, c.value)) + .collect(); + if !counts.is_empty() { + parts.push(counts.join(", ")); + } + if let Some((rel, ms)) = &self.slowest_listing { + let rel = if rel.is_empty() { "/" } else { rel.as_str() }; + parts.push(format!("slowest listing {rel:?} {}", human_ms(*ms))); + } + f.write_str(&parts.join("; ")) + } +} + +/// `950ms`, `12.3s`, `41m05s`, `2h10m`. +fn human_ms(ms: u64) -> String { + let secs = ms / 1000; + if ms < 1000 { + format!("{ms}ms") + } else if secs < 60 { + format!("{:.1}s", ms as f64 / 1000.0) + } else if secs < 3600 { + format!("{}m{:02}s", secs / 60, secs % 60) + } else { + format!("{}h{:02}m", secs / 3600, (secs % 3600) / 60) + } +} + +/// How often one thing happened in a pass, and how long it took. +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct SyncTraceStat { + pub name: String, + pub count: u64, + pub total_ms: u64, + pub max_ms: u64, +} + +/// One counter of a [`SyncPassTrace`]. +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct SyncTraceCount { + pub name: String, + pub value: u64, } /// The daemon's reply to a [`Request`]. @@ -3003,6 +3108,14 @@ fn poll_legacy(socket: &Path, on: &mut impl FnMut(Feed) -> bool) -> bool { mod tests { use super::*; + #[test] + fn durations_in_a_trace_read_at_a_glance() { + assert_eq!(human_ms(950), "950ms"); + assert_eq!(human_ms(12_345), "12.3s"); + assert_eq!(human_ms(2_465_000), "41m05s"); + assert_eq!(human_ms(7_800_000), "2h10m"); + } + #[test] fn polls_wait_briefly_and_real_work_waits_long() { assert_eq!(Request::Status.read_timeout(), POLL_READ_TIMEOUT); diff --git a/crates/pdfs-fuse/src/sim/daemon.rs b/crates/pdfs-fuse/src/sim/daemon.rs index 9c00426..70588b2 100644 --- a/crates/pdfs-fuse/src/sim/daemon.rs +++ b/crates/pdfs-fuse/src/sim/daemon.rs @@ -1647,6 +1647,99 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// The trace of the last finished pass over `folder` that `done` accepts. + fn traced_pass( + daemon: &Daemon, + folder: i64, + done: impl Fn(&control::SyncPassTrace) -> bool, + ) -> Option { + let mut found = None; + wait_until(Duration::from_secs(30), || { + let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics) + else { + return false; + }; + found = diagnostics.sync.and_then(|sync| { + sync.traces + .into_iter() + .find(|t| t.folder_id == folder && t.ended == "finished" && done(t)) + }); + found.is_some() + }); + found + } + + fn calls(trace: &control::SyncPassTrace, name: &str) -> u64 { + trace + .calls + .iter() + .find(|c| c.name == name) + .map_or(0, |c| c.count) + } + + fn counted(trace: &control::SyncPassTrace, name: &str) -> u64 { + trace + .counts + .iter() + .find(|c| c.name == name) + .map_or(0, |c| c.value) + } + + #[test] + #[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"] + fn a_mirror_pass_reports_where_its_time_went() { + // A pass over a large folder said only that it started and, hours + // later, that a stop cut it short (B294). Its trace says what each + // stage did, in `pdfs diagnostics` and in the journal. + let drive = FakeDrive::new(); + let dir = scratch("mirror-pass-trace"); + let (daemon, folder, _client) = start_mirror( + &drive, + &dir, + &[("a.txt", b"one"), ("b.txt", b"two"), ("c.txt", b"three")], + ); + let first = traced_pass(&daemon, folder, |t| calls(t, "upload") > 0) + .expect("the first pass is traced"); + assert_eq!(calls(&first, "upload"), 3); + assert_eq!(counted(&first, "local entries"), 3); + assert!(counted(&first, "remote folders") >= 1); + for phase in ["baseline", "local walk", "remote walk", "apply"] { + assert!( + first.phases.iter().any(|p| p.name == phase), + "no {phase} in {first}" + ); + } + assert!( + take_logged() + .iter() + .any(|line| line.contains("sync: pass trace")) + ); + + // Drive does not list a node it has just made at once, so the read + // back after an upload has no revision id to record. The next pass + // reads those files in full, one key unlock each, and records it. + daemon + .request(&Request::SyncNow { id: Some(folder) }) + .unwrap(); + let filled = traced_pass(&daemon, folder, |t| counted(t, "revisions recorded") == 3) + .expect("the pass after the uploads is traced"); + assert_eq!(counted(&filled, "nodes full"), 3, "{filled}"); + + // Every pass after that reads every node without a key unlock and + // applies nothing. + daemon + .request(&Request::SyncNow { id: Some(folder) }) + .unwrap(); + let quiet = traced_pass(&daemon, folder, |t| { + counted(t, "nodes") == 3 && counted(t, "nodes full") == 0 + }) + .expect("a quiet pass is traced"); + assert_eq!(calls(&quiet, "upload"), 0, "{quiet}"); + assert_eq!(counted(&quiet, "queued"), 0, "{quiet}"); + assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown))); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] #[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"] fn a_mirror_edit_does_not_replace_a_revision_another_computer_made_since() { diff --git a/crates/pdfs-fuse/src/supervisor.rs b/crates/pdfs-fuse/src/supervisor.rs index c15e5da..959741f 100644 --- a/crates/pdfs-fuse/src/supervisor.rs +++ b/crates/pdfs-fuse/src/supervisor.rs @@ -305,6 +305,7 @@ mod tests { pass_age_secs: SYNC_STALL_AFTER.as_secs() * 4, pass_idle_secs: 5, panics: 0, + traces: Vec::new(), }; assert!(!report_stalls(&with_sync(busy.clone()), (0, 0))); let quiet = SyncEngineState { diff --git a/crates/pdfs-fuse/src/sync.rs b/crates/pdfs-fuse/src/sync.rs index d9fb82c..c818dfe 100644 --- a/crates/pdfs-fuse/src/sync.rs +++ b/crates/pdfs-fuse/src/sync.rs @@ -48,6 +48,7 @@ mod engine; mod local_scan; mod model; mod planner; +mod trace; pub(crate) use engine::SYNC_CONCURRENCY; pub(crate) use engine::{EngineHealth, SyncMsg, spawn}; #[cfg(test)] @@ -69,6 +70,7 @@ use planner::{ plan_file, rel_to_path, remote_sig, remote_subtree_changed, revision_confirms_baseline, revision_moved, tracked_baseline, unchanged_remote_size, }; +use trace::{Call, Count, Phase}; /// A pass that took at least this long is logged at info even when it changed /// nothing, so the journal says where a slow engine spends its time. @@ -123,7 +125,9 @@ impl Core { // Hold the folder's lock for the whole pass so a mode switch can't evict the // local tree (and mount FUSE over it) while we walk and upload it. let lock = self.sync_lock(folder.id); + let waited = Instant::now(); let _guard = lock.lock(); + self.trace_phase(Phase::LockWait, waited.elapsed()); // `folder` was read before the lock; a switch may have landed in between, so // re-read and re-check the mode rather than trusting the snapshot. let current = match self.db.sync_folder_get(folder.id) { @@ -210,6 +214,7 @@ impl Core { }; let progress = self.sync_progress.lock().get(&folder.id).cloned(); self.progress_end(folder.id); + self.log_trace(folder, &result, started.elapsed()); match result { Ok(outcome) => { // A folder only reaches `idle` when every path applied cleanly — @@ -326,6 +331,46 @@ impl Core { self.sync_abandon.lock().remove(&folder.id); } + /// End the running pass's trace and put it in the journal: at info for + /// a pass worth hearing about (a first, slow or unfinished one), else at + /// debug, so the poll over a quiet folder adds nothing every two minutes. + fn log_trace( + &self, + folder: &StoredSyncFolder, + result: &Result, + elapsed: Duration, + ) { + let how = match result { + Ok(_) => "finished", + Err(PassAbort::Stopped | PassAbort::Interrupted) => "cut short", + Err(PassAbort::Abandoned) => "abandoned", + Err(PassAbort::Failed(_)) => "failed", + }; + let Some(trace) = self.sync_engine.end_trace(how) else { + return; + }; + if how != "finished" || folder.last_sync == 0 || elapsed >= SLOW_PASS { + info!(id = folder.id, how, trace = %trace, "sync: pass trace"); + } else { + debug!(id = folder.id, how, trace = %trace, "sync: pass trace"); + } + } + + /// Add `took` to a stage of the running pass's trace. + fn trace_phase(&self, phase: Phase, took: Duration) { + self.sync_engine.trace(|t| t.phase(phase, took)); + } + + /// Add one call that took `took` to the running pass's trace. + fn trace_call(&self, call: Call, took: Duration) { + self.sync_engine.trace(|t| t.call(call, took)); + } + + /// Add `n` to a counter of the running pass's trace. + fn trace_count(&self, count: Count, n: usize) { + self.sync_engine.trace(|t| t.count(count, n)); + } + /// Tell the activity feed what a pass over this folder had to leave out /// because it cannot be read, once each time that changes. Every other path /// in the folder still synced, so this does not make the folder's state an @@ -419,15 +464,18 @@ impl Core { remote_root: &NodeUid, rules: &IgnoreRules, ) -> Result { + let step = Instant::now(); let baseline = self .db .sync_entries(folder_id) .map_err(|e| format!("load baseline: {e:?}"))?; + self.trace_phase(Phase::Baseline, step.elapsed()); // Only the local side is walked here, so each baseline path is checked once. self.progress_scan_total(folder_id, baseline.len()); let mut local: HashMap = HashMap::new(); let mut unscanned = Unscanned::default(); + let step = Instant::now(); let writing = open_for_write_set(local_root); self.walk_local( folder_id, @@ -437,6 +485,8 @@ impl Core { &mut local, &mut unscanned, )?; + self.trace_phase(Phase::LocalWalk, step.elapsed()); + self.trace_count(Count::LocalEntries, local.len()); // The guard compares against the paths this pass could still see: an // ignored or unreadable path is absent from `local` by rule or by // failure, not by loss, and counting those as missing would trip the @@ -743,15 +793,18 @@ impl Core { // unchanged and so can skip decrypting their claimed size, and its size is // the only estimate available of how much this pass has to check — the walks // discover the real figure only by finishing. + let step = Instant::now(); let baseline = self .db .sync_entries(folder_id) .map_err(|e| format!("load baseline: {e:?}"))?; + self.trace_phase(Phase::Baseline, step.elapsed()); // Both sides are walked, so each baseline path is checked about twice. self.progress_scan_total(folder_id, baseline.len() * 2); let mut local: HashMap = HashMap::new(); let mut unscanned = Unscanned::default(); + let step = Instant::now(); let writing = open_for_write_set(local_root); self.walk_local( folder_id, @@ -761,6 +814,8 @@ impl Core { &mut local, &mut unscanned, )?; + self.trace_phase(Phase::LocalWalk, step.elapsed()); + self.trace_count(Count::LocalEntries, local.len()); // See `push_pass`: the guard must not count excluded paths as lost. guard_local_wipe(&tracked_baseline(&baseline, rules, &unscanned), &local)?; @@ -768,7 +823,8 @@ impl Core { let mut remote_dirs: HashMap = HashMap::new(); let mut gaps = RemoteGaps::default(); remote_dirs.insert(String::new(), remote_root.clone()); - self.walk_remote( + let step = Instant::now(); + let walked = self.walk_remote( folder_id, remote_root, "", @@ -778,7 +834,11 @@ impl Core { gaps: &mut gaps, }, &baseline, - )?; + ); + // Timed even when cut short: a walk that never ends is the case the + // trace exists for. + self.trace_phase(Phase::RemoteWalk, step.elapsed()); + walked?; guard_remote_wipe(&tracked_baseline(&baseline, rules, &unscanned), &remote)?; let mut order = classification_order(&local, &remote, &baseline, rules); @@ -811,21 +871,32 @@ impl Core { // counted, never fatal. let mut batch: Vec = Vec::new(); let mut batch_depth = 0usize; + // The plan stage is the loop's time without the batches it flushes, + // which `flush_batch` times as the apply stage. + let planning = Instant::now(); + let mut applying = Duration::ZERO; for rel in &order { let depth = rel.matches('/').count(); if depth > batch_depth { - self.flush_batch( + let step = Instant::now(); + let flushed = self.flush_batch( folder_id, local_root, &mut remote_dirs, std::mem::take(&mut batch), &mut outcome, - )?; + ); + applying += step.elapsed(); + if flushed.is_err() { + self.trace_phase(Phase::Plan, planning.elapsed().saturating_sub(applying)); + } + flushed?; batch_depth = depth; // A depth boundary is the pass's natural checkpoint — everything // queued has been applied, so stopping here leaves nothing half done. if self.ondemand_queued(folder_id) { + self.trace_phase(Phase::Plan, planning.elapsed().saturating_sub(applying)); return Err(PassAbort::Interrupted); } } @@ -989,11 +1060,13 @@ impl Core { } FilePlan::DeleteRemote => { let remote = r.expect("remote deletion requires a remote file"); - if let Err(e) = self + let step = Instant::now(); + let trashed = self .rt .block_on(self.drive.trash_nodes(std::slice::from_ref(&remote.uid))) - .and_then(batch::into_unit) - { + .and_then(batch::into_unit); + self.trace_call(Call::Trash, step.elapsed()); + if let Err(e) = trashed { warn!(rel, error = %e, "sync: trash remote failed"); self.log_activity( ActivityKind::Trash, @@ -1021,6 +1094,7 @@ impl Core { } } } + self.trace_phase(Phase::Plan, planning.elapsed().saturating_sub(applying)); // Flush the deepest level's batch. self.flush_batch( folder_id, @@ -1029,6 +1103,7 @@ impl Core { std::mem::take(&mut batch), &mut outcome, )?; + let cleanup = Instant::now(); // Deferred folder deletions, deepest first. A folder that holds what // Drive never had stays, and its baseline row goes, so the next pass @@ -1094,11 +1169,13 @@ impl Core { ); continue; } - if let Err(e) = self + let step = Instant::now(); + let trashed = self .rt .block_on(self.drive.trash_nodes(&[uid])) - .and_then(batch::into_unit) - { + .and_then(batch::into_unit); + self.trace_call(Call::Trash, step.elapsed()); + if let Err(e) = trashed { warn!(rel, error = %e, "sync: trash remote folder failed"); self.log_activity(ActivityKind::Trash, base_name(&rel), e.to_string(), false); outcome.failed(&format!("{rel}: {e}")); @@ -1116,6 +1193,7 @@ impl Core { ); outcome.deleted += 1; } + self.trace_phase(Phase::Cleanup, cleanup.elapsed()); Ok(outcome) } @@ -1209,10 +1287,14 @@ impl Core { if self.ondemand_queued(folder_id) { return Err(PassAbort::Interrupted); } + let listing = Instant::now(); + let step = Instant::now(); let uids = self .rt .block_on(self.drive.enumerate_folder_children_node_uids(folder)) .map_err(|e| format!("enumerate {folder}: {e}")); + self.trace_call(Call::ListChildren, step.elapsed()); + self.trace_count(Count::RemoteFolders, 1); let uids = match unlisted_gap(walk, prefix, uids)? { Some(uids) => uids, None => return Ok(()), @@ -1220,10 +1302,12 @@ impl Core { if uids.is_empty() { return Ok(()); } + let step = Instant::now(); let nodes = self .rt .block_on(self.drive.enumerate_nodes_light(&uids)) .map_err(|e| format!("resolve nodes: {e}")); + self.trace_call(Call::ReadNodes, step.elapsed()); let nodes = match unlisted_gap(walk, prefix, nodes)? { Some(nodes) => nodes, None => return Ok(()), @@ -1271,10 +1355,13 @@ impl Core { let sized: HashMap)> = if stale.is_empty() { HashMap::new() } else { + let step = Instant::now(); let full = self .rt .block_on(self.drive.enumerate_nodes(&stale)) .map_err(|e| format!("resolve nodes: {e}")); + self.trace_call(Call::ReadNodesFull, step.elapsed()); + self.trace_count(Count::NodesFull, stale.len()); let Some(full) = unlisted_gap(walk, prefix, full)? else { return Ok(()); }; @@ -1289,6 +1376,10 @@ impl Core { }; let stale: HashSet = stale.iter().map(|u| u.to_string()).collect(); self.record_revisions(folder_id, prefix, &nodes, &sized, baseline); + self.trace_count(Count::Nodes, nodes.len()); + // This folder's own listing, before the walk goes into its subfolders. + self.sync_engine + .trace(|t| t.listing(prefix, listing.elapsed())); for node in nodes { if node.trashed { @@ -1369,8 +1460,9 @@ impl Core { if rows.is_empty() { return; } - if let Err(e) = self.db.sync_entries_set_revision(folder_id, &rows) { - debug!(folder = prefix, error = ?e, "sync: cannot record revision ids"); + match self.db.sync_entries_set_revision(folder_id, &rows) { + Ok(n) => self.trace_count(Count::Revisions, n), + Err(e) => debug!(folder = prefix, error = ?e, "sync: cannot record revision ids"), } } @@ -1414,6 +1506,8 @@ impl Core { return Ok(()); } self.progress_queued(folder_id, batch.len()); + self.trace_count(Count::Queued, batch.len()); + let applying = Instant::now(); let core = self.clone(); let root = local_root.to_path_buf(); let results = self.rt.block_on(async move { @@ -1449,6 +1543,7 @@ impl Core { } (out, join_errors) }); + self.trace_phase(Phase::Apply, applying.elapsed()); let (results, join_errors) = results; outcome.errors += join_errors; for result in results { @@ -1493,7 +1588,9 @@ impl Core { op: Pending, ) -> Result { self.progress_started(folder_id, base_name(op.rel())); + let step = Instant::now(); let result = self.apply_one(folder_id, local_root, &op).await; + self.trace_call(op.call(), step.elapsed()); self.progress_finished(folder_id); let name = base_name(op.rel()); match &result { @@ -2622,6 +2719,42 @@ mod tests { assert_eq!(health.report().panics, 1); } + /// Each folder's last traced pass stays in the report, the running one + /// comes first, and a pass that never got going leaves none (B294). + #[test] + fn the_last_pass_of_each_folder_is_traced() { + let health = EngineHealth::default(); + health.contain(2, || { + health.trace(|t| t.call(Call::ReadNodesFull, Duration::from_secs(2))); + health.end_trace("cut short"); + }); + health.contain(3, || {}); + assert!(!health.contain(4, || panic!("a pass that panics"))); + let mut running = None; + health.contain(3, || { + health.trace(|t| t.count(Count::Nodes, 5)); + running = Some(health.report().traces); + }); + + let running = running.unwrap(); + assert_eq!(running[0].folder_id, 3); + assert_eq!(running[0].ended, ""); + let ended: Vec<(i64, String)> = health + .report() + .traces + .into_iter() + .map(|t| (t.folder_id, t.ended)) + .collect(); + assert_eq!( + ended, + [(2, "cut short".into()), (4, "panicked".into())], + "folder 3 never ended its trace" + ); + let cut = &health.report().traces[0]; + assert_eq!(cut.calls[0].name, "read nodes full"); + assert_eq!(cut.calls[0].total_ms, 2000); + } + /// Folders named by id run before the rest of a `ReconcileAll` in the /// same burst, so a folder just added does not wait behind a pass over /// every other folder (`docs/BUGS.md` B260). diff --git a/crates/pdfs-fuse/src/sync/engine.rs b/crates/pdfs-fuse/src/sync/engine.rs index 81114b9..2bef847 100644 --- a/crates/pdfs-fuse/src/sync/engine.rs +++ b/crates/pdfs-fuse/src/sync/engine.rs @@ -6,6 +6,9 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use pdfs_core::control::SyncEngineState; use tracing::error; +use std::collections::BTreeMap; + +use super::trace::PassTrace; use super::*; /// How long the watcher must go quiet before a burst counts as finished. @@ -73,6 +76,10 @@ pub(crate) struct EngineHealth { running: AtomicBool, pass: Mutex>, panics: AtomicU64, + /// The running pass's trace, while a pass runs. + trace: Mutex>, + /// The last trace of each folder's pass that got past its checks. + traces: Mutex>, } #[derive(Clone, Copy)] @@ -109,12 +116,26 @@ impl EngineHealth { /// a report must not wait on the thing it reports about. pub(crate) fn report(&self) -> SyncEngineState { let pass = self.pass.try_lock().and_then(|pass| *pass); + let mut traces: Vec<_> = self + .traces + .try_lock() + .map(|t| t.values().map(PassTrace::summary).collect()) + .unwrap_or_default(); + if let Some(running) = self + .trace + .try_lock() + .and_then(|t| t.as_ref().map(PassTrace::summary)) + { + traces.retain(|t| t.folder_id != running.folder_id); + traces.insert(0, running); + } SyncEngineState { running: self.running.load(Ordering::Relaxed), pass_folder: pass.map(|p| p.folder), pass_age_secs: pass.map_or(0, |p| p.started.elapsed().as_secs()), pass_idle_secs: pass.map_or(0, |p| p.moved.elapsed().as_secs()), panics: self.panics.load(Ordering::Relaxed), + traces, } } @@ -128,13 +149,38 @@ impl EngineHealth { moved: now, logged: now, }); + *self.trace.lock() = Some(PassTrace::new(folder)); let finished = std::panic::catch_unwind(AssertUnwindSafe(pass)).is_ok(); *self.pass.lock() = None; if !finished { self.panics.fetch_add(1, Ordering::Relaxed); + self.end_trace("panicked"); + } + // A pass that never ended its trace was skipped (paused, on-demand, + // stopping) and has nothing worth keeping. + if let Some(trace) = self.trace.lock().take() + && trace.is_ended() + { + self.traces.lock().insert(trace.folder_id(), trace); } finished } + + /// Apply `f` to the running pass's trace. Does nothing outside a pass. + pub(crate) fn trace(&self, f: impl FnOnce(&mut PassTrace)) { + if let Some(trace) = self.trace.lock().as_mut() { + f(trace); + } + } + + /// Note that the running pass ended, `how`, and return its trace for the + /// journal. + pub(crate) fn end_trace(&self, how: &'static str) -> Option { + let mut trace = self.trace.lock(); + let trace = trace.as_mut()?; + trace.end(how); + Some(trace.clone()) + } } /// Marks the engine running for as long as it lives. diff --git a/crates/pdfs-fuse/src/sync/model.rs b/crates/pdfs-fuse/src/sync/model.rs index 3bc5da0..88e0b02 100644 --- a/crates/pdfs-fuse/src/sync/model.rs +++ b/crates/pdfs-fuse/src/sync/model.rs @@ -267,6 +267,18 @@ impl Pending { } } + /// Which call of the pass's trace this op counts as. + pub(super) fn call(&self) -> Call { + match self { + Pending::CreateDir { .. } => Call::CreateFolder, + Pending::UploadNew { .. } | Pending::PushConflict { .. } => Call::Upload, + Pending::UploadRevision { .. } => Call::UploadRevision, + Pending::Download { .. } => Call::Download, + Pending::Adopt { .. } => Call::Adopt, + Pending::Conflict { .. } => Call::Conflict, + } + } + /// How this op reads in the activity feed. pub(super) fn kind(&self) -> ActivityKind { match self { diff --git a/crates/pdfs-fuse/src/sync/trace.rs b/crates/pdfs-fuse/src/sync/trace.rs new file mode 100644 index 0000000..29c110a --- /dev/null +++ b/crates/pdfs-fuse/src/sync/trace.rs @@ -0,0 +1,327 @@ +//! Where a reconcile pass spends its time. +//! +//! A pass over a large folder used to log that it started and, hours later, +//! that a stop cut it short. Nothing said whether the hours went into the local +//! walk, listing Drive, unlocking node keys or applying (`docs/BUGS.md` B294). +//! A [`PassTrace`] times each stage and each kind of call to Drive, counts what +//! each stage handled, and ends up in the journal and in `pdfs diagnostics`. + +use std::fmt; + +use pdfs_core::control::{SyncPassTrace, SyncTraceCount, SyncTraceStat}; + +use super::*; + +/// A stage of a pass. A pass runs them in this order, except that planning +/// and applying alternate, one folder depth at a time. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Phase { + /// Waiting for the folder's lock, held by a mode switch or a relocation. + LockWait, + /// Reading the stored baseline from the database. + Baseline, + LocalWalk, + RemoteWalk, + /// Deciding what to do with each path, and the inline work that needs no + /// network (local folders, baseline rows, local deletions). + Plan, + /// Running the queued uploads, downloads and folder creations. + Apply, + /// Removing the folders deleted on either side, deepest first. + Cleanup, +} + +impl Phase { + const ALL: [Phase; 7] = [ + Phase::LockWait, + Phase::Baseline, + Phase::LocalWalk, + Phase::RemoteWalk, + Phase::Plan, + Phase::Apply, + Phase::Cleanup, + ]; + + fn name(self) -> &'static str { + match self { + Phase::LockWait => "lock wait", + Phase::Baseline => "baseline", + Phase::LocalWalk => "local walk", + Phase::RemoteWalk => "remote walk", + Phase::Plan => "plan", + Phase::Apply => "apply", + Phase::Cleanup => "cleanup", + } + } +} + +/// A kind of call to Drive, or of work applied for one path. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Call { + /// The child uids of one folder. + ListChildren, + /// Names and kinds of one folder's children, without unlocking file keys. + ReadNodes, + /// Full reads of the files whose size had to be read for real: one node + /// key unlock each. + ReadNodesFull, + CreateFolder, + Upload, + UploadRevision, + Download, + /// Hashing a local file to match it up with Drive's copy on a first sync. + Adopt, + Conflict, + Trash, +} + +impl Call { + const ALL: [Call; 10] = [ + Call::ListChildren, + Call::ReadNodes, + Call::ReadNodesFull, + Call::CreateFolder, + Call::Upload, + Call::UploadRevision, + Call::Download, + Call::Adopt, + Call::Conflict, + Call::Trash, + ]; + + fn name(self) -> &'static str { + match self { + Call::ListChildren => "list children", + Call::ReadNodes => "read nodes", + Call::ReadNodesFull => "read nodes full", + Call::CreateFolder => "create folder", + Call::Upload => "upload", + Call::UploadRevision => "upload revision", + Call::Download => "download", + Call::Adopt => "adopt", + Call::Conflict => "conflict", + Call::Trash => "trash", + } + } +} + +/// Something a pass counts. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Count { + /// Files and folders the local walk found. + LocalEntries, + /// Folders on Drive the remote walk listed. + RemoteFolders, + /// Nodes read without unlocking their key. + Nodes, + /// Nodes read in full, one key unlock each. + NodesFull, + /// Baseline rows given the revision id they were missing. + Revisions, + /// Paths queued for the apply stage. + Queued, +} + +impl Count { + const ALL: [Count; 6] = [ + Count::LocalEntries, + Count::RemoteFolders, + Count::Nodes, + Count::NodesFull, + Count::Revisions, + Count::Queued, + ]; + + fn name(self) -> &'static str { + match self { + Count::LocalEntries => "local entries", + Count::RemoteFolders => "remote folders", + Count::Nodes => "nodes", + Count::NodesFull => "nodes full", + Count::Revisions => "revisions recorded", + Count::Queued => "queued", + } + } +} + +/// How often one thing happened, and how long it took. +#[derive(Clone, Copy, Default, Debug)] +struct Stat { + count: u64, + total: Duration, + max: Duration, +} + +impl Stat { + fn add(&mut self, took: Duration) { + self.count += 1; + self.total += took; + self.max = self.max.max(took); + } + + fn summary(self, name: &str) -> SyncTraceStat { + SyncTraceStat { + name: name.to_string(), + count: self.count, + total_ms: millis(self.total), + max_ms: millis(self.max), + } + } +} + +/// The timings and counts of one pass. +#[derive(Clone, Debug)] +pub(crate) struct PassTrace { + folder_id: i64, + started: Instant, + /// How the pass ended and how long it ran; `None` while it runs. + ended: Option<(&'static str, Duration)>, + phases: [Stat; Phase::ALL.len()], + calls: [Stat; Call::ALL.len()], + counts: [u64; Count::ALL.len()], + slowest_listing: Option<(String, Duration)>, +} + +impl PassTrace { + pub(crate) fn new(folder_id: i64) -> Self { + Self { + folder_id, + started: Instant::now(), + ended: None, + phases: [Stat::default(); Phase::ALL.len()], + calls: [Stat::default(); Call::ALL.len()], + counts: [0; Count::ALL.len()], + slowest_listing: None, + } + } + + pub(crate) fn folder_id(&self) -> i64 { + self.folder_id + } + + pub(crate) fn is_ended(&self) -> bool { + self.ended.is_some() + } + + pub(crate) fn phase(&mut self, phase: Phase, took: Duration) { + self.phases[phase as usize].add(took); + } + + pub(crate) fn call(&mut self, call: Call, took: Duration) { + self.calls[call as usize].add(took); + } + + pub(crate) fn count(&mut self, count: Count, n: usize) { + self.counts[count as usize] += n as u64; + } + + /// Note how long listing the Drive folder at `rel` took, keeping the slowest. + pub(crate) fn listing(&mut self, rel: &str, took: Duration) { + if self + .slowest_listing + .as_ref() + .is_none_or(|(_, max)| took > *max) + { + self.slowest_listing = Some((rel.to_string(), took)); + } + } + + pub(crate) fn end(&mut self, how: &'static str) { + if self.ended.is_none() { + self.ended = Some((how, self.started.elapsed())); + } + } + + fn elapsed(&self) -> Duration { + self.ended + .map_or_else(|| self.started.elapsed(), |(_, took)| took) + } + + /// The trace as `pdfs diagnostics` reports it. Stages and calls that + /// never happened are left out. + pub(crate) fn summary(&self) -> SyncPassTrace { + SyncPassTrace { + folder_id: self.folder_id, + ended: self + .ended + .map(|(how, _)| how.to_string()) + .unwrap_or_default(), + elapsed_ms: millis(self.elapsed()), + phases: Phase::ALL + .iter() + .filter(|p| self.phases[**p as usize].count > 0) + .map(|p| self.phases[*p as usize].summary(p.name())) + .collect(), + calls: Call::ALL + .iter() + .filter(|c| self.calls[**c as usize].count > 0) + .map(|c| self.calls[*c as usize].summary(c.name())) + .collect(), + counts: Count::ALL + .iter() + .filter(|c| self.counts[**c as usize] > 0) + .map(|c| SyncTraceCount { + name: c.name().to_string(), + value: self.counts[*c as usize], + }) + .collect(), + slowest_listing: self + .slowest_listing + .as_ref() + .map(|(rel, took)| (rel.clone(), millis(*took))), + } + } +} + +/// One line for the journal; see [`SyncPassTrace`]'s `Display`. +impl fmt::Display for PassTrace { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.summary().fmt(f) + } +} + +fn millis(d: Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_trace_reports_only_what_happened() { + let mut trace = PassTrace::new(3); + trace.phase(Phase::RemoteWalk, Duration::from_secs(7800)); + trace.call(Call::ReadNodesFull, Duration::from_secs(2)); + trace.call(Call::ReadNodesFull, Duration::from_secs(3)); + trace.count(Count::NodesFull, 480); + trace.listing("a", Duration::from_secs(1)); + trace.listing("a/b", Duration::from_secs(9)); + trace.listing("c", Duration::from_secs(4)); + trace.end("cut short"); + trace.end("finished"); + + let summary = trace.summary(); + assert_eq!(summary.folder_id, 3); + assert_eq!(summary.ended, "cut short"); + assert_eq!(summary.phases.len(), 1); + assert_eq!(summary.phases[0].name, "remote walk"); + assert_eq!( + summary.calls, + vec![SyncTraceStat { + name: "read nodes full".into(), + count: 2, + total_ms: 5000, + max_ms: 3000, + }] + ); + assert_eq!(summary.counts.len(), 1); + assert_eq!(summary.counts[0].value, 480); + assert_eq!(summary.slowest_listing, Some(("a/b".into(), 9000))); + assert_eq!( + summary.to_string(), + "remote walk 2h10m; read nodes full 2x/5.0s (max 3.0s); nodes full 480; \ + slowest listing \"a/b\" 9.0s" + ); + } +} diff --git a/docs/BUGS.md b/docs/BUGS.md index 7ad2e83..5a844ae 100644 --- a/docs/BUGS.md +++ b/docs/BUGS.md @@ -441,6 +441,12 @@ Not changed: a pass still walks both trees before it applies anything, so a fold be walked in one run still never syncs. Applying changes per subtree as the walk goes is the fix for that, and is not done. The two-minute poll still walks every folder in turn. +Later: every pass keeps a trace of where its time went (`crates/pdfs-fuse/src/sync/trace.rs`), +in the journal as `sync: pass trace` and in `pdfs diagnostics`. The sim test +`a_mirror_pass_reports_where_its_time_went` showed that a file uploaded by a pass also gets a +baseline row without a revision id, because Drive does not list it at once and the upload +returns only its uid. The next pass reads it in full once and records the id. + **Verified:** `revision_ids_fill_only_rows_without_one`, `baseline_rows_are_counted_per_folder`, `folders_left_syncing_are_reset_to_error`, `only_an_unchanged_row_without_an_id_takes_the_revision` and `the_smallest_folders_run_first_in_a_burst` on 2026-11-25. Not yet checked on the reporter's diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a1c894d..00db30c 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,6 +11,14 @@ scratch (user data in `staging/` and `recovery/` is never touched by this). ## [Unreleased] +### Added + +- **`pdfs diagnostics` and the journal say where a sync pass spends its time.** Each pass over a + synced folder records how long it took to walk this computer's copy, list Proton Drive, plan + and apply. It also records how many calls to Proton Drive it made of each kind, how long they + took, and which folder on Drive was slowest to list. The trace shows the running pass and the + last pass over each folder, in the journal as `sync: pass trace` (B294). + ## [3.10.0] — 2026-11-22 Schema: **47**. The trash table gets an index on the original folder, and its stored rows are diff --git a/docs/CLI.md b/docs/CLI.md index 072a69f..6f4433e 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -218,7 +218,7 @@ commands are for scripts and for cases where the mount is not available. | Command | Description | |---|---| | `pdfs diagnose` | Check the installation and print a report. Works without the service. When the service does not answer, also asks Proton which of your keys open. Exits non-zero if a check fails. | -| `pdfs diagnostics` | What a running service is doing now: worker threads, queues, requests in flight, memory. For a service that has stopped answering. | +| `pdfs diagnostics` | What a running service is doing now: worker threads, queues, requests in flight, memory, and where each synced folder's last pass spent its time. For a service that has stopped answering, or a synced folder that never finishes. | | `pdfs cache inspect [--deep]` | Database size, reclaimable space, row counts, cache use against the limit. `--deep` also runs SQLite's integrity check (slow). | | `pdfs cache vacuum` | Compact the database. Needs free space for a second copy of it while it runs. | | `pdfs cache clear` | Delete cached file content. Files kept available offline stay. | diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 4de01f3..e0dbbf2 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -263,6 +263,38 @@ pdfs sync reset 1 This downloads what Proton Drive has and uploads what only this computer has. Nothing is deleted. If you deleted the files on purpose, delete them on Proton Drive too, or stop syncing the folder. +### A synced folder takes hours, or never finishes + +Every pass over a synced folder leaves a trace of where its time went. `pdfs diagnostics` shows +the running pass and the last pass over each folder (one line each, wrapped here): + +``` +sync engine: pass on folder 2 for 2h14m, last progress 0s ago + folder 2 pass (running, 2h14m): baseline 3.1s, local walk 41m05s, remote walk 1h32m; + list children 1200x/4m10s (max 3.0s), read nodes 1200x/12m40s (max 4.2s), + read nodes full 1100x/1h15m (max 9.8s); local entries 493000, remote folders 1200, + nodes 310000, nodes full 290000, revisions recorded 290000; slowest listing "Fotos/2019" 9.8s +``` + +The journal has the same line as `sync: pass trace` when a pass ends, is cut short or takes longer +than 30 seconds: + +```bash +journalctl --user -u proton-drive.service | grep 'sync: pass trace' +``` + +What the parts mean: + +- **Stages:** `local walk` reads this computer's copy, `remote walk` lists Proton Drive, `plan` + decides what to do with each path, `apply` uploads, downloads and creates folders, and `cleanup` + removes deleted folders. `lock wait` is time spent waiting for a mode switch or a move to finish. +- **`read nodes full`** unlocks one key per file, to read a size that changed or was never + recorded. A high count here on a folder that has not changed is the slow case from B294. Each + pass records what it read, so the count falls on the next pass even if this one is cut short. +- **`slowest listing`** names the folder on Proton Drive that took longest to list. + +Please include these lines when you report a slow folder. + ### Files named `(sync-conflict …)` appeared The file changed in two places at once. Nothing was lost. See