Compare commits

..
Author SHA1 Message Date
nvrl 90e9c0de26 Merge branch 'feat/sync-local-dirty' into feat/sync-root-reducer
# Conflicts:
#	crates/pdfs-fuse/src/mount.rs
#	crates/pdfs-sync/src/mirror/host.rs
2026-11-27 19:27:09 +01:00
nvrl 61e0eefe3a Merge branch 'feat/sync-enforce-evidence' into feat/sync-local-dirty
# Conflicts:
#	crates/pdfs-fuse/src/mount.rs
#	crates/pdfs-sync/src/mirror/host.rs
2026-11-27 19:26:48 +01:00
nvrl 7862fc9195 Merge branch 'feat/sync-delete-window' into feat/sync-enforce-evidence 2026-11-27 19:26:18 +01:00
nvrl 413be9d961 feat(sync): run a root reducer per mirror folder alongside the engine
One pure state machine per mirror folder says how far the engine can
trust what it has seen: discovering, following, auditing after a doubt
(a watcher error, an overflowed queue, a gap in Drive's event stream, a
restart or a suspension), suspended, draining for on-demand, or handed
off. The passes, the watcher, the event stream and pause feed it inputs;
step() takes no time and does no I/O, so an input sequence replays
exactly.

Nothing acts on the state yet. The engine logs each transition as
'sync: root state', so it can be compared with what the engine did
before a pass relies on it.
2026-11-27 19:20:35 +01:00
nvrl 0fd8dda0d5 feat(sync): keep a local dirty set from the watcher, checked against the walk
The filesystem watcher now marks each path an event names, per mirror
folder (LocalDirty, in memory). A pass claims the marks before it plans
and retires them once it applied everything it found; marks made while
it ran stay for the next pass. A claim is trusted when the folder's
watch was live since the last pass claimed: a watcher error, an
overflowed queue or a restart breaks that.

For now the set is only checked. Each pass still walks the whole
folder, and counts in its trace the claimed marks, whether the claim
was trusted, and the changes it found on disk that a trusted claim did
not cover. Once that stays at zero, a trusted claim can stand in for
the local walk.
2026-11-27 19:14:35 +01:00
nvrl 4f542ae4d6 feat(sync): do not make a deletion the evidence does not back
The shadow check from the typed absence change counted deletions not
backed by proof of absence and acted on nothing. A deletion it flags is
now left out of the pass: it is logged, counted in the trace and failed
as a step, and the baseline row stays, so the next pass plans it again.
A regression in the filters then keeps a file on both sides instead of
deleting it, and a simulation that expects the deletion sees the file
still there.
2026-11-27 19:03:57 +01:00
15 changed files with 916 additions and 42 deletions

No files matched your search

