Compare commits

...
Author SHA1 Message Date
nvrl ea29a260b0 Merge pull request #180 from narrrl/fix/echo-false-conflict
fix(fuse): read a write based on a landed create's placeholder as the create's revision
2026-11-27 19:31:10 +01:00
nvrl 8e9816919d Merge pull request #184 from narrrl/feat/sync-root-reducer
feat(sync): run a root reducer per mirror folder alongside the engine
2026-11-27 19:30:48 +01:00
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 1c900f47bc Merge branch 'feat/sync-typed-absence' into feat/sync-delete-window 2026-11-27 19:26:17 +01:00
nvrl a9adbf96ef Merge remote-tracking branch 'origin/main' into feat/sync-typed-absence
# Conflicts:
#	docs/ARCHITECTURE.md
2026-11-27 19:26:00 +01:00
nvrl bcdf78c44d Merge pull request #177 from narrrl/fix/eacces-evidence
fix(fuse): log which authority refused a change
2026-11-27 19:23:58 +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
nvrl fb77dbda6a feat(sync,store): add up a mirror folder's deletions across passes
The wipe guards see one pass. A tree lost a little at a time, by a
failing disk or a script, passes them once per pass, and the passes
between delete the rest in batches.

Each mirror folder now keeps a deletion window (schema 50): when it
began, the most paths the folder tracked since, and the deletions made
since on either side. A pass whose planned deletions would bring the
window to nine tenths of the folder is refused. The plan is recorded
before anything is deleted and settled to what was actually deleted
when the pass ends. A window lasts a day, and changing or removing the
folder drops it.
2026-11-27 19:01:07 +01:00
nvrl 1b64c37519 test(sync): the evidence classifies what the old filters kept 2026-11-27 18:27:31 +01:00
nvrl e74a36c57e feat(sync): make absence a typed fact, and check deletions against it
Step 4 of the 4.0 plan starts with typed absence. A path missing from a
walk was read through three separate filters (`Unscanned`, `RemoteGaps`
and the ignore rules), each applied where a pass read the walks. The new
`evidence` module answers one question per side instead: the path is
present, proven absent, excluded by rule, or unknown, with why
(unreadable, vanished, unread, under a short listing or under a failed
listing).