+7 -1
View File
@@ -3,6 +3,7 @@
use super::*;
use crate::shutdown::Shutdown;
use pdfs_core::error::session_revoked;
use pdfs_sync::root::{Doubt, RootInput};
/// Drop `uid` from one mount's tree and tell that mount's kernel session the
/// entry is gone. Shared by the trash and delete paths, which differ only in
@@ -148,7 +149,12 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
core.db.sync_remote_changed(&node_uid.to_string(), None)
}
// What changed went by unseen: every pass walks Drive whole again.
DriveEvent::ContinuityLost { .. } => core.db.sync_walks_clear_all().map(|()| Vec::new()),
DriveEvent::ContinuityLost { .. } => {
core.sync
.roots
.input_all(RootInput::Doubted(Doubt::EventGap));
core.db.sync_walks_clear_all().map(|()| Vec::new())
}
_ => Ok(Vec::new()),
};
match marked {
+2
View File
@@ -520,6 +520,8 @@ pub(crate) fn mount_with(
unscanned: Arc::default(),
abandon: Arc::default(),
events_read_at: Arc::new(AtomicI64::new(0)),
local_dirty: Arc::default(),
roots: Arc::default(),
admission: Arc::new(pdfs_sched::Classes::new(|class| match class {
pdfs_sched::Class::Mirror => sync::SYNC_CONCURRENCY,
pdfs_sched::Class::Listing => super::listing::COLD_LISTINGS,
+52
View File
@@ -1963,6 +1963,58 @@ mod tests {
.map_or(0, |c| c.value)
}
/// What the watcher reports covers every change a pass then finds on
/// disk: an edit, a new folder with a file in it, a deletion, and a folder
/// moved in from outside with a folder and a file in it (`local_dirty`).
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn the_local_dirty_set_covers_what_the_walk_finds() {
let drive = FakeDrive::new();
let dir = scratch("local-dirty");
let (daemon, folder, _client) =
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
// From the pass after this one, the watch has been live since the
// last claim.
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
let settled = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
assert_eq!(counted(&settled, "local dirty untrusted"), 0, "{settled}");
let local = dir.join("local");
let outside = dir.join("outside");
std::fs::create_dir_all(outside.join("deep")).unwrap();
std::fs::write(outside.join("deep").join("x.txt"), b"moved in").unwrap();
std::fs::write(local.join("a.txt"), b"edited").unwrap();
std::fs::create_dir(local.join("new")).unwrap();
std::fs::write(local.join("new").join("c.txt"), b"three").unwrap();
std::fs::remove_file(local.join("b.txt")).unwrap();
std::fs::rename(&outside, local.join("moved")).unwrap();
assert!(wait_until(Duration::from_secs(60), || {
drive.lookup("mirrored/new/c.txt").is_some()
&& drive.lookup("mirrored/moved/deep/x.txt").is_some()
&& drive.lookup("mirrored/b.txt").is_none()
}));
let after = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
assert_eq!(counted(&after, "local dirty untrusted"), 0, "{after}");
let logged = take_logged();
let missed: Vec<&String> = logged
.iter()
.filter(|line| line.contains("local dirty set missed"))
.collect();
assert!(missed.is_empty(), "{missed:?}");
// The first pass took the folder from discovery to following, and
// nothing since put it in doubt (`root`).
let roots: Vec<&String> = logged
.iter()
.filter(|line| line.contains("sync: root state"))
.collect();
assert!(
roots.len() == 1 && roots[0].contains("to=following"),
"{roots:?}"
);
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_pass_reports_where_its_time_went() {
+3 -3
View File
@@ -11,9 +11,9 @@
//! Only [`Presence::Absent`] may lead to a deletion. A pass classifies a path
//! only when both sides are known ([`Evidence::classifiable`]), and every
//! deletion it plans is checked against the evidence again
//! ([`Evidence::unproven_deletion`]). That check acts on nothing yet: it
//! counts and logs a deletion the evidence does not support, so a regression
//! in the filters shows up in the pass trace before it can cost data.
//! ([`Evidence::unproven_deletion`]). A deletion the evidence does not
//! support is not made: it is logged, counted in the pass trace and failed,
//! so a regression in the filters keeps files instead of costing them.
use std::collections::HashMap;
+2
View File
@@ -21,10 +21,12 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{Node, NodeKind};
pub mod evidence;
pub mod local_dirty;
pub mod mirror;
pub mod model;
pub mod naming;
pub mod planner;
pub mod root;
pub mod store;
pub mod trace;
+285
View File
@@ -0,0 +1,285 @@
//! The local dirty set: where a mirror folder changed on disk since a pass
//! last looked, as the filesystem watcher reports it (`docs/SYNC_ENGINE.md`).
//!
//! The watcher marks each path an event names. A pass claims every mark made
//! so far and, once it has applied what it found, retires them. Marks made
//! while it ran are newer than its claim and stay for the next pass.
//!
//! A claim is only as good as the watch behind it. It is *trusted* when the
//! folder's watch has been live since before the last pass claimed: then
//! every change since that pass was reported. A watch that failed, a watcher
//! error, an overflowed queue or a restart breaks that, and the next pass has
//! nothing to trust until a pass claims again with the watch live throughout.
//!
//! For now the set is checked, not used: a pass still walks the whole folder,
//! and counts the changes it finds that a trusted claim did not cover. Once
//! those stay at zero, a trusted claim can stand in for the walk.
use std::collections::{HashMap, HashSet};
use parking_lot::Mutex;
/// The dirty marks of every mirror folder, by folder id.
#[derive(Default)]
pub struct LocalDirty {
inner: Mutex<Dirty>,
}
#[derive(Default)]
struct Dirty {
/// The newest generation, across every folder: of a mark, or of a watch
/// coming up.
generation: u64,
folders: HashMap<i64, Marks>,
}
impl Dirty {
/// The next generation. A watch that comes up, or comes back after an
/// overflow, takes one of its own, so it is always later than the last
/// claim, even when no mark was made in between.
fn tick(&mut self) -> u64 {
self.generation += 1;
self.generation
}
}
#[derive(Default)]
struct Marks {
/// Folders whose direct children changed, with the generation of the
/// newest mark on each.
shallow: HashMap<String, u64>,
/// Paths that changed in full, with whatever is below them: a file
/// written, or a folder that appeared with its contents.
deep: HashMap<String, u64>,
/// The generation from which the watch has reported every change, or
/// `None` while the folder is not watched.
live_since: Option<u64>,
/// The generation the last pass claimed through.
claimed: Option<u64>,
}
/// The marks a pass claimed: what the watcher reported up to `through`.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Claim {
pub through: u64,
/// Whether the watch was live since before the last claim, so the marks
/// cover every change since.
pub trusted: bool,
shallow: HashSet<String>,
deep: HashSet<String>,
}
impl Claim {
/// Whether a change to `rel` was reported: its folder's children
/// changed, or it or a folder above it changed in full.
pub fn covers(&self, rel: &str) -> bool {
if self.shallow.contains(parent(rel)) {
return true;
}
let mut at = rel;
loop {
if self.deep.contains(at) {
return true;
}
if at.is_empty() {
return false;
}
at = parent(at);
}
}
/// How many marks the claim holds.
pub fn len(&self) -> usize {
self.shallow.len() + self.deep.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl LocalDirty {
/// The watch on `folder` is in place: every change from now on is
/// reported.
pub fn watched(&self, folder: i64) {
let mut d = self.inner.lock();
let now = d.tick();
let marks = d.folders.entry(folder).or_default();
if marks.live_since.is_none() {
marks.live_since = Some(now);
}
}
/// The watch on `folder` is gone, or never came up.
pub fn unwatched(&self, folder: i64) {
if let Some(marks) = self.inner.lock().folders.get_mut(&folder) {
marks.live_since = None;
}
}
/// The watcher lost events it cannot name: an error, or an overflowed
/// queue. No folder's marks can be trusted until it is watched again.
pub fn lost(&self) {
for marks in self.inner.lock().folders.values_mut() {
marks.live_since = None;
}
}
/// The watcher's queue overflowed: the changes in it are lost, but the
/// watches stand, so every folder still watched reports changes again
/// from now on.
pub fn overflowed(&self) {
let mut d = self.inner.lock();
let now = d.tick();
for marks in d.folders.values_mut() {
if marks.live_since.is_some() {
marks.live_since = Some(now);
}
}
}
/// Note a change the watcher reported at `rel` in `folder`.
pub fn mark(&self, folder: i64, rel: &str) {
let mut d = self.inner.lock();
let generation = d.tick();
let marks = d.folders.entry(folder).or_default();
marks.deep.insert(rel.to_string(), generation);
marks.shallow.insert(parent(rel).to_string(), generation);
}
/// Claim every mark of `folder` made so far, for a pass about to look.
pub fn claim(&self, folder: i64) -> Claim {
let mut d = self.inner.lock();
let through = d.generation;
let marks = d.folders.entry(folder).or_default();
Claim {
through,
trusted: matches!(
(marks.live_since, marks.claimed),
(Some(live), Some(claimed)) if live <= claimed
),
shallow: marks.shallow.keys().cloned().collect(),
deep: marks.deep.keys().cloned().collect(),
}
}
/// A pass that claimed `claim` has looked. With `applied`, it applied
/// everything it found, and the marks it claimed are retired; without,
/// they stay for the next pass to claim again. Either way the next claim
/// is measured from this one.
pub fn looked(&self, folder: i64, claim: &Claim, applied: bool) {
let mut d = self.inner.lock();
let marks = d.folders.entry(folder).or_default();
if applied {
marks.shallow.retain(|_, g| *g > claim.through);
marks.deep.retain(|_, g| *g > claim.through);
}
marks.claimed = Some(claim.through);
}
/// Forget a folder that is no longer synced.
pub fn forget(&self, folder: i64) {
self.inner.lock().folders.remove(&folder);
}
}
/// The folder `rel` is in; the root's is the root.
fn parent(rel: &str) -> &str {
rel.rfind('/').map_or("", |i| &rel[..i])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_claim_covers_a_change_and_its_siblings_folder_but_not_cousins() {
let dirty = LocalDirty::default();
dirty.mark(1, "docs/a.txt");
let claim = dirty.claim(1);
assert!(claim.covers("docs/a.txt"));
// A file made or deleted next to it shows in the same folder.
assert!(claim.covers("docs/b.txt"));
assert!(!claim.covers("other/c.txt"));
assert!(!claim.covers("docs/sub/d.txt"));
assert!(!claim.covers("top.txt"));
}
#[test]
fn a_folder_moved_in_covers_everything_below_it() {
let dirty = LocalDirty::default();
dirty.mark(1, "photos/2024");
let claim = dirty.claim(1);
assert!(claim.covers("photos/2024/jan/1.jpg"));
assert!(claim.covers("photos/other"));
assert!(!claim.covers("music/x.mp3"));
}
#[test]
fn a_claim_is_trusted_only_with_the_watch_live_since_the_last_one() {
let dirty = LocalDirty::default();
dirty.watched(1);
// The first pass after the watch came up has nothing to measure from.
let first = dirty.claim(1);
assert!(!first.trusted);
dirty.looked(1, &first, true);
assert!(dirty.claim(1).trusted);
// Events lost: the next claim is not trusted, nor the one after the
// watch comes back, until a pass has claimed with it live.
dirty.lost();
let lost = dirty.claim(1);
assert!(!lost.trusted);
dirty.looked(1, &lost, true);
dirty.watched(1);
dirty.mark(1, "a.txt");
let back = dirty.claim(1);
assert!(!back.trusted, "watched again after the last claim");
dirty.looked(1, &back, true);
assert!(dirty.claim(1).trusted);
}
#[test]
fn marks_made_during_a_pass_stay_for_the_next_one() {
let dirty = LocalDirty::default();
dirty.mark(1, "a.txt");
let claim = dirty.claim(1);
dirty.mark(1, "b/c.txt");
dirty.looked(1, &claim, true);
let next = dirty.claim(1);
assert!(!next.covers("a.txt"));
assert!(next.covers("b/c.txt"));
}
#[test]
fn a_pass_that_did_not_apply_everything_keeps_its_marks() {
let dirty = LocalDirty::default();
dirty.mark(1, "a.txt");
let claim = dirty.claim(1);
dirty.looked(1, &claim, false);
assert!(dirty.claim(1).covers("a.txt"));
}
#[test]
fn an_overflow_breaks_trust_until_a_pass_claims_again() {
let dirty = LocalDirty::default();
dirty.watched(1);
let first = dirty.claim(1);
dirty.looked(1, &first, true);
dirty.mark(1, "a.txt");
dirty.overflowed();
let lost = dirty.claim(1);
assert!(!lost.trusted);
dirty.looked(1, &lost, true);
assert!(dirty.claim(1).trusted);
}
#[test]
fn folders_keep_their_own_marks() {
let dirty = LocalDirty::default();
dirty.mark(1, "a.txt");
assert!(dirty.claim(2).is_empty());
dirty.forget(1);
assert!(dirty.claim(1).is_empty());
}
}
+193 -23
View File
@@ -39,7 +39,9 @@ use sha1::{Digest as _, Sha1};
use tracing::{debug, info, warn};
use crate::evidence::{Evidence, RemoteEvidence, Side};
use crate::local_dirty::Claim;
use crate::planner::HasKind;
use crate::root::{RootInput, Suspension};
use pdfs_core::batch;
use pdfs_core::control::{ActivityKind, TransferDirection};
use pdfs_core::syncignore::IgnoreRules;
@@ -100,15 +102,21 @@ impl Syncer {
pub fn reconcile_folder(&self, folder: &StoredSyncFolder) {
// A paused folder skips the settle too: a queued switch to on-demand
// evicts the local tree, which is only safe after a pass uploaded it.
self.roots.begin(folder.id, folder.last_sync != 0);
if self.sync_folder_paused(folder.id) {
debug!(id = folder.id, "sync: folder paused, skipping reconcile");
self.roots
.input(folder.id, RootInput::Suspended(Suspension::Paused));
return;
}
self.roots.input(folder.id, RootInput::Resumed);
// `ondemand` folders are live FUSE mounts, not mirrored, so there is nothing
// to reconcile — but one may still carry a queued switch back to `mirror`,
// so the settle below is not skipped with it.
if folder.mode == "mirror" {
self.reconcile_pass(folder);
} else {
self.roots.input(folder.id, RootInput::HandedOff);
}
self.settle_pending_mode(folder.id);
}
@@ -149,8 +157,18 @@ impl Syncer {
let _ = self
.store
.sync_folder_set_state(folder.id, "error", now_secs());
self.roots
.input(folder.id, RootInput::Suspended(Suspension::RootMissing));
return;
}
self.roots.input(
folder.id,
if push_only {
RootInput::HandoffQueued
} else {
RootInput::Mirrored
},
);
let _ = self
.store
@@ -211,6 +229,9 @@ impl Syncer {
let progress = self.progress.lock().get(&folder.id).cloned();
self.progress_end(folder.id);
self.log_trace(folder, &result, started.elapsed());
if result.is_ok() && !push_only {
self.roots.input(folder.id, RootInput::Covered);
}
match result {
Ok(outcome) => {
// A folder only reaches `idle` when every path applied cleanly —
@@ -354,25 +375,33 @@ impl Syncer {
}
}
/// Shadow check of a deletion the pass is about to make: count and log it
/// when the evidence does not prove the path gone on the side the
/// deletion is based on. Acts on nothing; the filters before the plan are
/// what keep such a path out of it, and this says when they did not.
fn check_deletion<L: HasKind, R: HasKind>(
/// Whether the pass must not make a deletion it planned: the evidence does
/// not prove the path gone on the side the deletion is based on. Such a
/// deletion is logged, counted in the trace and as a failed step, and left
/// out; its baseline row stays, so the next pass plans it again.
///
/// The filters before the plan keep such a path out of it, so this
/// should never fire. When it does, a file stays on both sides rather than
/// going on the strength of a walk that never saw it.
fn refuses_deletion<L: HasKind, R: HasKind>(
&self,
evidence: &Evidence<'_, L, R>,
rel: &str,
side: Side,
) {
if let Some(basis) = evidence.unproven_deletion(rel, side) {
warn!(
rel,
?side,
?basis,
"sync: a planned deletion is not backed by proof of absence"
);
self.trace_count(Count::UnprovenDeletions, 1);
}
outcome: &mut Outcome,
) -> bool {
let Some(basis) = evidence.unproven_deletion(rel, side) else {
return false;
};
warn!(
rel,
?side,
?basis,
"sync: not deleting a path whose absence is not proven"
);
self.trace_count(Count::UnprovenDeletions, 1);
outcome.failed(&format!("{rel}: not deleted, its absence is not proven"));
true
}
/// Add `took` to a stage of the running pass's trace.
@@ -497,6 +526,15 @@ impl Syncer {
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)?;
// What the watcher reported since the last pass, checked against what
// the walk found (`local_dirty`).
let claim = self.local_dirty.claim(folder_id);
self.check_local_dirty(
folder_id,
&claim,
&tracked_baseline(&baseline, rules, &unscanned),
&local,
);
let mut remote: HashMap<String, RemoteItem> = HashMap::new();
let mut remote_dirs: HashMap<String, NodeUid> = HashMap::new();
@@ -622,11 +660,14 @@ impl Syncer {
}
(true, false) => {
// In baseline, gone remotely → the remote side deleted it.
self.check_deletion(
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Local,
);
&mut outcome,
) {
continue;
}
delete_local_dirs.push(rel.clone());
}
(false, true) if !in_base => {
@@ -641,11 +682,14 @@ impl Syncer {
}
(false, true) => {
// In baseline, gone locally → the local side deleted it.
self.check_deletion(
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Remote,
);
&mut outcome,
) {
continue;
}
delete_remote_dirs.push((rel.clone(), remote[rel].uid.clone()));
}
(false, false) => {
@@ -736,11 +780,14 @@ impl Syncer {
}
},
FilePlan::DeleteLocal => {
self.check_deletion(
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Local,
);
&mut outcome,
) {
continue;
}
let path = local_root.join(rel_to_path(rel));
// The plan comes from a scan taken before the remote walk,
// which can take minutes. An edit saved since then is not
@@ -767,11 +814,14 @@ impl Syncer {
outcome.deleted += 1;
}
FilePlan::DeleteRemote => {
self.check_deletion(
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Remote,
);
&mut outcome,
) {
continue;
}
let remote = r.expect("remote deletion requires a remote file");
let step = Instant::now();
let trashed = self
@@ -908,10 +958,50 @@ impl Syncer {
}
self.trace_phase(Phase::Cleanup, cleanup.elapsed());
self.settle_deletions(folder_id, window, outcome.deleted);
// A change the pass could not apply stays dirty for the next one.
self.local_dirty.looked(
folder_id,
&claim,
outcome.errors == 0 && outcome.deferred == 0,
);
Ok(outcome)
}
/// Count the claimed marks of the local dirty set, and, when the claim is
/// trusted, the local changes the walk found that it did not cover. Acts
/// on nothing: the walk is still what the pass plans from.
fn check_local_dirty(
&self,
folder_id: i64,
claim: &Claim,
tracked: &HashMap<String, &StoredSyncEntry>,
local: &HashMap<String, LocalItem>,
) {
self.trace_count(Count::LocalDirty, claim.len());
if !claim.trusted {
self.trace_count(Count::LocalUntrusted, 1);
return;
}
let missed = missed_local(claim, tracked, local);
if missed.is_empty() {
return;
}
for rel in &missed {
debug!(
id = folder_id,
rel, "sync: a local change the watcher did not report"
);
}
info!(
id = folder_id,
missed = missed.len(),
first = %missed[0],
"sync: the local dirty set missed changes the walk found"
);
self.trace_count(Count::MissedLocal, missed.len());
}
/// Open or continue the folder's deletion window for a pass that plans
/// `planned` deletions, and refuse the pass when they would make the
/// window a wipe ([`guard_delete_window`]). `tracked` is how many paths
@@ -964,6 +1054,33 @@ impl Syncer {
}
}
/// The local changes the walk found since the baseline that `claim` does not
/// cover: paths new on disk, files whose size or mtime moved, and tracked
/// paths gone. Sorted, for a stable log.
fn missed_local(
claim: &Claim,
tracked: &HashMap<String, &StoredSyncEntry>,
local: &HashMap<String, LocalItem>,
) -> Vec<String> {
let changed = local.iter().filter_map(|(rel, item)| {
let moved = match tracked.get(rel) {
None => true,
Some(base) => {
!item.is_dir && (base.local_mtime != item.mtime || base.local_size != item.size)
}
};
moved.then_some(rel)
});
let gone = tracked.keys().filter(|rel| !local.contains_key(*rel));
let mut missed: Vec<String> = changed
.chain(gone)
.filter(|rel| !claim.covers(rel))
.cloned()
.collect();
missed.sort();
missed
}
/// A [`Read`] that hashes what an upload reads through it, so the digest Drive
/// reports afterwards can be compared with what was sent.
/// The evidence of a mirror pass, built where it is asked so it borrows the
@@ -1791,6 +1908,59 @@ mod tests {
)])
}
/// A walk's changes that a claim of the local dirty set did not cover:
/// one next to a reported change is covered, the rest are missed.
#[test]
fn missed_local_lists_the_changes_a_claim_does_not_cover() {
use crate::local_dirty::LocalDirty;
let row = |rel: &str, mtime: i64| StoredSyncEntry {
rel_path: rel.to_string(),
remote_uid: Some("v~l".into()),
local_mtime: mtime,
local_size: 1,
local_mtime_ns: None,
remote_rev: None,
remote_hash: None,
remote_revision_id: None,
};
let rows: HashMap<String, StoredSyncEntry> = [
("docs", 0),
("docs/a.txt", 1),
("same.txt", 1),
("top.txt", 1),
("old/x.txt", 1),
]
.into_iter()
.map(|(rel, mtime)| (rel.to_string(), row(rel, mtime)))
.collect();
let tracked: HashMap<String, &StoredSyncEntry> =
rows.iter().map(|(k, v)| (k.clone(), v)).collect();
let item = |is_dir: bool, mtime: i64| LocalItem {
mtime_ns: None,
is_dir,
mtime,
size: 1,
open_for_write: false,
};
let local: HashMap<String, LocalItem> = [
("docs", item(true, 9)),
("docs/a.txt", item(false, 2)),
("docs/new.txt", item(false, 1)),
("same.txt", item(false, 1)),
("top.txt", item(false, 2)),
]
.into_iter()
.map(|(rel, item)| (rel.to_string(), item))
.collect();
let dirty = LocalDirty::default();
dirty.mark(1, "docs/a.txt");
let claim = dirty.claim(1);
assert_eq!(
missed_local(&claim, &tracked, &local),
vec!["old/x.txt".to_string(), "top.txt".to_string()]
);
}
#[test]
fn an_unchanged_mtime_reuses_the_recorded_size() {
// The whole point: this file's node key never gets unlocked.
+47 -2
View File
@@ -10,6 +10,8 @@ use std::collections::BTreeMap;
use super::trace::PassTrace;
use super::*;
use crate::local_dirty::LocalDirty;
use crate::root::{Doubt, RootInput};
/// How long the watcher must go quiet before a burst counts as finished.
///
@@ -246,21 +248,33 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
let tx_events = core.tx.clone();
let watched_events = watched.clone();
let dirty = core.local_dirty.clone();
let roots = core.roots.clone();
let handler = move |res: notify::Result<notify::Event>| {
let event = match res {
Ok(event) => event,
// Running out of inotify watches for a new subfolder, say: that
// subfolder's changes are then found by the poll only (B262).
// Nothing says which, so no folder's dirty set is whole now.
Err(e) => {
warn!(error = %e, "sync: filesystem watcher error");
dirty.lost();
roots.input_all(RootInput::Doubted(Doubt::WatchLost));
return;
}
};
if event.need_rescan() {
dirty.overflowed();
roots.input_all(RootInput::Doubted(Doubt::Overflow));
}
// Ignore pure metadata/access noise; content changes are what matter.
if matches!(event.kind, notify::EventKind::Access(_)) {
return;
}
let msg = event_target(&watched_events.lock(), &event.paths);
let watched = watched_events.lock();
mark_dirty(&dirty, &watched, &event.paths);
let msg = event_target(&watched, &event.paths);
drop(watched);
let _ = tx_events.send(msg);
};
// The local walk skips symlinks, so following them here would only watch
@@ -513,6 +527,28 @@ pub(super) fn event_target(watched: &[(PathBuf, i64)], paths: &[PathBuf]) -> Syn
}
}
/// Mark each of `paths` in the local dirty set of the folder it is in.
pub(super) fn mark_dirty(dirty: &LocalDirty, watched: &[(PathBuf, i64)], paths: &[PathBuf]) {
for path in paths {
let Some((root, id)) = watched
.iter()
.filter(|(root, _)| path.starts_with(root))
.max_by_key(|(root, _)| root.components().count())
else {
continue;
};
let Ok(rel) = path.strip_prefix(root) else {
continue;
};
// The walk leaves out a name that is not UTF-8, so there is nothing
// to mark for one.
let parts: Option<Vec<&str>> = rel.components().map(|c| c.as_os_str().to_str()).collect();
if let Some(parts) = parts {
dirty.mark(*id, &parts.join("/"));
}
}
}
/// Bring the filesystem watches in line with the current mirror-folder set:
/// watch newly-added folders, drop removed ones. Returns whether a folder is
/// left unwatched because its watch failed.
@@ -537,9 +573,14 @@ fn rewatch(
}
};
let mut have = watched.lock().clone();
let before = have.clone();
// Drop watches no longer wanted.
for path in keep_wanted(&mut have, &want) {
let _ = watcher.unwatch(&path);
if let Some((_, id)) = before.iter().find(|(p, _)| *p == path) {
core.local_dirty.forget(*id);
core.roots.forget(*id);
}
}
// Add newly wanted watches.
let mut failed = false;
@@ -548,8 +589,12 @@ fn rewatch(
continue;
}
match watcher.watch(path, RecursiveMode::Recursive) {
Ok(()) => have.push((path.clone(), *id)),
Ok(()) => {
have.push((path.clone(), *id));
core.local_dirty.watched(*id);
}
Err(e) => {
core.local_dirty.unwatched(*id);
// A recursive watch that fails partway keeps the watches it had
// added. Their events would match no folder and run a pass over
// every one, and they hold watches the next folder needs (B262).
+5
View File
@@ -86,6 +86,11 @@ pub struct SyncParts {
/// first read. A pass trusts the feed's dirty folders only while it is
/// being read.
pub events_read_at: Arc<AtomicI64>,
/// Where each mirror folder changed on disk since a pass last looked,
/// as the filesystem watcher reports it.
pub local_dirty: Arc<crate::local_dirty::LocalDirty>,
/// What each mirror folder's sync knows about its coverage (`root`).
pub roots: Arc<crate::root::Roots>,
/// When each step of a pass may start: its uploads, downloads and folder
/// creations.
pub admission: Arc<dyn pdfs_sched::Admission>,
+4 -3
View File
@@ -314,9 +314,10 @@ impl Syncer {
unscanned: &unscanned,
remote: None,
};
for rel in &deletions {
self.check_deletion(&evidence, rel, Side::Remote);
}
let deletions: Vec<String> = deletions
.into_iter()
.filter(|rel| !self.refuses_deletion(&evidence, rel, Side::Remote, &mut outcome))
.collect();
let mut trashed: Vec<String> = Vec::new();
for rel in &deletions {
if trashed
+256
View File
@@ -0,0 +1,256 @@
//! The root reducer: what a mirror folder's sync knows about its coverage,
//! as one state machine per folder (`docs/SYNC_ENGINE.md`).
//!
//! [`step`] is pure: it takes the state and one input and returns the next
//! state. Time, the watcher, the event stream and the passes stay outside, as
//! inputs, so a sequence of inputs replays exactly.
//!
//! The states say how far the engine can trust what it has seen:
//!
//! - **Discovering**: no pass over the folder has finished yet.
//! - **Following**: a pass covered the whole folder, and nothing since says a
//! change could have gone unreported.
//! - **Auditing**: something did (a lost watch, an overflowed queue, a gap in
//! Drive's event stream, a restart, a suspension). Only a pass over the
//! whole folder brings it back to Following.
//! - **Suspended**: the folder cannot be synced for now: its local root is
//! missing, or sync is paused.
//! - **Draining**: a switch to on-demand is queued; passes only push.
//! - **HandedOff**: the folder is on-demand.
//!
//! For now the reducer is run alongside the engine and acted on by nothing:
//! every pass still covers the whole folder. Its transitions are logged, so
//! they can be compared with what the engine did before anything relies on
//! them.
use std::collections::HashMap;
use std::fmt;
use parking_lot::Mutex;
use tracing::info;
/// Why a folder's coverage is in doubt.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Doubt {
/// The daemon started: nothing was watched while it was down.
Restart,
/// The filesystem watcher reported an error.
WatchLost,
/// The watcher's event queue overflowed.
Overflow,
/// Drive's event stream lost changes.
EventGap,
/// The folder was suspended, and nothing was followed meanwhile.
Suspension,
}
/// Why a folder is not synced for now.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Suspension {
RootMissing,
Paused,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RootState {
Discovering,
Following,
Auditing(Doubt),
Suspended(Suspension),
Draining,
HandedOff,
}
/// Something that happened to a folder, as the reducer takes it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RootInput {
/// A pass over the whole folder finished.
Covered,
/// A change may have gone unreported.
Doubted(Doubt),
/// The folder cannot be synced for now.
Suspended(Suspension),
/// Sync is no longer paused. A missing root is only found again by a
/// pass that covers it.
Resumed,
/// A switch to on-demand is queued.
HandoffQueued,
/// The folder is on-demand.
HandedOff,
/// The folder is a mirror again after being on-demand.
Mirrored,
}
/// The state after `input`.
pub fn step(state: RootState, input: RootInput) -> RootState {
use RootState as S;
match (state, input) {
// An on-demand folder is not synced: only going back to a mirror
// changes it, and that is a first sync over again.
(S::HandedOff, RootInput::Mirrored) => S::Discovering,
(S::HandedOff, _) => S::HandedOff,
(S::Draining, RootInput::HandedOff) => S::HandedOff,
// A switch called off: a mirror again, which followed nothing while
// it pushed.
(S::Draining, RootInput::Mirrored) => S::Auditing(Doubt::Suspension),
(S::Draining, _) => S::Draining,
(_, RootInput::HandoffQueued) => S::Draining,
(_, RootInput::HandedOff) => S::HandedOff,
(S::Suspended(_), RootInput::Covered) => S::Following,
(S::Suspended(Suspension::Paused), RootInput::Resumed) => S::Auditing(Doubt::Suspension),
(S::Suspended(_), RootInput::Suspended(why)) => S::Suspended(why),
(S::Suspended(why), _) => S::Suspended(why),
(_, RootInput::Suspended(why)) => S::Suspended(why),
(_, RootInput::Covered) => S::Following,
(S::Following, RootInput::Doubted(why)) => S::Auditing(why),
// A first sync and an audit cover everything anyway; the first doubt
// is the one to report.
(state, _) => state,
}
}
impl fmt::Display for RootState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RootState::Discovering => f.write_str("discovering"),
RootState::Following => f.write_str("following"),
RootState::Auditing(why) => write!(f, "auditing ({why:?})"),
RootState::Suspended(why) => write!(f, "suspended ({why:?})"),
RootState::Draining => f.write_str("draining"),
RootState::HandedOff => f.write_str("handed off"),
}
}
}
/// The root state of every mirror folder the engine has seen, by id.
#[derive(Default)]
pub struct Roots {
states: Mutex<HashMap<i64, RootState>>,
}
impl Roots {
/// Start following `folder`, unless it already is: from discovery for a
/// folder never synced, and otherwise from an audit, since nothing
/// watched it while the daemon was down.
pub fn begin(&self, folder: i64, synced_before: bool) {
self.states
.lock()
.entry(folder)
.or_insert(if synced_before {
RootState::Auditing(Doubt::Restart)
} else {
RootState::Discovering
});
}
/// Feed `input` to `folder`'s reducer, and log the transition it makes.
/// A folder not begun yet is left alone: its first pass begins it.
pub fn input(&self, folder: i64, input: RootInput) {
let mut states = self.states.lock();
let Some(state) = states.get_mut(&folder) else {
return;
};
let next = step(*state, input);
if next != *state {
info!(id = folder, from = %state, to = %next, ?input, "sync: root state");
*state = next;
}
}
/// Feed `input` to every folder's reducer.
pub fn input_all(&self, input: RootInput) {
let folders: Vec<i64> = self.states.lock().keys().copied().collect();
for folder in folders {
self.input(folder, input);
}
}
/// The state of `folder`, if the engine has begun it.
pub fn state(&self, folder: i64) -> Option<RootState> {
self.states.lock().get(&folder).copied()
}
/// Forget a folder that is no longer synced.
pub fn forget(&self, folder: i64) {
self.states.lock().remove(&folder);
}
}
#[cfg(test)]
mod tests {
use super::*;
use RootInput as I;
use RootState as S;
fn run(from: RootState, inputs: &[RootInput]) -> RootState {
inputs.iter().fold(from, |state, input| step(state, *input))
}
#[test]
fn a_first_sync_follows_once_a_pass_covers_the_folder() {
assert_eq!(run(S::Discovering, &[I::Covered]), S::Following);
// A doubt during discovery changes nothing: the pass covers it all.
assert_eq!(
run(S::Discovering, &[I::Doubted(Doubt::Overflow)]),
S::Discovering
);
}
#[test]
fn a_doubt_takes_a_followed_folder_to_an_audit_until_a_pass_covers_it() {
let audit = run(
S::Following,
&[I::Doubted(Doubt::WatchLost), I::Doubted(Doubt::EventGap)],
);
assert_eq!(
audit,
S::Auditing(Doubt::WatchLost),
"the first doubt stays"
);
assert_eq!(step(audit, I::Covered), S::Following);
}
#[test]
fn a_suspension_ends_in_an_audit_or_a_pass() {
let paused = run(S::Following, &[I::Suspended(Suspension::Paused)]);
assert_eq!(paused, S::Suspended(Suspension::Paused));
assert_eq!(step(paused, I::Doubted(Doubt::Overflow)), paused);
assert_eq!(step(paused, I::Resumed), S::Auditing(Doubt::Suspension));
let missing = run(S::Following, &[I::Suspended(Suspension::RootMissing)]);
assert_eq!(step(missing, I::Resumed), missing);
assert_eq!(step(missing, I::Covered), S::Following);
}
#[test]
fn a_handoff_drains_then_stays_until_the_folder_is_a_mirror_again() {
let draining = step(S::Following, I::HandoffQueued);
assert_eq!(draining, S::Draining);
assert_eq!(step(draining, I::Covered), S::Draining);
let off = step(draining, I::HandedOff);
assert_eq!(off, S::HandedOff);
assert_eq!(step(off, I::Covered), S::HandedOff);
assert_eq!(step(off, I::Mirrored), S::Discovering);
assert_eq!(
step(draining, I::Mirrored),
S::Auditing(Doubt::Suspension),
"a switch called off"
);
}
#[test]
fn roots_begin_once_and_feed_every_folder() {
let roots = Roots::default();
roots.input(1, I::Covered);
assert_eq!(roots.state(1), None, "not begun");
roots.begin(1, false);
roots.begin(2, true);
assert_eq!(roots.state(2), Some(S::Auditing(Doubt::Restart)));
roots.input_all(I::Covered);
roots.begin(1, false);
assert_eq!(roots.state(1), Some(S::Following), "begun only once");
roots.input_all(I::Doubted(Doubt::EventGap));
assert_eq!(roots.state(2), Some(S::Auditing(Doubt::EventGap)));
roots.forget(2);
assert_eq!(roots.state(2), None);
}
}
+18 -4
View File
@@ -133,14 +133,22 @@ pub enum Count {
Reused,
/// Folders on Drive marked as changed since the last pass listed them.
Dirty,
/// Deletions the pass planned that the evidence does not back: the path
/// was not proven gone on the side the deletion is based on. Should stay
/// zero; see `evidence`.
/// Deletions the pass planned that the evidence does not back, and so
/// did not make: the path was not proven gone on the side the deletion is
/// based on. Should stay zero; see `evidence`.
UnprovenDeletions,
/// Marks of the local dirty set the pass claimed.
LocalDirty,
/// One when the pass's claim of the local dirty set was not trusted: the
/// watch was not live throughout since the last pass claimed.
LocalUntrusted,
/// Local changes the pass found that a trusted claim of the local dirty
/// set did not cover. Should stay zero; see `local_dirty`.
MissedLocal,
}
impl Count {
const ALL: [Count; 10] = [
const ALL: [Count; 13] = [
Count::LocalEntries,
Count::RemoteFolders,
Count::Nodes,
@@ -151,6 +159,9 @@ impl Count {
Count::Reused,
Count::Dirty,
Count::UnprovenDeletions,
Count::LocalDirty,
Count::LocalUntrusted,
Count::MissedLocal,
];
fn name(self) -> &'static str {
@@ -165,6 +176,9 @@ impl Count {
Count::Reused => "reused",
Count::Dirty => "dirty folders",
Count::UnprovenDeletions => "unproven deletions",
Count::LocalDirty => "local dirty",
Count::LocalUntrusted => "local dirty untrusted",
Count::MissedLocal => "missed local changes",
}
}
}
+3 -2
View File
@@ -349,8 +349,9 @@ Safety rules:
not tell, and why (`Unknown`: unreadable or vanished here; unread, under a short listing or
under a failed listing on Drive). Only a path known on both sides is classified, and only
`Absent` backs a deletion. Every deletion a pass plans is checked against the evidence once
more. For now that check acts on nothing: it logs the deletion and counts it as `unproven
deletions` in the pass trace, which should stay at zero.
more, and one it does not back is not made: the pass logs it, counts it as `unproven
deletions` in its trace and fails the step, and the next pass plans it again. The count
should stay at zero.
- **Wipe guard.** A pass in which every previously synced file has vanished locally is refused
instead of trashing the whole folder on Drive. It applies to any non-empty baseline.
- **Deletion window.** The wipe guard sees one pass. A tree lost a little at a time passes it once
+28 -1
View File
@@ -203,6 +203,26 @@ that grows into hours: it is network-bound, while the local walk only reads the
What a quiet pass still costs: loading the baseline and the picture from the database, and the
local walk. The local dirty set removes the local walk.
## Root reducer as built
The states above are first built as a check. `pdfs_sync::root` holds one reducer per mirror
folder. `step(state, input)` is pure: the passes, the watcher, the event stream and pause are
inputs, so a sequence of inputs replays exactly.
| State | Meaning |
|---|---|
| Discovering | No pass over the folder has finished yet. |
| Following | A pass covered the whole folder, and nothing since says a change went unreported. |
| Auditing | A doubt arrived: a watcher error, an overflowed queue, a gap in Drive's event stream, a restart or a suspension. Only a pass over the whole folder ends it. |
| Suspended | The local root is missing, or the folder is paused. |
| Draining | A switch to on-demand is queued, and passes only push. |
| HandedOff | The folder is on-demand. Going back to a mirror starts discovery again. |
Nothing acts on the state yet: every pass still covers the whole folder, so a finished pass
always returns the folder to Following. The engine logs each transition as `sync: root state`,
so the reducer can be compared with what the engine did. Once a Following folder plans from its
dirty sets alone, the state decides which passes must walk everything.
## Plan of work (separate PRs)
1. **Frontier checkpoint.**
@@ -210,7 +230,14 @@ local walk. The local dirty set removes the local walk.
- Left: per-subtree apply, once a round-level guard exists. A resumable local walk matters
less now that the local walk is the only full walk left, and is cheap next to Drive.
2. **Remote dirty set.** Done, described above.
3. **Local dirty set.** `SyncMsg::Dirty`, the `sync_dirty` table, overflow leading to FullCheck.
3. **Local dirty set.**
- Done, as a check: the watcher marks each path an event names in `LocalDirty` (in memory).
A pass claims the marks, and retires them once it applied everything it found. A claim is
trusted when the watch was live since the last pass claimed; a watcher error, an overflow or
a restart breaks that. Each pass still walks the whole folder, and counts the changes it
found that a trusted claim did not cover (`missed local changes` in the trace).
- Left: once that count stays at zero, a trusted claim stands in for the local walk, and
only the marked folders are read.
4. **Step scheduler.** Replace `run_burst` and the per-pass lock with steps and priorities.
5. **Drop the 120 s poll** for the daily audit, once 2 and 3 have run for a release with the
poll still on, and traces show the dirty sets catch everything the poll finds.
+11 -3
View File
@@ -309,9 +309,17 @@ What the parts mean:
happens on the first pass, once a day, and after the daemon lost track of Proton Drive's
changes. **`resumed`** counts the paths a pass took from a listing that a restart cut short.
- **`unproven deletions`** counts deletions a pass planned for a path it had not proven gone.
It should never appear. If it does, the journal has a `sync: a planned deletion is not backed
by proof of absence` line for each one; please report it with those lines.
- **`unproven deletions`** counts deletions a pass planned for a path it had not proven gone,
and so did not make. It should never appear. If it does, the folder shows an error, the path
stays on both sides, and the journal has a `sync: not deleting a path whose absence is not
proven` line for each one; please report it with those lines.
- **`local dirty`** counts the places on disk the filesystem watcher reported changed since the
last pass. **`local dirty untrusted`** is 1 when the watch was not live the whole time since
then: after a start, a watch that failed, or an overflowed event queue. **`missed local
changes`** counts changes the pass found on disk that a trusted watch did not report. It
should stay at zero; the journal then has a `sync: the local dirty set missed changes the walk
found` line naming the first one. For now these only check the watcher: every pass still
walks the whole folder.
Please include these lines when you report a slow folder.