The mirror pass now classifies a path only when both sides are known,
which is the same set the old filters let through. Every deletion the
mirror pass and the push pass plan is checked against the evidence once
more in shadow mode: a deletion of a path not proven gone on the side it
is based on is logged and counted as `unproven deletions` in the pass
trace. The check acts on nothing; it should stay at zero, and makes a
regression in the filters visible before it can cost data.
2026-11-27 18:23:02 +01:00
nvrl 7e8417b135 fix(fuse): log which authority refused a change
Two simulation runs failed with an EACCES on a create or mkdir that
should have been allowed (three-clients seed 3 on #176, lan seed 4 on
#171). Neither reproduces locally, and the daemon log said nothing about
the refusal. Both admission points now log a warning when they refuse:
the tree's access for a node that is read-only, or, for a check by uid,
the persisted access and every resident mount's access. The next
occurrence in CI leaves the evidence in the simulation's daemon log.
2026-11-27 18:01:15 +01:00
24 changed files with 1892 additions and 37 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 {
+23 -2
View File
@@ -1200,7 +1200,21 @@ impl Core {
}
fn require_writable(&self, ino: u64) -> Result<(), Errno> {
self.state().require_writable(ino).map_err(node_errno)
let st = self.state();
st.require_writable(ino).map_err(|error| {
// A refusal of a node the mount owns has no cause the user can
// see, so it says which node and what access the tree holds.
if matches!(error, pdfs_vfs::tree::NodeError::NotWritable) {
let entry = st.entries.get(&ino);
warn!(
ino,
uid = ?entry.map(|e| &e.uid),
access = ?entry.map(|e| e.access),
"refused a change: the tree holds the node read-only"
);
}
node_errno(error)
})
}
/// Mutation admission point. Persisted and every resident authority must
@@ -1220,7 +1234,14 @@ impl Core {
// The drain, which replays intent recorded long ago, is the one
// caller that has to tell the two apart — see
// [`Core::uid_write_authority`].
WriteAuthority::Denied | WriteAuthority::Unknown => Err(Errno::EACCES),
refused @ (WriteAuthority::Denied | WriteAuthority::Unknown) => {
// Which authority refused, so a refusal nobody expected
// leaves evidence: the persisted row, or a resident mount.
let persisted = self.db.effective_node_access(uid);
let live: Vec<Access> = self.state().access_by_uid(uid).into_iter().collect();
warn!(%uid, ?refused, ?persisted, ?live, "refused a change: the node is not writable");
Err(Errno::EACCES)
}
}
}
+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() {
+39 -1
View File
@@ -11,7 +11,7 @@ use super::Db;
use pdfs_core::Result;
/// Current schema version. Bump on every forward migration added below.
pub(super) const SCHEMA_VERSION: i64 = 49;
pub(super) const SCHEMA_VERSION: i64 = 50;
impl Db {
pub(super) fn migrate(&self) -> Result<()> {
@@ -543,6 +543,16 @@ impl Db {
tx.execute_batch(MIGRATION_V49)?;
}
}
if current < 50 {
let has_folders: bool = tx.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sync_folder'",
[],
|row| row.get::<_, i64>(0).map(|n| n > 0),
)?;
if has_folders {
tx.execute_batch(MIGRATION_V50)?;
}
}
tx.execute(
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
@@ -1547,6 +1557,34 @@ ALTER TABLE sync_walk ADD COLUMN complete INTEGER NOT NULL DEFAULT 0;
ALTER TABLE sync_walk ADD COLUMN seq INTEGER NOT NULL DEFAULT 0;
";
/// Schema v50: the deletions a mirror folder made lately, so the wipe guard
/// sees a tree lost a little at a time, and not only one lost in a single pass
/// (`docs/SYNC_ENGINE.md`).
///
/// One row a folder: when the window began, how many paths the folder
/// tracked then, and how many deletions it has made since. A change to what
/// the folder is, or its removal, drops the row, as it drops the saved walk.
const MIGRATION_V50: &str = "
CREATE TABLE IF NOT EXISTS sync_delete_window (
folder_id INTEGER PRIMARY KEY,
started_at INTEGER NOT NULL,
reference INTEGER NOT NULL,
deleted INTEGER NOT NULL
);
DROP TRIGGER IF EXISTS sync_delete_window_drop_on_folder_update;
DROP TRIGGER IF EXISTS sync_delete_window_drop_on_folder_delete;
CREATE TRIGGER sync_delete_window_drop_on_folder_update
AFTER UPDATE OF local_path, remote_uid, mode ON sync_folder
BEGIN
DELETE FROM sync_delete_window WHERE folder_id = OLD.id;
END;
CREATE TRIGGER sync_delete_window_drop_on_folder_delete
AFTER DELETE ON sync_folder
BEGIN
DELETE FROM sync_delete_window WHERE folder_id = OLD.id;
END;
";
/// See [`MIGRATION_V49_COLUMNS`].
const MIGRATION_V49: &str = "
CREATE TABLE IF NOT EXISTS sync_remote_dirty (
+3 -1
View File
@@ -65,7 +65,9 @@ pub use ops::{
pub use photos::{StoredPhoto, StoredPlace, THUMB_HAVE, THUMB_NONE, THUMB_UNKNOWN, TimelineRow};
pub use pins::PinRow;
pub use replace::ReplaceIntent;
pub use sync::{SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
pub use sync::{
DeleteWindow, SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder,
};
pub use trash::StoredTrash;
/// Size the WAL is truncated back to after a checkpoint. Comfortably above the
+48
View File
@@ -7,6 +7,18 @@ use super::Db;
use pdfs_core::Result;
use std::collections::HashMap;
/// The deletions a mirror folder has made since a window began, which the
/// wipe guard adds to a pass's own before it lets that pass delete anything.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DeleteWindow {
/// When the window began, in seconds since the epoch.
pub started_at: i64,
/// The most paths the folder has tracked since then.
pub reference: u64,
/// The deletions made since then, on either side.
pub deleted: u64,
}
/// What a mirror pass has walked of Drive, saved so a pass cut short
/// resumes the walk instead of listing every folder again (B294), and so a
/// finished walk serves as the next pass's picture of Drive.
@@ -780,6 +792,42 @@ impl Db {
Ok(())
}
/// The deletion window of a mirror folder, if one is open.
pub fn sync_delete_window(&self, folder_id: i64) -> Result<Option<DeleteWindow>> {
let conn = self.read()?;
conn.query_row(
"SELECT started_at, reference, deleted FROM sync_delete_window WHERE folder_id = ?1",
params![folder_id],
|row| {
Ok(DeleteWindow {
started_at: row.get(0)?,
reference: row.get::<_, i64>(1)?.max(0) as u64,
deleted: row.get::<_, i64>(2)?.max(0) as u64,
})
},
)
.optional()
.map_err(Into::into)
}
/// Record the deletion window of a mirror folder.
pub fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"INSERT INTO sync_delete_window (folder_id, started_at, reference, deleted)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(folder_id) DO UPDATE SET started_at = excluded.started_at,
reference = excluded.reference, deleted = excluded.deleted",
params![
folder_id,
window.started_at,
i64::try_from(window.reference).unwrap_or(i64::MAX),
i64::try_from(window.deleted).unwrap_or(i64::MAX)
],
)?;
Ok(())
}
/// Drop the entire baseline for a folder. Used when flipping ondemand→mirror:
/// the local tree was evicted, so the old baseline is stale and would make the
/// next reconcile mistake "locally deleted" for "must re-download". Clearing it
+32
View File
@@ -8420,3 +8420,35 @@ fn a_replace_intent_is_kept_until_it_ends() {
db.end_replace("vol~src").unwrap();
assert!(db.open_replaces().unwrap().is_empty());
}
/// A folder's deletion window outlives the pass that opened it, and goes with
/// the folder: a change to what the folder is starts the count again.
#[test]
fn a_deletion_window_is_kept_per_folder_until_the_folder_changes() {
let db = Db::open_in_memory().unwrap();
let id = db.sync_folder_add("/home/me/Docs", "v~root", "s").unwrap();
let other = db
.sync_folder_add("/home/me/Other", "v~other", "s")
.unwrap();
assert_eq!(db.sync_delete_window(id).unwrap(), None);
let window = DeleteWindow {
started_at: 100,
reference: 40,
deleted: 12,
};
db.sync_delete_window_set(id, &window).unwrap();
db.sync_delete_window_set(other, &window).unwrap();
assert_eq!(db.sync_delete_window(id).unwrap(), Some(window));
let more = DeleteWindow {
deleted: 20,
..window
};
db.sync_delete_window_set(id, &more).unwrap();
assert_eq!(db.sync_delete_window(id).unwrap(), Some(more));
db.sync_folder_set_mode(id, "ondemand").unwrap();
assert_eq!(db.sync_delete_window(id).unwrap(), None);
assert_eq!(db.sync_delete_window(other).unwrap(), Some(window));
db.sync_folder_remove(other).unwrap();
assert_eq!(db.sync_delete_window(other).unwrap(), None);
}
+410
View File
@@ -0,0 +1,410 @@
//! What a pass knows about a path on each side, as a typed fact.
//!
//! A path missing from a walk is not proof that it is gone. The local scan
//! leaves out what it cannot read, the remote walk what would not decrypt or
//! list, and the ignore rules what the user excluded. Before this module each
//! of those was a filter of its own ([`Unscanned`], [`RemoteGaps`],
//! [`IgnoreRules`]), applied at each place that read the walks. Here they
//! answer one question per side, [`Presence`]: the path is there, it is
//! proven absent, it is excluded by rule, or nothing is known of it and why.
//!
//! 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`]). 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;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use crate::planner::{HasKind, RemoteGaps, Unscanned};
use pdfs_core::syncignore::IgnoreRules;
/// What a pass knows about one path on one side.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Presence {
/// The walk returned it.
Present,
/// The walk read the folder it would be in, completely, and it was not
/// there.
Absent,
/// The ignore rules exclude it, so the walks do not look at it.
Excluded,
/// The walk could not tell.
Unknown(Unknown),
}
/// Why a walk could not tell whether a path is there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unknown {
/// Here: the path, or a folder above it, cannot be read.
Unreadable,
/// Here: the path, or a folder above it, vanished while the scan looked
/// at it. The next pass sees it settled.
Vanished,
/// On Drive: the path is listed, but what the pass needs of it could not
/// be read.
Unread,
/// On Drive: the listing of the deepest folder above it named nodes that
/// did not come back, so it may be one of them.
ShortListing,
/// On Drive: the listing of the deepest folder above it failed.
Unlisted,
}
impl Presence {
/// Whether the side is known: there, or proven gone.
pub fn is_known(self) -> bool {
matches!(self, Presence::Present | Presence::Absent)
}
}
/// Which side a deletion acts on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
/// The local copy is deleted, because the path is gone from Drive.
Local,
/// The copy on Drive is trashed, because the path is gone here.
Remote,
}
/// The evidence of one pass: both walks and what each could not read.
pub struct Evidence<'a, L, R> {
pub rules: &'a IgnoreRules,
pub local: &'a HashMap<String, L>,
pub unscanned: &'a Unscanned,
/// `None` for a pass that does not walk Drive, such as the push pass
/// before a switch to on-demand. Every remote path is then unknown.
pub remote: Option<RemoteEvidence<'a, R>>,
}
/// The remote half of [`Evidence`].
pub struct RemoteEvidence<'a, R> {
pub entries: &'a HashMap<String, R>,
pub dirs: &'a HashMap<String, NodeUid>,
pub gaps: &'a RemoteGaps,
}
impl<L: HasKind, R: HasKind> Evidence<'_, L, R> {
/// Whether the ignore rules exclude `rel`. A path neither walk returned
/// has no kind, so it is tested as both: erring towards "excluded" only
/// leaves a path alone, never deletes it.
pub fn excluded(&self, rel: &str) -> bool {
if self.rules.is_empty() {
return false;
}
let kind = self.local.get(rel).map(HasKind::is_dir).or_else(|| {
self.remote
.as_ref()
.and_then(|remote| remote.entries.get(rel))
.map(HasKind::is_dir)
});
match kind {
Some(is_dir) => self.rules.is_ignored(rel, is_dir),
None => self.rules.is_ignored(rel, false) || self.rules.is_ignored(rel, true),
}
}
/// What the local walk says of `rel`.
pub fn local(&self, rel: &str) -> Presence {
if self.excluded(rel) {
return Presence::Excluded;
}
// Not even a path the scan returned is known when a folder above it
// could not be read: a pass leaves the whole subtree alone (B196).
if let Some(why) = self.unscanned.why(rel) {
return Presence::Unknown(why);
}
if self.local.contains_key(rel) {
Presence::Present
} else {
Presence::Absent
}
}
/// What the remote walk says of `rel`.
pub fn remote(&self, rel: &str) -> Presence {
if self.excluded(rel) {
return Presence::Excluded;
}
let Some(remote) = &self.remote else {
return Presence::Unknown(Unknown::Unlisted);
};
if remote.entries.contains_key(rel) {
return Presence::Present;
}
match remote.gaps.why(rel, remote.entries, remote.dirs) {
Some(why) => Presence::Unknown(why),
None => Presence::Absent,
}
}
/// Whether a pass may classify `rel`: neither side excluded, and both
/// known. A path under a folder the local scan could not read is left out
/// even when Drive has it, since a download has nowhere to be written.
pub fn classifiable(&self, rel: &str) -> bool {
self.local(rel).is_known() && self.remote(rel).is_known()
}
/// What the evidence says of the side a deletion of `rel` is based on,
/// when that is not proof of absence. A deletion of the local copy needs
/// `rel` proven gone from Drive, and a trash on Drive needs it proven
/// gone here.
pub fn unproven_deletion(&self, rel: &str, side: Side) -> Option<Presence> {
let basis = match side {
Side::Local => self.remote(rel),
Side::Remote => self.local(rel),
};
(basis != Presence::Absent).then_some(basis)
}
}
#[cfg(test)]
mod tests {
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
use super::*;
fn none() -> IgnoreRules {
IgnoreRules::load(std::path::Path::new("/nonexistent-sync-root"), &[])
}
struct Item(bool);
impl HasKind for Item {
fn is_dir(&self) -> bool {
self.0
}
}
fn map(paths: &[(&str, bool)]) -> HashMap<String, Item> {
paths
.iter()
.map(|(rel, dir)| (rel.to_string(), Item(*dir)))
.collect()
}
fn dirs(paths: &[&str]) -> HashMap<String, NodeUid> {
paths
.iter()
.map(|rel| {
(
rel.to_string(),
NodeUid::new(VolumeId::from("v"), LinkId::from(*rel)),
)
})
.collect()
}
#[test]
fn a_path_missing_from_a_complete_walk_is_absent() {
let rules = none();
let local = map(&[("a.txt", false)]);
let remote = map(&[("a.txt", false), ("b.txt", false)]);
let remote_dirs = dirs(&[""]);
let (unscanned, gaps) = (Unscanned::default(), RemoteGaps::default());
let evidence = Evidence {
rules: &rules,
local: &local,
unscanned: &unscanned,
remote: Some(RemoteEvidence {
entries: &remote,
dirs: &remote_dirs,
gaps: &gaps,
}),
};
assert_eq!(evidence.local("a.txt"), Presence::Present);
assert_eq!(evidence.local("b.txt"), Presence::Absent);
assert_eq!(evidence.remote("c.txt"), Presence::Absent);
assert!(evidence.classifiable("b.txt"));
assert_eq!(evidence.unproven_deletion("b.txt", Side::Remote), None);
assert_eq!(
evidence.unproven_deletion("a.txt", Side::Remote),
Some(Presence::Present)
);
}
#[test]
fn what_a_walk_could_not_read_is_unknown_never_absent() {
let rules = none();
let local = map(&[("locked", true)]);
let mut unscanned = Unscanned::default();
unscanned.unreadable("locked".into(), "permission denied");
unscanned.vanished("tmp".into());
let remote = map(&[("docs", true), ("docs/a.txt", false), ("pics", true)]);
let remote_dirs = dirs(&["", "docs", "pics"]);
let mut gaps = RemoteGaps::default();
gaps.short_listing("docs");
gaps.unlisted("pics");
gaps.unread("odd.bin".into());
let evidence = Evidence {
rules: &rules,
local: &local,
unscanned: &unscanned,
remote: Some(RemoteEvidence {
entries: &remote,
dirs: &remote_dirs,
gaps: &gaps,
}),
};
assert_eq!(
evidence.local("locked"),
Presence::Unknown(Unknown::Unreadable)
);
assert_eq!(
evidence.local("locked/deep/x.txt"),
Presence::Unknown(Unknown::Unreadable)
);
assert_eq!(
evidence.local("tmp/y"),
Presence::Unknown(Unknown::Vanished)
);
assert_eq!(
evidence.remote("docs/b.txt"),
Presence::Unknown(Unknown::ShortListing)
);
assert_eq!(evidence.remote("docs/a.txt"), Presence::Present);
assert_eq!(
evidence.remote("pics/2019/x.jpg"),
Presence::Unknown(Unknown::Unlisted)
);
assert_eq!(
evidence.remote("odd.bin"),
Presence::Unknown(Unknown::Unread)
);
assert_eq!(evidence.remote("top.txt"), Presence::Absent);
assert!(!evidence.classifiable("locked/deep/x.txt"));
assert!(!evidence.classifiable("docs/b.txt"));
assert_eq!(
evidence.unproven_deletion("locked/deep/x.txt", Side::Remote),
Some(Presence::Unknown(Unknown::Unreadable))
);
assert_eq!(
evidence.unproven_deletion("docs/b.txt", Side::Local),
Some(Presence::Unknown(Unknown::ShortListing))
);
}
#[test]
fn an_ignored_path_is_excluded_on_both_sides() {
let rules =
IgnoreRules::with_folder_text(std::path::Path::new("/r"), &[], "*.tmp\nbuild/\n");
let local = map(&[("a.tmp", false), ("build", true)]);
let remote: HashMap<String, Item> = HashMap::new();
let (unscanned, remote_dirs, gaps) =
(Unscanned::default(), dirs(&[""]), RemoteGaps::default());
let evidence = Evidence {
rules: &rules,
local: &local,
unscanned: &unscanned,
remote: Some(RemoteEvidence {
entries: &remote,
dirs: &remote_dirs,
gaps: &gaps,
}),
};
assert_eq!(evidence.local("a.tmp"), Presence::Excluded);
assert_eq!(evidence.remote("a.tmp"), Presence::Excluded);
assert_eq!(evidence.local("build"), Presence::Excluded);
// Neither walk returned it, so it is tested as a folder too.
assert_eq!(evidence.remote("build"), Presence::Excluded);
assert!(!evidence.classifiable("a.tmp"));
assert_eq!(
evidence.unproven_deletion("a.tmp", Side::Remote),
Some(Presence::Excluded)
);
}
/// The paths a pass classifies are the ones the separate filters let
/// through before: the ignore rules on the union of the walks, then
/// `Unscanned::covers` and `RemoteGaps::hides`.
#[test]
fn classifiable_paths_are_the_ones_the_old_filters_kept() {
let rules =
IgnoreRules::with_folder_text(std::path::Path::new("/r"), &[], "*.tmp\ncache/\n");
let local = map(&[
("a.txt", false),
("b.tmp", false),
("cache", true),
("locked", true),
("docs", true),
("docs/new.txt", false),
]);
let remote = map(&[
("a.txt", false),
("docs", true),
("docs/kept.txt", false),
("pics", true),
("remote-only.txt", false),
]);
let baseline: HashMap<String, Item> = map(&[
("a.txt", false),
("gone-here.txt", false),
("docs/lost.txt", false),
("pics/2019/x.jpg", false),
("locked/inner.txt", false),
("old.tmp", false),
("cache", true),
]);
let mut unscanned = Unscanned::default();
unscanned.unreadable("locked".into(), "permission denied");
let remote_dirs = dirs(&["", "docs", "pics"]);
let mut gaps = RemoteGaps::default();
gaps.short_listing("docs");
gaps.unlisted("pics");
let evidence = Evidence {
rules: &rules,
local: &local,
unscanned: &unscanned,
remote: Some(RemoteEvidence {
entries: &remote,
dirs: &remote_dirs,
gaps: &gaps,
}),
};
let mut old = crate::planner::classification_order(&local, &remote, &baseline, &rules);
old.retain(|rel| !unscanned.covers(rel) && !gaps.hides(rel, &remote, &remote_dirs));
let mut new = crate::planner::classification_order(
&local,
&remote,
&baseline,
&IgnoreRules::load(std::path::Path::new("/nonexistent-sync-root"), &[]),
);
new.retain(|rel| evidence.classifiable(rel));
old.sort();
new.sort();
assert_eq!(old, new);
// Left out: ignored paths, everything under the unreadable folder,
// what may hide under the short and the failed listing.
assert_eq!(
old,
[
"a.txt",
"docs",
"docs/kept.txt",
"gone-here.txt",
"pics",
"remote-only.txt"
]
);
}
#[test]
fn a_pass_that_does_not_walk_drive_knows_nothing_there() {
let rules = none();
let local = map(&[]);
let unscanned = Unscanned::default();
let evidence: Evidence<'_, Item, Item> = Evidence {
rules: &rules,
local: &local,
unscanned: &unscanned,
remote: None,
};
assert_eq!(evidence.local("gone.txt"), Presence::Absent);
assert!(!evidence.remote("gone.txt").is_known());
assert!(!evidence.classifiable("gone.txt"));
assert_eq!(evidence.unproven_deletion("gone.txt", Side::Remote), None);
}
}
+4 -1
View File
@@ -16,14 +16,17 @@ use std::time::{Duration, Instant, SystemTime};
use pdfs_core::control::ActivityKind;
use pdfs_core::syncignore::IgnoreRules;
use pdfs_store::db::StoredSyncEntry;
use pdfs_store::db::{DeleteWindow, StoredSyncEntry};
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());
}
}
+306 -6
View File
@@ -38,13 +38,17 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
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;
use pdfs_core::timestamp::now_secs;
use pdfs_core::transfers::{CountingWriter, OwnedCountingReader};
use pdfs_drive::parse_uid;
use pdfs_store::db::{SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
use pdfs_store::db::{DeleteWindow, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
mod apply;
mod engine;
@@ -78,10 +82,10 @@ use planner::conflict_path_as;
#[cfg(test)]
use planner::filter_baseline;
use planner::{
FilePlan, RemoteGaps, Unscanned, classification_order, guard_local_wipe, guard_remote_wipe,
join_rel, local_deletions, parent_rel, plan_file, rel_to_path, remote_sig,
remote_subtree_changed, revision_confirms_baseline, revision_moved, tracked_baseline,
unchanged_remote_size,
FilePlan, RemoteGaps, Unscanned, classification_order, delete_window, guard_delete_window,
guard_local_wipe, guard_remote_wipe, join_rel, local_deletions, parent_rel, plan_file,
planned_deletions, rel_to_path, remote_sig, remote_subtree_changed, revision_confirms_baseline,
revision_moved, tracked_baseline, unchanged_remote_size,
};
use trace::{Call, Count, Phase};
@@ -98,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);
}
@@ -147,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
@@ -209,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 —
@@ -352,6 +375,35 @@ impl Syncer {
}
}
/// 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,
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.
fn trace_phase(&self, phase: Phase, took: Duration) {
self.engine.trace(|t| t.phase(phase, took));
@@ -474,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();
@@ -501,7 +562,19 @@ impl Syncer {
// ignored one, and a remote path under it has nowhere to be written.
// The same holds for a path the remote walk could not read: missing
// from it, it would read as deleted on Drive (B212).
order.retain(|rel| !unscanned.covers(rel) && !gaps.hides(rel, &remote, &remote_dirs));
// Only a path both walks know about is classified (`evidence`).
order.retain(|rel| {
pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps).classifiable(rel)
});
// The deletions this pass plans, added to those the folder made
// lately: a tree lost a little at a time passes the guards above one
// pass at a time.
let window = self.claim_deletions(
folder_id,
tracked_baseline(&baseline, rules, &unscanned).len(),
planned_deletions(&order, &local, &remote, &baseline),
)?;
let mut unscanned_report = unscanned.report();
unscanned_report.extend(gaps.report());
@@ -587,6 +660,14 @@ impl Syncer {
}
(true, false) => {
// In baseline, gone remotely → the remote side deleted it.
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 => {
@@ -601,6 +682,14 @@ impl Syncer {
}
(false, true) => {
// In baseline, gone locally → the local side deleted it.
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) => {
@@ -691,6 +780,14 @@ impl Syncer {
}
},
FilePlan::DeleteLocal => {
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
@@ -717,6 +814,14 @@ impl Syncer {
outcome.deleted += 1;
}
FilePlan::DeleteRemote => {
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
@@ -852,13 +957,155 @@ impl Syncer {
outcome.deleted += 1;
}
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
/// the folder tracks now.
///
/// The window is recorded before anything is deleted, as if every planned
/// deletion will succeed: a pass cut short then leaves the window counting
/// at least what it deleted. Returns the window as it was before this
/// pass, for [`settle_deletions`](Self::settle_deletions).
fn claim_deletions(
&self,
folder_id: i64,
tracked: usize,
planned: usize,
) -> Result<Option<DeleteWindow>, String> {
let open = self
.store
.sync_delete_window(folder_id)
.map_err(|e| format!("load the deletion window: {e:?}"))?;
let window = delete_window(open, tracked, now_secs());
guard_delete_window(&window, planned)?;
if planned == 0 {
return Ok(None);
}
let claimed = DeleteWindow {
deleted: window.deleted + planned as u64,
..window
};
self.store
.sync_delete_window_set(folder_id, &claimed)
.map_err(|e| format!("record the deletion window: {e:?}"))?;
Ok(Some(window))
}
/// Count what a finished pass actually deleted in the window
/// [`claim_deletions`](Self::claim_deletions) opened, in place of what it
/// planned to: a deletion that failed is tried again by the next pass and
/// would otherwise count twice.
fn settle_deletions(&self, folder_id: i64, window: Option<DeleteWindow>, deleted: usize) {
let Some(window) = window else {
return;
};
let settled = DeleteWindow {
deleted: window.deleted + deleted as u64,
..window
};
if let Err(e) = self.store.sync_delete_window_set(folder_id, &settled) {
debug!(id = folder_id, error = ?e, "sync: cannot settle the deletion window");
}
}
}
/// 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
/// walks only for the question: `remote_dirs` gains the folders the pass
/// creates between questions.
fn pass_evidence<'a>(
rules: &'a IgnoreRules,
local: &'a HashMap<String, LocalItem>,
unscanned: &'a Unscanned,
remote: &'a HashMap<String, RemoteItem>,
remote_dirs: &'a HashMap<String, NodeUid>,
gaps: &'a RemoteGaps,
) -> Evidence<'a, LocalItem, RemoteItem> {
Evidence {
rules,
local,
unscanned,
remote: Some(RemoteEvidence {
entries: remote,
dirs: remote_dirs,
gaps,
}),
}
}
struct Sha1Tap<R> {
inner: R,
hasher: Arc<Mutex<Sha1>>,
@@ -1661,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>,
+10
View File
@@ -308,6 +308,16 @@ impl Syncer {
}
return Ok(outcome);
}
let evidence: Evidence<'_, LocalItem, RemoteItem> = Evidence {
rules,
local: &local,
unscanned: &unscanned,
remote: None,
};
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
+251 -14
View File
@@ -102,7 +102,8 @@ pub fn filter_baseline<'a, B>(
/// stopping every other file in the tree from syncing (B196).
#[derive(Default)]
pub struct Unscanned {
covered: HashSet<String>,
/// Each left-out path, with why it was left out.
covered: HashMap<String, crate::evidence::Unknown>,
/// The subset worth telling the user about, with why: an entry that only
/// vanished mid-scan is not, since the next pass sees it settled.
unreadable: Vec<String>,
@@ -111,29 +112,37 @@ pub struct Unscanned {
impl Unscanned {
/// Leave out `rel`, which vanished while the scan looked at it.
pub fn vanished(&mut self, rel: String) {
self.covered.insert(rel);
// An unreadable path stays unreadable: that is the reason the user
// is told about.
self.covered
.entry(rel)
.or_insert(crate::evidence::Unknown::Vanished);
}
/// Leave out `rel`, which cannot be read for `reason`.
pub fn unreadable(&mut self, rel: String, reason: &str) {
self.unreadable.push(format!("{rel} ({reason})"));
self.covered.insert(rel);
self.covered
.insert(rel, crate::evidence::Unknown::Unreadable);
}
/// Whether `rel` is a left-out path or lies under one.
pub fn covers(&self, rel: &str) -> bool {
self.why(rel).is_some()
}
/// Why `rel` was left out, when it is a left-out path or lies under one.
/// The nearest left-out path above it decides.
pub fn why(&self, rel: &str) -> Option<crate::evidence::Unknown> {
if self.covered.is_empty() {
return false;
return None;
}
let mut at = rel;
loop {
if self.covered.contains(at) {
return true;
}
match at.rfind('/') {
Some(i) => at = &at[..i],
None => return false,
if let Some(why) = self.covered.get(at) {
return Some(*why);
}
at = &at[..at.rfind('/')?];
}
}
@@ -250,6 +259,84 @@ pub fn guard_remote_wipe<B, R>(
Ok(())
}
/// How long the deletions a folder makes add up in one window, before a
/// new window starts from the folder as it then is.
pub const DELETE_WINDOW_SECS: i64 = 24 * 60 * 60;
/// The window a pass's deletions count in: the one `open`, or a new one from
/// `now` when none is open or it has run out. `tracked` is how many paths the
/// folder tracks now.
///
/// The reference grows with what is added during the window, so a folder that
/// gains files and then loses them is measured against what it held at its
/// largest. It never shrinks: a tree lost a little at a time is measured
/// against the tree it was, which is the point.
pub fn delete_window(open: Option<DeleteWindow>, tracked: usize, now: i64) -> DeleteWindow {
let tracked = tracked as u64;
match open {
Some(w) if (w.started_at..w.started_at + DELETE_WINDOW_SECS).contains(&now) => {
DeleteWindow {
reference: w.reference.max(tracked + w.deleted),
..w
}
}
_ => DeleteWindow {
started_at: now,
reference: tracked,
deleted: 0,
},
}
}
/// Refuse a pass whose `planned` deletions, added to those the folder made
/// since its `window` began, would make the window a wipe
/// ([`looks_like_a_wipe`]).
///
/// The per-pass guards see one pass. A tree lost a little at a time, by a
/// failing disk or a script, passes each of them in turn, and the passes
/// between delete the rest of the tree in batches (`docs/SYNC_ENGINE.md`).
/// Measured against the whole folder, a user emptying one large subfolder of
/// a healthy tree still passes.
pub fn guard_delete_window(window: &DeleteWindow, planned: usize) -> Result<(), String> {
let deleted = window.deleted.saturating_add(planned as u64);
if planned > 0 && looks_like_a_wipe(deleted as usize, window.reference as usize) {
return Err(format!(
"{deleted} of {} synced paths would be deleted within a day; refusing to \
delete more. If deleted on purpose, remove the folder from sync; to \
upload them again, sync the folder from scratch.",
window.reference
));
}
Ok(())
}
/// How many of `order` a mirror pass will delete, on either side: the files
/// [`plan_file`] deletes, and the folders gone from one side that the
/// baseline still has.
pub fn planned_deletions(
order: &[String],
local: &HashMap<String, LocalItem>,
remote: &HashMap<String, RemoteItem>,
baseline: &HashMap<String, StoredSyncEntry>,
) -> usize {
order
.iter()
.filter(|rel| {
let (l, r) = (local.get(*rel), remote.get(*rel));
let in_base = baseline.get(*rel);
// As the pass tells a folder: a folder gone from both sides only
// loses its baseline row.
if l.map(|x| x.is_dir).or(r.map(|x| x.is_dir)).unwrap_or(false) {
return in_base.is_some() && l.is_some() != r.is_some();
}
matches!(
plan_file(l, r, in_base),
FilePlan::DeleteLocal | FilePlan::DeleteRemote
)
})
.count()
}
/// What a remote walk saw but could not read: a node the SDK left out because
/// it would not decrypt, or a file whose size could not be read.
///
@@ -305,21 +392,37 @@ impl RemoteGaps {
remote: &HashMap<String, R>,
remote_dirs: &HashMap<String, NodeUid>,
) -> bool {
self.why(rel, remote, remote_dirs).is_some()
}
/// Why `rel` may be missing from `remote` only because the walk could not
/// read it, or `None` when its absence is real. A path the walk returned
/// is never hidden.
pub fn why<R>(
&self,
rel: &str,
remote: &HashMap<String, R>,
remote_dirs: &HashMap<String, NodeUid>,
) -> Option<crate::evidence::Unknown> {
use crate::evidence::Unknown;
if self.is_empty() || remote.contains_key(rel) {
return false;
return None;
}
if self.unread.contains(rel) {
return true;
return Some(Unknown::Unread);
}
// The deepest folder the walk did list decides: under a short listing,
// anything not returned may be one of the nodes it could not read.
let mut at = parent_rel(rel);
loop {
if remote_dirs.contains_key(at) {
return self.short.contains(at) || self.unlisted.contains(at);
if self.unlisted.contains(at) {
return Some(Unknown::Unlisted);
}
return self.short.contains(at).then_some(Unknown::ShortListing);
}
if at.is_empty() {
return false;
return None;
}
at = parent_rel(at);
}
@@ -1019,3 +1122,137 @@ mod file_plan_tests {
assert_eq!(remote_subtree_changed("x", &remote_tree, &base), None);
}
}
#[cfg(test)]
mod delete_window_tests {
use super::*;
const NOW: i64 = 1_800_000_000;
fn window(started_at: i64, reference: u64, deleted: u64) -> DeleteWindow {
DeleteWindow {
started_at,
reference,
deleted,
}
}
#[test]
fn a_window_opens_from_the_folder_as_it_is_and_runs_out_after_a_day() {
assert_eq!(delete_window(None, 100, NOW), window(NOW, 100, 0));
let open = window(NOW, 100, 30);
assert_eq!(delete_window(Some(open), 70, NOW + 60), open);
let later = NOW + DELETE_WINDOW_SECS;
assert_eq!(delete_window(Some(open), 70, later), window(later, 70, 0));
// A clock that went back does not keep a window open for ever.
assert_eq!(
delete_window(Some(open), 70, NOW - 1),
window(NOW - 1, 70, 0)
);
}
#[test]
fn what_a_folder_gains_in_a_window_raises_its_reference() {
// 30 deleted and 50 added since: the folder has held 150 paths.
let open = window(NOW, 100, 30);
assert_eq!(delete_window(Some(open), 120, NOW + 1).reference, 150);
}
/// The case the per-pass guard cannot see: a tree lost ten paths a pass.
/// Each pass alone deletes a small share of what is left, until the very
/// last; counted together the window stops them at nine tenths.
#[test]
fn a_tree_lost_a_little_each_pass_is_stopped_at_nine_tenths() {
let mut open = None;
let mut tracked = 100usize;
let mut passes = 0;
loop {
let w = delete_window(open, tracked, NOW + passes);
if guard_delete_window(&w, 10).is_err() {
break;
}
assert!(
!looks_like_a_wipe(10, tracked),
"the per-pass guard let it through"
);
open = Some(DeleteWindow {
deleted: w.deleted + 10,
..w
});
tracked -= 10;
passes += 1;
}
assert_eq!(
passes, 8,
"80 deleted, the pass that makes it 90 is refused"
);
}
#[test]
fn emptying_one_large_subfolder_of_a_healthy_tree_passes() {
let w = delete_window(None, 1000, NOW);
assert!(guard_delete_window(&w, 600).is_ok());
let w = window(NOW, 1000, 600);
assert!(guard_delete_window(&w, 250).is_ok());
}
#[test]
fn a_pass_with_nothing_to_delete_is_never_refused() {
assert!(guard_delete_window(&window(NOW, 100, 95), 0).is_ok());
assert!(guard_delete_window(&window(NOW, 100, 95), 1).is_err());
}
#[test]
fn planned_deletions_counts_both_sides_and_folders() {
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
let item = |is_dir| LocalItem {
mtime_ns: None,
is_dir,
mtime: 1,
size: 1,
open_for_write: false,
};
let node = |is_dir| RemoteItem {
uid: NodeUid::new(VolumeId::from("v"), LinkId::from("l")),
is_dir,
mtime: 1,
size: 1,
revision: None,
sha1: None,
};
let row = |rel: &str| StoredSyncEntry {
rel_path: rel.into(),
remote_uid: Some("v~l".into()),
local_mtime: 1,
local_mtime_ns: None,
local_size: 1,
remote_rev: Some("1".into()),
remote_hash: Some("1".into()),
remote_revision_id: None,
};
// Gone remotely, gone locally, a folder gone remotely, one on both
// sides, a new local file, and a folder gone from both sides.
let local: HashMap<String, LocalItem> = [
("a.txt", item(false)),
("d", item(true)),
("kept", item(false)),
("new.txt", item(false)),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
let remote: HashMap<String, RemoteItem> = [("b.txt", node(false)), ("kept", node(false))]
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
let baseline: HashMap<String, StoredSyncEntry> = ["a.txt", "b.txt", "d", "kept", "gone"]
.into_iter()
.map(|rel| (rel.to_string(), row(rel)))
.collect();
let order: Vec<String> = ["a.txt", "b.txt", "d", "kept", "new.txt", "gone"]
.into_iter()
.map(String::from)
.collect();
assert_eq!(planned_deletions(&order, &local, &remote, &baseline), 3);
}
}
+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);
}
}
+19 -3
View File
@@ -1,7 +1,8 @@
//! The port through which the mirror engine reads and writes its own tables.
//!
//! The engine keeps three things in the database: the synced folders, the
//! per-file baseline of each, and the saved walk of Drive with its dirty marks.
//! The engine keeps four things in the database: the synced folders, the
//! per-file baseline of each, the saved walk of Drive with its dirty marks,
//! and the deletions each folder made lately.
//! [`SyncStore`] is exactly the calls a pass makes on them, so the engine does
//! not depend on the whole database, and a test can give it a store of its own.
//!
@@ -11,7 +12,9 @@
use std::collections::HashMap;
use pdfs_core::Result;
use pdfs_store::db::{Db, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
use pdfs_store::db::{
Db, DeleteWindow, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder,
};
/// The sync tables, as the mirror engine uses them.
pub trait SyncStore: Send + Sync {
@@ -70,6 +73,13 @@ pub trait SyncStore: Send + Sync {
fn sync_remote_dirty_consume(&self, folder_id: i64, seq: i64) -> Result<()>;
/// Mark folders to list on Drive again.
fn sync_remote_mark(&self, folder_id: i64, dirs: &[String]) -> Result<()>;
// The deletions made lately, for the wipe guard.
/// The folder's deletion window, if one is open.
fn sync_delete_window(&self, folder_id: i64) -> Result<Option<DeleteWindow>>;
/// Record the folder's deletion window.
fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()>;
}
impl SyncStore for Db {
@@ -138,6 +148,12 @@ impl SyncStore for Db {
fn sync_remote_mark(&self, folder_id: i64, dirs: &[String]) -> Result<()> {
Db::sync_remote_mark(self, folder_id, dirs)
}
fn sync_delete_window(&self, folder_id: i64) -> Result<Option<DeleteWindow>> {
Db::sync_delete_window(self, folder_id)
}
fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()> {
Db::sync_delete_window_set(self, folder_id, window)
}
}
#[cfg(test)]
+21 -1
View File
@@ -133,10 +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, 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; 9] = [
const ALL: [Count; 13] = [
Count::LocalEntries,
Count::RemoteFolders,
Count::Nodes,
@@ -146,6 +158,10 @@ impl Count {
Count::Resumed,
Count::Reused,
Count::Dirty,
Count::UnprovenDeletions,
Count::LocalDirty,
Count::LocalUntrusted,
Count::MissedLocal,
];
fn name(self) -> &'static str {
@@ -159,6 +175,10 @@ impl Count {
Count::Resumed => "resumed",
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",
}
}
}
+16 -1
View File
@@ -50,7 +50,7 @@ graph TD
| [`pdfs-core`](../crates/pdfs-core) | Authentication and keyring (`auth`), configuration and directories (`config`), the control protocol (`control`), search scoring, ignore rules, Google Takeout parsing, the machine profile, the transfer registry (`transfers`) and the shutdown signal (`shutdown`) |
| [`pdfs-store`](../crates/pdfs-store) | The SQLite schema and queries (`db/`), the content cache (`cache`) |
| [`pdfs-drive`](../crates/pdfs-drive) | The `DriveApi` seam over the SDK, the call counter (`counted`), and `FakeDrive` for the simulations |
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes (`mirror`), split into the walks (`mirror::walk`), applying a plan (`mirror::apply`) and the push pass (`mirror::push`), its engine thread (`mirror::engine`), its reads and writes of the local disk in one module (`mirror::local`), and the parts with no I/O: planner, pass model and pass trace. It owns its state (`SyncParts`), reads and writes its tables only through `SyncStore`, and reaches the daemon only through `SyncHost` |
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes (`mirror`), split into the walks (`mirror::walk`), applying a plan (`mirror::apply`) and the push pass (`mirror::push`), its engine thread (`mirror::engine`), its reads and writes of the local disk in one module (`mirror::local`), and the parts with no I/O: planner, what each walk proves about a path (`evidence`), pass model and pass trace. It owns its state (`SyncParts`), reads and writes its tables only through `SyncStore`, and reaches the daemon only through `SyncHost` |
| [`pdfs-sched`](../crates/pdfs-sched) | The admission port: a service describes each step of background work it is about to run (`Step`: its class and its root) and waits for a `Permit` from an `Admission`. `Bounded` admits a fixed number at once. The mirror engine admits every upload, download and folder creation of a pass through it |
| [`pdfs-vfs`](../crates/pdfs-vfs) | The mounted-files service, with no kernel adapter: the tree (`tree`: nodes, stable inodes, per-mount roots), the reserved inodes (`ids`), the open files (`open`: write handles and their authored ranges, released writes waiting for upload, directory handles, `fallocate` rules), the open-file service (`files`: open, write, resize, fsync and close, behind the `FilesHost` port), the namespace service (`namespace`: create, mkdir, unlink, rmdir and rename behind the `NamespaceHost` port, and the settling of a cut-off replacing rename), a headless adapter that serves both by path (`headless`) and the scenarios every adapter has to pass (`conformance`), and what the mount accepted but has not sent yet (`writes`: queued revisions, nodes removed here, echoes of our own changes). Errors are typed; the FUSE adapter maps them to errno |
| [`pdfs-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), finding nodes (`resolve`), folder listings and file sizes (`listing`, `sizes`), reads (`reads`), queueing and the drain (`enqueue`, `queue`, `drain`, `upload`), calls sent straight to Drive (`remote`), requests by path (`requests`), startup recovery (`recovery`), pins, search, trash, the shared tree (`shared`), the link state (`link`), remote events (`background`), the daemon's side of the sync engine (`sync`, which implements `SyncHost`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
@@ -343,8 +343,23 @@ A filesystem watcher (`notify`) and a remote poll every 120 s feed a debounced p
Safety rules:
- **Absence is a typed fact** (`pdfs_sync::evidence`). For each path and side, a pass knows
that it is there (`Present`), that the walk read the folder it would be in completely and it
was not there (`Absent`), that the ignore rules exclude it (`Excluded`), or that the walk could
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, 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
per pass, so each folder also counts the deletions it made in the last day, on either side, in
`sync_delete_window` (schema 50). A mirror pass whose deletions would bring that count to nine
tenths of what the folder tracked is refused (`guard_delete_window`). A user emptying one large
subfolder of a healthy tree stays under it. A pass records its plan before it deletes and what
it actually deleted once it ends. Changing or removing the folder drops the window.
- **Open for writing.** Files that some process holds open for writing (`/proc/*/fd`,
`open_for_write_set`) are left out of the pass and picked up after they are closed.
- **Ignore rules.** `.pdfsignore` (or `.protonignore`) at the folder root plus `ignore_patterns`
+8 -2
View File
@@ -11,8 +11,9 @@ scratch (user data in `staging/` and `recovery/` is never touched by this).
## [Unreleased]
Schema: **49**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
kept, with a list of the folders that changed on Proton Drive since (49).
Schema: **50**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
kept, with a list of the folders that changed on Proton Drive since (49). Each mirror folder
counts the deletions it made in the last day (50).
### Added
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
@@ -44,6 +45,11 @@ kept, with a list of the folders that changed on Proton Drive since (49).
any more.
### Changed
- **Deletions in a mirror folder add up across passes.** A sync pass already refuses to delete
nearly every file of a folder at once. Now a folder lost a little at a time is stopped too:
once nine in ten of its synced files would have been deleted within a day, on either side,
the pass is refused and the folder shows the error. Emptying one large subfolder of a healthy
folder still goes through.
- **A sync pass over a large folder picks up where a restart stopped it.** A pass lists the
folder on Proton Drive before it changes anything, and on a folder of hundreds of thousands
of files that takes hours. A restart used to throw the listing away, so a large enough folder
+3 -1
View File
@@ -183,7 +183,9 @@ This section is for the curious and for anyone debugging a restore.
ones become conflict copies, as described above.
- **The wipe guard.** A sync pass in which every previously synced file has vanished locally is
refused instead of being mirrored to Proton Drive as a mass deletion. A folder that was emptied
by accident therefore does not empty the backup.
by accident therefore does not empty the backup. Deletions made over several passes add up:
once nine in ten of a folder's synced paths would have gone within a day, further deletions
are refused too.
- **The profile format.** Each profile carries a `version` field. A client refuses a profile
written by a newer, incompatible client instead of applying part of it.
+33 -1
View File
@@ -131,6 +131,11 @@ would refuse a user who empties one large folder on purpose. Left out, they woul
listing or an unmounted disk delete one subtree at a time. Both need a round-level guard
before planning can be split up.
That guard is the deletion window (`guard_delete_window`): a folder counts the deletions it made
in the last day against the most paths it tracked in that time, and refuses a pass that would
bring the count to nine tenths. It already covers a tree lost over several whole passes. Split
planning would add each step's deletions to the same count.
What is built:
- **Schema 48:** `sync_walk` (root, start time), `sync_walk_dir` (each folder found:
@@ -198,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.**
@@ -205,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.
+12
View File
@@ -309,6 +309,18 @@ 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,
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.
### Files named `(sync-conflict …)` appeared