Compare commits

..
Author SHA1 Message Date
nvrl f97b57236e Merge pull request #138 from narrrl/refactor/pdfs-sync
refactor: move the sync planner, pass model and trace into pdfs-sync
2026-11-26 01:11:41 +01:00
18 changed files with 29 additions and 1288 deletions

No files matched your search

-9
View File
@@ -3646,15 +3646,6 @@ fn cmd_diagnostics() -> Result<()> {
);
}
}
if !d.drive_calls.is_empty() {
println!("calls to Drive since start:");
for call in &d.drive_calls {
println!(
" {:<38} {:>7} calls {:>5} failed {:>9} ms total {:>7} ms longest",
call.call, call.count, call.errors, call.total_ms, call.longest_ms,
);
}
}
if d.inflight.is_empty() {
println!("in-flight requests: none");
} else {
-16
View File
@@ -2369,22 +2369,6 @@ pub struct Diagnostics {
/// The folder-sync engine. `None` from a daemon that predates the field.
#[serde(default)]
pub sync: Option<SyncEngineState>,
/// Every kind of call made to Drive since start: how many, how many
/// failed, and how long they took. Empty from a daemon that predates the
/// field.
#[serde(default)]
pub drive_calls: Vec<DriveCallStat>,
}
/// One kind of call to Drive, in [`Diagnostics::drive_calls`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct DriveCallStat {
/// The client method, such as `enumerate_folder_children_node_uids`.
pub call: String,
pub count: u64,
pub errors: u64,
pub total_ms: u64,
pub longest_ms: u64,
}
/// What the folder-sync engine is doing, for [`Diagnostics`].
-1
View File
@@ -11,7 +11,6 @@ pub mod error;
pub mod kernelkey;
pub mod keycheck;
pub mod localindex;
pub mod lockrank;
pub mod menu;
pub mod mountfail;
pub mod mountpoint;
-244
View File
@@ -1,244 +0,0 @@
//! A mutex that knows where it sits in the daemon's lock order.
//!
//! Most of the daemon's deadlocks were two threads taking the same pair of
//! locks in opposite orders (`docs/BUGS.md` B110, the cold size upgrade, the
//! diagnostics threads behind the database writer). Each such order was
//! written down in a comment, and the next feature did not read it.
//!
//! A [`Ranked`] lock carries a [`Rank`]. In a debug build, a thread that blocks
//! on a lock while it holds one of a higher rank panics, naming both, at the
//! line that would deadlock under the wrong interleaving. Release builds keep
//! no record and check nothing.
//!
//! Locks of equal rank may be held together. The code that takes several of
//! them orders them itself (several synced folders, lowest id first). A
//! `try_lock` cannot wait, so it is never refused, but what it takes is
//! recorded like any other lock.
use std::ops::{Deref, DerefMut};
use std::time::Duration;
use parking_lot::{Mutex, MutexGuard};
/// Where a lock sits in the order. A thread takes locks in increasing rank.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Rank {
/// One synced folder's lock, held by its sync pass for as long as the pass
/// runs.
SyncFolder = 10,
/// Publishing a shared change to every mounted session.
SharedPublication = 20,
/// The inode tree.
State = 30,
/// The database's single write connection.
DbWriter = 40,
}
/// A mutex with a [`Rank`]; see the module documentation.
pub struct Ranked<T> {
rank: Rank,
inner: Mutex<T>,
}
impl<T> Ranked<T> {
pub const fn new(rank: Rank, value: T) -> Self {
Self {
rank,
inner: Mutex::new(value),
}
}
pub fn rank(&self) -> Rank {
self.rank
}
/// Block until the lock is free. In a debug build, panics when this
/// thread holds a lock of a higher rank.
pub fn lock(&self) -> RankedGuard<'_, T> {
held::check(self.rank);
RankedGuard::new(self.inner.lock(), self.rank)
}
/// Take the lock if it is free.
pub fn try_lock(&self) -> Option<RankedGuard<'_, T>> {
self.inner
.try_lock()
.map(|guard| RankedGuard::new(guard, self.rank))
}
/// Wait up to `timeout` for the lock. It waits, so it is checked as
/// [`Ranked::lock`] is.
pub fn try_lock_for(&self, timeout: Duration) -> Option<RankedGuard<'_, T>> {
held::check(self.rank);
self.inner
.try_lock_for(timeout)
.map(|guard| RankedGuard::new(guard, self.rank))
}
pub fn into_inner(self) -> T {
self.inner.into_inner()
}
pub fn get_mut(&mut self) -> &mut T {
self.inner.get_mut()
}
}
/// A held [`Ranked`] lock.
pub struct RankedGuard<'a, T> {
guard: MutexGuard<'a, T>,
_held: held::Held,
}
impl<'a, T> RankedGuard<'a, T> {
fn new(guard: MutexGuard<'a, T>, rank: Rank) -> Self {
Self {
guard,
_held: held::Held::new(rank),
}
}
}
impl<T> Deref for RankedGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
&self.guard
}
}
impl<T> DerefMut for RankedGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.guard
}
}
#[cfg(debug_assertions)]
mod held {
use std::cell::RefCell;
use super::Rank;
thread_local! {
/// The ranks this thread holds, in the order it took them.
static HELD: RefCell<Vec<Rank>> = const { RefCell::new(Vec::new()) };
}
pub(super) fn check(rank: Rank) {
HELD.with(|held| {
let held = held.borrow();
if let Some(higher) = held.iter().find(|&&other| other > rank) {
panic!(
"lock order: waiting on {rank:?} while holding {higher:?} \
(held: {held:?}); take {rank:?} first (see pdfs_core::lockrank)"
);
}
});
}
pub(super) struct Held(Rank);
impl Held {
pub(super) fn new(rank: Rank) -> Self {
HELD.with(|held| held.borrow_mut().push(rank));
Self(rank)
}
}
impl Drop for Held {
fn drop(&mut self) {
HELD.with(|held| {
let mut held = held.borrow_mut();
// Guards can drop out of order; forget the latest of this rank.
if let Some(at) = held.iter().rposition(|&rank| rank == self.0) {
held.remove(at);
}
});
}
}
}
#[cfg(not(debug_assertions))]
mod held {
use super::Rank;
#[inline]
pub(super) fn check(_: Rank) {}
pub(super) struct Held;
impl Held {
#[inline]
pub(super) fn new(_: Rank) -> Self {
Held
}
}
}
#[cfg(all(test, debug_assertions))]
mod tests {
use super::*;
#[test]
fn locks_taken_in_rank_order_are_allowed() {
let state = Ranked::new(Rank::State, 1);
let db = Ranked::new(Rank::DbWriter, 2);
let a = state.lock();
let b = db.lock();
assert_eq!(*a + *b, 3);
}
#[test]
#[should_panic(expected = "lock order: waiting on State while holding DbWriter")]
fn a_lower_rank_taken_under_a_higher_one_panics() {
let state = Ranked::new(Rank::State, ());
let db = Ranked::new(Rank::DbWriter, ());
let _db = db.lock();
let _state = state.lock();
}
#[test]
fn locks_of_equal_rank_may_be_held_together() {
let one = Ranked::new(Rank::SyncFolder, ());
let two = Ranked::new(Rank::SyncFolder, ());
let _one = one.lock();
let _two = two.lock();
}
#[test]
fn a_released_lock_no_longer_counts() {
let state = Ranked::new(Rank::State, ());
let db = Ranked::new(Rank::DbWriter, ());
drop(db.lock());
let _state = state.lock();
let _db = db.lock();
}
#[test]
fn guards_dropped_out_of_order_are_both_forgotten() {
let publication = Ranked::new(Rank::SharedPublication, ());
let state = Ranked::new(Rank::State, ());
let db = Ranked::new(Rank::DbWriter, ());
let p = publication.lock();
let s = state.lock();
drop(p);
drop(s);
let _db = db.lock();
drop(_db);
let _p = publication.lock();
}
#[test]
fn a_try_lock_is_never_refused_but_still_counts() {
let state = Ranked::new(Rank::State, ());
let db = Ranked::new(Rank::DbWriter, ());
let _db = db.lock();
let s = state.try_lock().expect("free");
drop(_db);
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _ = Ranked::new(Rank::SharedPublication, ()).lock();
}));
drop(s);
assert!(result.is_err(), "the try_lock'd State still counts as held");
}
}
-597
View File
@@ -1,597 +0,0 @@
//! A [`DriveApi`] that counts and times every call it forwards.
//!
//! Wrapping the client in [`Counted`] answers "what is the daemon asking Drive,
//! and how long does Drive take" without a debugger or a log at debug level:
//! [`CallStats::snapshot`] gives, per kind of call, how many were made, how
//! many failed, and their total and longest time. The diagnostics report shows
//! it.
//!
//! A streaming call (a batch move, restore or delete) is counted once when it
//! starts. Its time is not measured, because the stream outlives the call.
use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use proton_drive_rs::proton_sdk::account::Quota;
use proton_drive_rs::proton_sdk::error::Result;
use proton_drive_rs::proton_sdk::ids::{DriveEventId, NodeUid, ShareId};
use proton_drive_rs::{
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeMoveItem,
Thumbnail, ThumbnailType, TrashedNode,
};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
/// Every kind of call [`DriveApi`] makes, one per method.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DriveCall {
GetMyFilesFolder,
ContextShareId,
GetNode,
EnumerateNodes,
EnumerateNodesLight,
EnumerateChildren,
EnumerateEvents,
InvalidateCaches,
CreateFolder,
UploadFile,
UploadFileFrom,
UploadFileReplacingDraft,
UploadNewRevision,
OpenRevision,
DownloadThumbnail,
DownloadFile,
DownloadRevision,
RenameNode,
MoveNode,
CopyNode,
GetAvailableName,
MoveNodes,
TrashNodes,
RestoreNodes,
RestoreNodesStreaming,
DeleteNodes,
EnumerateTrash,
EmptyTrash,
EnumerateTrashedNodes,
Quota,
EnumerateDevices,
CreateDevice,
}
impl DriveCall {
pub const ALL: [DriveCall; 32] = [
DriveCall::GetMyFilesFolder,
DriveCall::ContextShareId,
DriveCall::GetNode,
DriveCall::EnumerateNodes,
DriveCall::EnumerateNodesLight,
DriveCall::EnumerateChildren,
DriveCall::EnumerateEvents,
DriveCall::InvalidateCaches,
DriveCall::CreateFolder,
DriveCall::UploadFile,
DriveCall::UploadFileFrom,
DriveCall::UploadFileReplacingDraft,
DriveCall::UploadNewRevision,
DriveCall::OpenRevision,
DriveCall::DownloadThumbnail,
DriveCall::DownloadFile,
DriveCall::DownloadRevision,
DriveCall::RenameNode,
DriveCall::MoveNode,
DriveCall::CopyNode,
DriveCall::GetAvailableName,
DriveCall::MoveNodes,
DriveCall::TrashNodes,
DriveCall::RestoreNodes,
DriveCall::RestoreNodesStreaming,
DriveCall::DeleteNodes,
DriveCall::EnumerateTrash,
DriveCall::EmptyTrash,
DriveCall::EnumerateTrashedNodes,
DriveCall::Quota,
DriveCall::EnumerateDevices,
DriveCall::CreateDevice,
];
/// The name the diagnostics report shows: the client method's own.
pub fn name(self) -> &'static str {
match self {
DriveCall::GetMyFilesFolder => "get_my_files_folder",
DriveCall::ContextShareId => "context_share_id",
DriveCall::GetNode => "get_node",
DriveCall::EnumerateNodes => "enumerate_nodes",
DriveCall::EnumerateNodesLight => "enumerate_nodes_light",
DriveCall::EnumerateChildren => "enumerate_folder_children_node_uids",
DriveCall::EnumerateEvents => "enumerate_events",
DriveCall::InvalidateCaches => "invalidate_caches_for_event",
DriveCall::CreateFolder => "create_folder",
DriveCall::UploadFile => "upload_file",
DriveCall::UploadFileFrom => "upload_file_from",
DriveCall::UploadFileReplacingDraft => "upload_file_replacing_draft_from",
DriveCall::UploadNewRevision => "upload_new_revision_from",
DriveCall::OpenRevision => "open_revision",
DriveCall::DownloadThumbnail => "download_thumbnail",
DriveCall::DownloadFile => "download_file_to",
DriveCall::DownloadRevision => "download_revision_to",
DriveCall::RenameNode => "rename_node",
DriveCall::MoveNode => "move_node",
DriveCall::CopyNode => "copy_node",
DriveCall::GetAvailableName => "get_available_name",
DriveCall::MoveNodes => "move_nodes_streaming",
DriveCall::TrashNodes => "trash_nodes",
DriveCall::RestoreNodes => "restore_nodes",
DriveCall::RestoreNodesStreaming => "restore_nodes_streaming",
DriveCall::DeleteNodes => "delete_nodes_streaming",
DriveCall::EnumerateTrash => "enumerate_trash_node_uids",
DriveCall::EmptyTrash => "empty_trash",
DriveCall::EnumerateTrashedNodes => "enumerate_trashed_nodes_light",
DriveCall::Quota => "quota",
DriveCall::EnumerateDevices => "enumerate_devices",
DriveCall::CreateDevice => "create_device",
}
}
}
/// One kind of call, as [`CallStats::snapshot`] reports it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CallStat {
pub call: DriveCall,
pub count: u64,
pub errors: u64,
pub total: Duration,
pub longest: Duration,
}
#[derive(Default)]
struct Counter {
count: AtomicU64,
errors: AtomicU64,
total_us: AtomicU64,
longest_us: AtomicU64,
}
/// The counts behind a [`Counted`] drive, shared with whoever reports them.
pub struct CallStats {
counters: [Counter; DriveCall::ALL.len()],
}
impl Default for CallStats {
fn default() -> Self {
Self {
counters: std::array::from_fn(|_| Counter::default()),
}
}
}
impl CallStats {
fn record(&self, call: DriveCall, failed: bool, took: Option<Duration>) {
let counter = &self.counters[call as usize];
counter.count.fetch_add(1, Ordering::Relaxed);
if failed {
counter.errors.fetch_add(1, Ordering::Relaxed);
}
if let Some(took) = took {
let us = u64::try_from(took.as_micros()).unwrap_or(u64::MAX);
counter.total_us.fetch_add(us, Ordering::Relaxed);
counter.longest_us.fetch_max(us, Ordering::Relaxed);
}
}
/// Every kind of call made at least once, in [`DriveCall::ALL`] order.
pub fn snapshot(&self) -> Vec<CallStat> {
DriveCall::ALL
.iter()
.filter_map(|&call| {
let counter = &self.counters[call as usize];
let count = counter.count.load(Ordering::Relaxed);
(count > 0).then(|| CallStat {
call,
count,
errors: counter.errors.load(Ordering::Relaxed),
total: Duration::from_micros(counter.total_us.load(Ordering::Relaxed)),
longest: Duration::from_micros(counter.longest_us.load(Ordering::Relaxed)),
})
})
.collect()
}
}
/// A [`DriveApi`] that forwards to `inner` and records every call in `stats`.
pub struct Counted {
inner: Arc<dyn DriveApi>,
stats: Arc<CallStats>,
}
impl Counted {
pub fn new(inner: Arc<dyn DriveApi>, stats: Arc<CallStats>) -> Self {
Self { inner, stats }
}
async fn timed<T>(
&self,
call: DriveCall,
future: impl std::future::Future<Output = Result<T>>,
) -> Result<T> {
let started = Instant::now();
let result = future.await;
self.stats
.record(call, result.is_err(), Some(started.elapsed()));
result
}
}
#[async_trait]
impl DriveApi for Counted {
async fn get_my_files_folder(&self) -> Result<Node> {
self.timed(
DriveCall::GetMyFilesFolder,
self.inner.get_my_files_folder(),
)
.await
}
async fn context_share_id(&self, uid: &NodeUid) -> Result<ShareId> {
self.timed(DriveCall::ContextShareId, self.inner.context_share_id(uid))
.await
}
async fn get_node(&self, uid: &NodeUid) -> Result<Option<Node>> {
self.timed(DriveCall::GetNode, self.inner.get_node(uid))
.await
}
async fn enumerate_nodes(&self, uids: &[NodeUid]) -> Result<Vec<Node>> {
self.timed(DriveCall::EnumerateNodes, self.inner.enumerate_nodes(uids))
.await
}
async fn enumerate_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<Node>> {
self.timed(
DriveCall::EnumerateNodesLight,
self.inner.enumerate_nodes_light(uids),
)
.await
}
async fn enumerate_folder_children_node_uids(
&self,
folder_uid: &NodeUid,
) -> Result<Vec<NodeUid>> {
self.timed(
DriveCall::EnumerateChildren,
self.inner.enumerate_folder_children_node_uids(folder_uid),
)
.await
}
async fn enumerate_events(
&self,
scope: &DriveEventScopeId,
cursor: Option<&DriveEventId>,
) -> Result<Vec<DriveEvent>> {
self.timed(
DriveCall::EnumerateEvents,
self.inner.enumerate_events(scope, cursor),
)
.await
}
async fn invalidate_caches_for_event(&self, event: &DriveEvent) -> Result<()> {
self.timed(
DriveCall::InvalidateCaches,
self.inner.invalidate_caches_for_event(event),
)
.await
}
async fn create_folder(
&self,
parent_uid: &NodeUid,
name: &str,
last_modification_time: Option<i64>,
) -> Result<NodeUid> {
self.timed(
DriveCall::CreateFolder,
self.inner
.create_folder(parent_uid, name, last_modification_time),
)
.await
}
async fn upload_file(
&self,
parent_uid: &NodeUid,
name: &str,
media_type: &str,
contents: &[u8],
) -> Result<NodeUid> {
self.timed(
DriveCall::UploadFile,
self.inner
.upload_file(parent_uid, name, media_type, contents),
)
.await
}
async fn upload_file_from_dyn(
&self,
parent_uid: &NodeUid,
name: &str,
media_type: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
aead: bool,
) -> Result<NodeUid> {
self.timed(
DriveCall::UploadFileFrom,
self.inner.upload_file_from_dyn(
parent_uid,
name,
media_type,
reader,
intended_size,
thumbnails,
last_modification_time,
aead,
),
)
.await
}
async fn upload_file_replacing_draft_from_dyn(
&self,
parent_uid: &NodeUid,
name: &str,
media_type: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
aead: bool,
) -> Result<NodeUid> {
self.timed(
DriveCall::UploadFileReplacingDraft,
self.inner.upload_file_replacing_draft_from_dyn(
parent_uid,
name,
media_type,
reader,
intended_size,
thumbnails,
last_modification_time,
aead,
),
)
.await
}
async fn upload_new_revision_from_dyn(
&self,
file_uid: &NodeUid,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<()> {
self.timed(
DriveCall::UploadNewRevision,
self.inner.upload_new_revision_from_dyn(
file_uid,
reader,
intended_size,
thumbnails,
last_modification_time,
),
)
.await
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
self.timed(DriveCall::OpenRevision, self.inner.open_revision(uid))
.await
}
async fn download_thumbnail(
&self,
uid: &NodeUid,
thumbnail_type: ThumbnailType,
) -> Result<Option<Vec<u8>>> {
self.timed(
DriveCall::DownloadThumbnail,
self.inner.download_thumbnail(uid, thumbnail_type),
)
.await
}
async fn download_file_to_dyn(
&self,
uid: &NodeUid,
output: &mut (dyn Write + Send),
) -> Result<()> {
self.timed(
DriveCall::DownloadFile,
self.inner.download_file_to_dyn(uid, output),
)
.await
}
async fn download_revision_to_dyn(
&self,
file_uid: &NodeUid,
revision_id: &str,
writer: &mut (dyn Write + Send),
) -> Result<()> {
self.timed(
DriveCall::DownloadRevision,
self.inner
.download_revision_to_dyn(file_uid, revision_id, writer),
)
.await
}
async fn rename_node(
&self,
uid: &NodeUid,
new_name: &str,
new_media_type: Option<&str>,
) -> Result<()> {
self.timed(
DriveCall::RenameNode,
self.inner.rename_node(uid, new_name, new_media_type),
)
.await
}
async fn move_node(&self, uid: &NodeUid, new_parent: &NodeUid) -> Result<()> {
self.timed(DriveCall::MoveNode, self.inner.move_node(uid, new_parent))
.await
}
async fn copy_node(
&self,
uid: &NodeUid,
new_parent: &NodeUid,
name: Option<&str>,
) -> Result<NodeUid> {
self.timed(
DriveCall::CopyNode,
self.inner.copy_node(uid, new_parent, name),
)
.await
}
async fn get_available_name(
&self,
parent_uid: &NodeUid,
name: &str,
target: AvailableNameTarget,
) -> Result<String> {
self.timed(
DriveCall::GetAvailableName,
self.inner.get_available_name(parent_uid, name, target),
)
.await
}
fn move_nodes_streaming<'a>(
&'a self,
items: Vec<NodeMoveItem>,
new_parent: NodeUid,
) -> OutcomeStream<'a> {
self.stats.record(DriveCall::MoveNodes, false, None);
self.inner.move_nodes_streaming(items, new_parent)
}
async fn trash_nodes(&self, uids: &[NodeUid]) -> Result<NodeOutcomes> {
self.timed(DriveCall::TrashNodes, self.inner.trash_nodes(uids))
.await
}
async fn restore_nodes(&self, uids: &[NodeUid]) -> Result<NodeOutcomes> {
self.timed(DriveCall::RestoreNodes, self.inner.restore_nodes(uids))
.await
}
fn restore_nodes_streaming<'a>(&'a self, uids: &[NodeUid]) -> OutcomeStream<'a> {
self.stats
.record(DriveCall::RestoreNodesStreaming, false, None);
self.inner.restore_nodes_streaming(uids)
}
fn delete_nodes_streaming<'a>(&'a self, uids: &[NodeUid]) -> OutcomeStream<'a> {
self.stats.record(DriveCall::DeleteNodes, false, None);
self.inner.delete_nodes_streaming(uids)
}
async fn enumerate_trash_node_uids(&self) -> Result<Vec<NodeUid>> {
self.timed(
DriveCall::EnumerateTrash,
self.inner.enumerate_trash_node_uids(),
)
.await
}
async fn empty_trash(&self) -> Result<()> {
self.timed(DriveCall::EmptyTrash, self.inner.empty_trash())
.await
}
async fn enumerate_trashed_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<TrashedNode>> {
self.timed(
DriveCall::EnumerateTrashedNodes,
self.inner.enumerate_trashed_nodes_light(uids),
)
.await
}
async fn quota(&self) -> Result<Quota> {
self.timed(DriveCall::Quota, self.inner.quota()).await
}
async fn enumerate_devices(&self) -> Result<Vec<Device>> {
self.timed(DriveCall::EnumerateDevices, self.inner.enumerate_devices())
.await
}
async fn create_device(&self, name: &str, device_type: DeviceType) -> Result<Device> {
self.timed(
DriveCall::CreateDevice,
self.inner.create_device(name, device_type),
)
.await
}
fn landing(&self, uid: &NodeUid) {
self.inner.landing(uid);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_call_has_its_own_counter() {
for (index, call) in DriveCall::ALL.iter().enumerate() {
assert_eq!(*call as usize, index, "{} is out of order", call.name());
}
let names: std::collections::HashSet<_> =
DriveCall::ALL.iter().map(|call| call.name()).collect();
assert_eq!(names.len(), DriveCall::ALL.len());
}
#[test]
fn a_call_is_counted_with_its_failures_and_time() {
let stats = CallStats::default();
stats.record(DriveCall::GetNode, false, Some(Duration::from_millis(30)));
stats.record(DriveCall::GetNode, true, Some(Duration::from_millis(10)));
stats.record(DriveCall::DeleteNodes, false, None);
assert_eq!(
stats.snapshot(),
vec![
CallStat {
call: DriveCall::GetNode,
count: 2,
errors: 1,
total: Duration::from_millis(40),
longest: Duration::from_millis(30),
},
CallStat {
call: DriveCall::DeleteNodes,
count: 1,
errors: 0,
total: Duration::ZERO,
longest: Duration::ZERO,
},
]
);
}
}
-2
View File
@@ -33,8 +33,6 @@ use proton_drive_rs::{
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
};
pub mod counted;
/// One outcome per node of a batch request; see [`ProtonDriveClient::trash_nodes`].
pub type NodeOutcomes = Vec<(NodeUid, Result<()>)>;
+2 -7
View File
@@ -17,7 +17,6 @@ use pdfs_core::control::{
ActivityKind, DeviceInfo, JobItem, MountKind, MountSpec, SyncFolderInfo, SyncPhase,
SyncProgress,
};
use pdfs_core::lockrank::{Rank, Ranked};
use pdfs_core::mounts::MountMode;
use pdfs_core::profile::PROFILE_DIR_NAME;
use pdfs_core::{CoreError, CoreResult};
@@ -699,12 +698,8 @@ impl Core {
}
/// The lock guarding sync-folder `id` against concurrent reconcile/mode-switch.
pub(crate) fn sync_lock(&self, id: i64) -> Arc<Ranked<()>> {
self.sync_locks
.lock()
.entry(id)
.or_insert_with(|| Arc::new(Ranked::new(Rank::SyncFolder, ())))
.clone()
pub(crate) fn sync_lock(&self, id: i64) -> Arc<Mutex<()>> {
self.sync_locks.lock().entry(id).or_default().clone()
}
/// Remove a synced folder from the sync set. `delete_remote` also deletes its
+1 -13
View File
@@ -18,7 +18,7 @@ use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};
use parking_lot::Mutex;
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, WorkerState};
use pdfs_core::control::{Diagnostics, InflightRequest, WorkerState};
use super::Core;
@@ -164,18 +164,6 @@ impl Core {
control_handler_limit: super::control::handler_limit(),
pending_ops: self.pending_ops_quickly(),
sync: Some(self.sync_engine.report()),
drive_calls: self
.drive_calls
.snapshot()
.into_iter()
.map(|stat| DriveCallStat {
call: stat.call.name().to_owned(),
count: stat.count,
errors: stat.errors,
total_ms: u64::try_from(stat.total.as_millis()).unwrap_or(u64::MAX),
longest_ms: u64::try_from(stat.longest.as_millis()).unwrap_or(u64::MAX),
})
.collect(),
}
}
+3 -6
View File
@@ -32,7 +32,6 @@
//! remainder of the file is pulled from the remote — lazily, at commit.
use parking_lot::{Condvar, Mutex};
use pdfs_core::lockrank::{Rank, Ranked};
use std::collections::{HashMap, HashSet, VecDeque};
use std::ffi::OsStr;
use std::fs::File;
@@ -507,8 +506,6 @@ struct Core {
/// downloads, renames, moves and trashes. The real client in production, an
/// in-memory Drive in the simulation tests. See [`drive`].
drive: Arc<dyn DriveApi>,
/// What [`Core::drive`] has been asked, for the diagnostics report.
drive_calls: Arc<pdfs_drive::counted::CallStats>,
/// The concrete client, for what [`DriveApi`] does not cover: sharing,
/// Photos, devices, invitations and public links.
client: ProtonDriveClient,
@@ -521,7 +518,7 @@ struct Core {
/// directory belongs exclusively to the primary My Files mount.
primary: bool,
/// The one tree every mount of the daemon serves from.
state: Arc<Ranked<State>>,
state: Arc<Mutex<State>>,
/// The tree inode this mount's session is rooted at, set when the session
/// is built ([`ProtonFs::new`]). Each fork has its own cell.
root: Arc<OnceLock<u64>>,
@@ -558,7 +555,7 @@ struct Core {
db: Arc<Db>,
/// Serializes only shared-list publication and access-loss invalidation.
/// Network calls happen before taking it.
shared_publication: Arc<Ranked<()>>,
shared_publication: Arc<Mutex<()>>,
/// Invalidates in-flight shared responses when access/list events arrive.
shared_generation: Arc<AtomicU64>,
/// Successful refreshes suppress retries even if persisting their timestamp
@@ -772,7 +769,7 @@ struct Core {
/// FUSE over it, so it must never overlap a pass that is walking and
/// uploading that same tree — the engine would upload files as they vanish
/// and then walk the FUSE mount as if it were local.
sync_locks: Arc<Mutex<HashMap<i64, Arc<Ranked<()>>>>>,
sync_locks: Arc<Mutex<HashMap<i64, Arc<Mutex<()>>>>>,
/// Per-sync-folder paths the last pass could not read, so the activity feed
/// says so when the set changes rather than on every poll (B196).
sync_unscanned: Arc<Mutex<HashMap<i64, Vec<String>>>>,
+2 -12
View File
@@ -466,12 +466,6 @@ pub(crate) fn mount_with(
// Start the uptime clock here rather than at the first `pdfs diagnostics`,
// so the age it reports is the daemon's own.
super::diagnostics::start_clock();
// Count every call to Drive from the first, the root lookup included.
let drive_calls = Arc::new(pdfs_drive::counted::CallStats::default());
let drive: Arc<dyn DriveApi> = Arc::new(pdfs_drive::counted::Counted::new(
drive,
drive_calls.clone(),
));
check_mountpoint(mountpoint)?;
let (root, start) = fetch_or_recall_root(drive.as_ref(), &rt, &db)?;
let online = start == Start::Online;
@@ -493,17 +487,13 @@ pub(crate) fn mount_with(
gallery_session.map(|session| Arc::new(super::gallery::Gallery::new(gallery_dir, session)));
let core = Core {
drive,
drive_calls,
client,
gallery,
rt: rt.clone(),
maintenance: Arc::new(Mutex::new(Default::default())),
primary_root_uid: root.uid.clone(),
primary: true,
state: Arc::new(Ranked::new(
Rank::State,
State::new(db.clone(), share_access),
)),
state: Arc::new(Mutex::new(State::new(db.clone(), share_access))),
root: Arc::new(OnceLock::new()),
cache: Arc::new(cache),
readers: Arc::new(Mutex::new(HashMap::new())),
@@ -514,7 +504,7 @@ pub(crate) fn mount_with(
prefetch_budget: Arc::new(tokio::sync::Semaphore::new(PREFETCH_BUDGET)),
workers: Arc::new(Workers::new(FUSE_WORKERS)?),
db,
shared_publication: Arc::new(Ranked::new(Rank::SharedPublication, ())),
shared_publication: Arc::new(Mutex::new(())),
shared_generation: Arc::new(AtomicU64::new(0)),
shared_refresh_deadlines: Arc::new(Mutex::new(SharedRefreshDeadlines::default())),
online: Arc::new(AtomicBool::new(online)),
+2 -2
View File
@@ -18,6 +18,7 @@ use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use parking_lot::Mutex;
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::{StoredSyncEntry, StoredSyncFolder};
use proton_drive_rs::NodeKind;
@@ -199,8 +200,7 @@ impl Core {
.collect();
ids.sort_unstable();
ids.dedup();
let locks: Vec<Arc<pdfs_core::lockrank::Ranked<()>>> =
ids.iter().map(|&id| self.sync_lock(id)).collect();
let locks: Vec<Arc<Mutex<()>>> = ids.iter().map(|&id| self.sync_lock(id)).collect();
let mut guards = Vec::with_capacity(locks.len());
for lock in &locks {
guards.push(lock.try_lock_for(MIRROR_LOCK_WAIT).ok_or_else(|| {
-209
View File
@@ -30,16 +30,6 @@ const MOUNT_DEADLINE: Duration = Duration::from_secs(20);
/// How long a restart may wait for the last run to let go of its database.
const LAST_RUN_DEADLINE: Duration = Duration::from_secs(30);
/// How long a stop may wait for the mount to end before it aborts the FUSE
/// connection. A mount that stops answering otherwise hangs the test, and the
/// whole run with it (`docs/BUGS.md` B297).
const STOP_DEADLINE: Duration = Duration::from_secs(60);
/// How long one daemon may live. Past this, its FUSE connection is aborted, so
/// a test blocked on a request the mount never answers fails with `ENOTCONN`
/// instead of hanging the run. The whole suite takes about 15 minutes in CI.
const LIFETIME_LIMIT: Duration = Duration::from_secs(20 * 60);
pub(crate) struct Daemon {
pub(crate) client: FakeClient,
pub(crate) mountpoint: PathBuf,
@@ -48,13 +38,6 @@ pub(crate) struct Daemon {
stop: SyncSender<()>,
mount: Option<JoinHandle<io::Result<MountOutcome>>>,
rt: Option<tokio::runtime::Runtime>,
/// The mount's FUSE connection, as `/sys/fs/fuse/connections` names it.
connection: u64,
/// Dropped with the daemon, which ends the thread enforcing
/// [`LIFETIME_LIMIT`].
_alive: std::sync::mpsc::Sender<()>,
/// Dropped after `shut_down`, so the next simulation waits for this one.
_turn: Turn,
}
impl Daemon {
@@ -62,7 +45,6 @@ impl Daemon {
/// A later start on the same `dir` is a restart: it finds the queue, the
/// cache and the database the last run left.
pub(crate) fn start(dir: &Path, client: FakeClient) -> io::Result<Self> {
let turn = Turn::take();
log_to_test_output();
isolate_from_the_developer();
let mountpoint = dir.join("mnt");
@@ -130,27 +112,6 @@ impl Daemon {
}
std::thread::sleep(Duration::from_millis(20));
}
let connection = {
use std::os::unix::fs::MetadataExt;
u64::from(libc::minor(std::fs::metadata(&mountpoint)?.dev()))
};
let (alive, dropped) = std::sync::mpsc::channel::<()>();
{
let mountpoint = mountpoint.clone();
std::thread::Builder::new()
.name("sim-lifetime".into())
.spawn(move || {
if let Err(std::sync::mpsc::RecvTimeoutError::Timeout) =
dropped.recv_timeout(LIFETIME_LIMIT)
{
eprintln!(
"{}: the daemon outlived {LIFETIME_LIMIT:?}; aborting its FUSE connection",
mountpoint.display()
);
abort_connection(connection);
}
})?;
}
Ok(Self {
client,
mountpoint,
@@ -159,9 +120,6 @@ impl Daemon {
stop,
mount: Some(mount),
rt: Some(rt),
connection,
_alive: alive,
_turn: turn,
})
}
@@ -257,21 +215,6 @@ impl Daemon {
return Ok(MountOutcome::Shutdown);
};
let _ = self.stop.try_send(());
if !wait_until(STOP_DEADLINE, || mount.is_finished()) {
abort_connection(self.connection);
let _ = wait_until(STOP_DEADLINE, || mount.is_finished());
if !mount.is_finished() {
// Joining would hang the run; leak the thread instead.
return Err(io::Error::other(format!(
"{}: the mount did not end after its FUSE connection was aborted",
self.mountpoint.display()
)));
}
return Err(io::Error::other(format!(
"{}: the mount did not stop within {STOP_DEADLINE:?}, so its FUSE connection was aborted",
self.mountpoint.display()
)));
}
let outcome = mount
.join()
.unwrap_or_else(|_| Err(io::Error::other("mount thread panicked")));
@@ -288,61 +231,6 @@ impl Drop for Daemon {
}
}
/// Abort FUSE connection `connection`: every request waiting on it fails with
/// `ENOTCONN`, and the mount's session ends. The connection belongs to the
/// user who mounted it, so this needs no privileges.
fn abort_connection(connection: u64) {
let path = format!("/sys/fs/fuse/connections/{connection}/abort");
if let Err(error) = std::fs::write(&path, "1") {
eprintln!("could not abort {path}: {error}");
}
}
/// One simulation's turn to run daemons. The simulations share the process:
/// its environment (see [`isolate_from_the_developer`]), its cores and its
/// mounts. Run side by side, as plain `cargo test` does, they miss their
/// deadlines and can hang (`docs/BUGS.md` B297). So a daemon started on one
/// test thread waits while another test thread still has one.
struct Turn;
/// The test thread whose daemons run now, and how many it has.
static TURN: parking_lot::Mutex<Option<(std::thread::ThreadId, usize)>> =
parking_lot::Mutex::new(None);
static TURN_FREE: parking_lot::Condvar = parking_lot::Condvar::new();
impl Turn {
fn take() -> Self {
let me = std::thread::current().id();
let mut turn = TURN.lock();
loop {
match turn.as_mut() {
None => {
*turn = Some((me, 1));
return Turn;
}
Some((owner, count)) if *owner == me => {
*count += 1;
return Turn;
}
Some(_) => TURN_FREE.wait(&mut turn),
}
}
}
}
impl Drop for Turn {
fn drop(&mut self) {
let mut turn = TURN.lock();
if let Some((_, count)) = turn.as_mut() {
*count -= 1;
if *count == 0 {
*turn = None;
TURN_FREE.notify_all();
}
}
}
}
/// Whether a file system is mounted at `path`: it sits on another device than
/// its parent.
fn is_mounted(path: &Path) -> bool {
@@ -481,63 +369,6 @@ mod tests {
use pdfs_core::control::{RefreshScope, SyncIssue};
use std::collections::BTreeMap;
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_simulation_on_another_thread_waits_for_this_ones_daemons() {
// Side by side, the simulations missed their deadlines and could hang
// on a mount (B297).
let drive = FakeDrive::new();
let first = Daemon::start(&scratch("turn-first"), drive.client(1, Faults::lan())).unwrap();
let second_up = Arc::new(std::sync::atomic::AtomicBool::new(false));
let other = {
let drive = drive.clone();
let second_up = second_up.clone();
std::thread::spawn(move || {
let second =
Daemon::start(&scratch("turn-second"), drive.client(2, Faults::lan())).unwrap();
second_up.store(true, std::sync::atomic::Ordering::SeqCst);
second.stop().unwrap();
})
};
std::thread::sleep(Duration::from_secs(2));
assert!(!second_up.load(std::sync::atomic::Ordering::SeqCst));
// A second daemon on this thread does not wait for the first.
let restarted = first.restart().unwrap();
assert!(!second_up.load(std::sync::atomic::Ordering::SeqCst));
restarted.stop().unwrap();
other.join().unwrap();
assert!(second_up.load(std::sync::atomic::Ordering::SeqCst));
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn diagnostics_count_the_calls_made_to_drive() {
let drive = FakeDrive::new();
let daemon =
Daemon::start(&scratch("drive-calls"), drive.client(1, Faults::lan())).unwrap();
std::fs::write(daemon.mountpoint.join("a.txt"), b"a").unwrap();
assert!(wait_until(Duration::from_secs(30), || drive
.tree()
.contains_key("a.txt")));
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
else {
panic!("no diagnostics");
};
let calls: BTreeMap<_, _> = diagnostics
.drive_calls
.iter()
.map(|stat| (stat.call.as_str(), stat))
.collect();
assert!(calls.contains_key("get_my_files_folder"), "{calls:?}");
let uploads = calls
.get("upload_file_from")
.or_else(|| calls.get("upload_file_replacing_draft_from"))
.unwrap_or_else(|| panic!("no upload counted: {calls:?}"));
assert!(uploads.count >= 1);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_daemon_on_the_fake_drive_syncs_both_ways() {
@@ -2110,46 +1941,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_mirror_edit_whose_reply_was_lost_is_not_kept_as_a_conflict() {
// Drive made the revision, but the answer never came back. The next
// pass saw both sides changed since the baseline and kept a conflict
// copy of this computer's own edit.
let drive = FakeDrive::new();
let dir = scratch("mirror-lost-revision-reply");
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
let local = dir.join("local");
assert!(wait_until(Duration::from_secs(30), || drive
.lookup("mirrored/a.txt")
.is_some()));
assert!(wait_for_pass(&daemon, folder, 0));
client.lose_reply_to_next_revision();
std::fs::write(local.join("a.txt"), b"two").unwrap();
assert!(wait_until(Duration::from_secs(30), || {
on_drive(&drive, "mirrored/a.txt").is_some_and(|bytes| bytes == b"two")
}));
daemon
.request(&Request::SyncNow { id: Some(folder) })
.unwrap();
assert!(wait_for_pass(&daemon, folder, 0));
daemon
.request(&Request::SyncNow { id: Some(folder) })
.unwrap();
assert!(wait_for_pass(&daemon, folder, 0));
assert!(conflict_copies(&local, "a").is_empty());
assert!(
!drive.tree().keys().any(|k| k.contains("sync-conflict")),
"{:?}",
drive.tree()
);
assert_eq!(std::fs::read(local.join("a.txt")).unwrap(), b"two");
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_revision_made_during_a_mirror_download_still_arrives() {
+3 -3
View File
@@ -374,12 +374,12 @@ impl DbWrite {
/// write still happens synchronously on this thread before the caller proceeds,
/// so a read that follows a mutation still sees it.
pub(crate) struct StateGuard<'a> {
guard: Option<pdfs_core::lockrank::RankedGuard<'a, State>>,
guard: Option<parking_lot::MutexGuard<'a, State>>,
db: &'a Arc<Db>,
}
impl<'a> StateGuard<'a> {
pub(crate) fn new(guard: pdfs_core::lockrank::RankedGuard<'a, State>, db: &'a Arc<Db>) -> Self {
pub(crate) fn new(guard: parking_lot::MutexGuard<'a, State>, db: &'a Arc<Db>) -> Self {
Self {
guard: Some(guard),
db,
@@ -1641,7 +1641,7 @@ mod tests {
let (st, _dir) = state();
let db = st.db.clone();
let root = uid("root").to_string();
let state = pdfs_core::lockrank::Ranked::new(pdfs_core::lockrank::Rank::State, st);
let state = parking_lot::Mutex::new(st);
{
let mut guard = StateGuard::new(state.lock(), &db);
guard.intern(0, node("root", "none", "My Files", true));
+7 -8
View File
@@ -24,7 +24,6 @@
//! and never name a submodule.
use parking_lot::Mutex;
use pdfs_core::lockrank::{Rank, Ranked, RankedGuard};
use rusqlite::Connection;
use pdfs_core::{Error, Result};
@@ -97,7 +96,7 @@ const WAL_AUTOCHECKPOINT_PAGES: i64 = 500;
/// Cheap to wrap in an `Arc`; clone the `Arc`, not this. All access goes through
/// the inner `Mutex<Connection>`.
pub struct Db {
conn: Ranked<Connection>,
conn: Mutex<Connection>,
/// Read-only connections for `SELECT`-only methods. `None` for an in-memory
/// database, where a second connection would open a different, empty one —
/// those fall back to the write connection.
@@ -154,7 +153,7 @@ impl ReadPool {
/// for `self.read()?` and nothing else.
pub(super) struct Reader<'a> {
pooled: Option<Connection>,
writer: Option<RankedGuard<'a, Connection>>,
writer: Option<parking_lot::MutexGuard<'a, Connection>>,
pool: Option<&'a ReadPool>,
}
@@ -186,10 +185,10 @@ impl Drop for Reader<'_> {
/// reachable; losing that row loses a write `close()` already reported as
/// done. A FULL commit syncs the WAL, which covers every NORMAL commit before
/// it as well.
pub(super) struct Durable<'a>(RankedGuard<'a, Connection>);
pub(super) struct Durable<'a>(parking_lot::MutexGuard<'a, Connection>);
impl<'a> Durable<'a> {
pub(super) fn new(conn: RankedGuard<'a, Connection>) -> Result<Self> {
pub(super) fn new(conn: parking_lot::MutexGuard<'a, Connection>) -> Result<Self> {
conn.pragma_update(None, "synchronous", "FULL")?;
Ok(Self(conn))
}
@@ -285,7 +284,7 @@ impl Db {
Err(e) => return Err(e),
};
let db = Self {
conn: Ranked::new(Rank::DbWriter, conn),
conn: Mutex::new(conn),
// No pool for `:memory:`. A second connection to that name is a
// second, empty database rather than another view of this one, so
// every routed read would find a schema that does not exist.
@@ -381,7 +380,7 @@ impl Db {
conn.pragma_update(None, "wal_autocheckpoint", WAL_AUTOCHECKPOINT_PAGES)?;
let db = Self {
conn: Ranked::new(Rank::DbWriter, conn),
conn: Mutex::new(conn),
readers: None,
_single_writer: None,
};
@@ -405,7 +404,7 @@ impl Db {
// connection unless explicitly enabled.
conn.pragma_update(None, "foreign_keys", "ON")?;
let db = Self {
conn: Ranked::new(Rank::DbWriter, conn),
conn: Mutex::new(conn),
readers: None,
_single_writer: None,
};
+9 -20
View File
@@ -544,15 +544,15 @@ pub fn plan_file(
(false, false) => FilePlan::Unchanged,
(true, false) => FilePlan::UploadRevision,
(false, true) => FilePlan::Download,
// Both sides changed. When the sizes match and Drive has a digest,
// the apply step hashes the local file first, and records a
// baseline without a transfer if they are the same bytes. Without
// a baseline that is a first sync of a file already on both sides.
// With one, it is an upload whose reply was lost: Drive holds this
// computer's own edit, and a conflict copy of it would be a copy of
// itself. Different bytes, divergent sizes, or no digest stay a
// real conflict: a missing digest proves nothing.
(true, true) if l.size == r.size && r.sha1.is_some() => FilePlan::AdoptBaseline,
// With a baseline, both-changed is a genuine concurrent edit and must
// be preserved as a conflict. Without one, "both changed" only means
// this is the first sync and there was nothing to compare to: when the
// sizes match and Drive has a digest to compare against, the apply
// step hashes the local file before adopting it. Divergent sizes, or
// no digest, stay a real conflict: a missing digest proves nothing.
(true, true) if baseline.is_none() && l.size == r.size && r.sha1.is_some() => {
FilePlan::AdoptBaseline
}
(true, true) => FilePlan::Conflict,
},
(Some(_), None) if baseline.is_none() || local_changed => FilePlan::UploadNew,
@@ -790,17 +790,6 @@ mod file_plan_tests {
plan_file(Some(&edited), Some(&newer), Some(&base)),
FilePlan::Conflict
);
// The same size with a digest is hashed first: it may be this
// computer's own upload whose reply was lost.
let digested = RemoteItem {
revision: Some("r2".into()),
sha1: Some("da39a3ee".into()),
..remote(30, 40)
};
assert_eq!(
plan_file(Some(&local(11, 40)), Some(&digested), Some(&base)),
FilePlan::AdoptBaseline
);
// A row from before schema 44 has no id to compare, and a node read
// without one says nothing: both fall back to the signature.
-56
View File
@@ -672,60 +672,4 @@ local state per node as each batch lands.
- **Mirrored folders** still have their own engine (§7). They move onto the local tree and the
queue after that.
### 4.0: from one daemon to composed services
The daemon grew one feature at a time inside `pdfs-fuse`, which now holds the FUSE handlers, the
drain, the sync engine, photos, thumbnails, takeout, devices, the control server, the supervisor
and diagnostics. Everything shares one `Core` struct (`lib.rs`) with over seventy fields, so any
code can take any lock in any order, and a new feature can deadlock an old one (`docs/BUGS.md`
B110, the cold size upgrade, the diagnostics threads stuck behind the database writer). Over
forty threads are spawned ad hoc, each with its own stop and join rules. The only real seam is
`DriveApi` (`drive.rs`), which is what lets the simulation tests run against a fake Drive.
4.0 splits the daemon into services that each own their state and threads, behind ports that can
be swapped and tested alone. Dependencies point inward; inner crates never see GTK, `fuser`,
`libc` error numbers or SDK node types.
```
apps pdfs-cli, pdfs-gui talk to the daemon over the control socket only
daemon pdfs-daemon builds the services, supervisor, diagnostics, control server
adapters pdfs-fuse (Linux FUSE), pdfs-local (watch, scan, place), pdfs-drive (SDK adapter, fake Drive)
services pdfs-sync (mirrors), pdfs-vfs (mounted files: objects, handles, generations), photos, ...
base pdfs-store (SQLite, migrations), pdfs-core (config, protocol, ids, errors)
```
Six rules hold that shape:
1. **Ownership.** Each service owns its state and its threads. Services talk through typed ports
or messages, never through another service's lock.
2. **Lifecycle.** Each service starts from its dependencies and returns a handle with `stop`, a
bounded `join` and a health snapshot. The supervisor starts the services in dependency order
and stops them in reverse. No thread is left detached.
3. **No lock across a boundary.** No lock is held across an SDK call, a FUSE reply or kernel
notification, a blocking send or a join. Debug builds check the order of the nested locks
that remain.
4. **Short transactions.** A read never falls back to the writer connection. Diagnostics use
their own connection and report "busy" instead of waiting.
5. **Absence is a fact, not a gap.** A locked, unreadable, partly listed or ignored path is never
read as deleted, whether in sync, in the mount or behind a locked store.
6. **Headless tests.** Each service runs in tests without a mount, a desktop or a Proton account:
sync against the fake Drive and a temporary directory, the mounted-files service against a
fake store.
The work goes in steps. Each ships the same behaviour with the simulation tests green:
| Step | What |
|---|---|
| 0 | Finish what is open: the resumable walk of Drive's changed folders (B294), the ignored `set_len` error on a resize (B295), a reopen after close that depends on the single dispatch thread, and no conflict copy when a lost reply left the same content on Drive |
| 1 | Seams and measurement: a `DriveApi` decorator that counts calls and their time, diagnostics that cannot hang (B296), lock-order checks, a live one-edit benchmark |
| 2 | Move code into `pdfs-store`, `pdfs-drive` and `pdfs-sync` without changing it |
| 3 | Split `Core` into services with a lifecycle, under a supervisor in `pdfs-daemon` |
| 4 | Sync on evidence: a local dirty set, typed absence, a delete guard over the whole walk, and a durable intent for each effect, first in shadow mode |
| 5 | `pdfs-vfs`: open files, then directories and renames, behind the FUSE adapter |
| 6 | One admission policy for mirrors, reads and writeback |
Steps 0 to 3 are 4.0.0. Steps 4 to 6 follow in 4.x, one service at a time. Out of scope for
now: an encrypted local vault (full-disk encryption covers a copied disk today), Windows and
macOS adapters, and a separate repository for the sync engine.
[ROADMAP.md](ROADMAP.md) tracks these and the rest of the planned work.
-77
View File
@@ -108,8 +108,6 @@ a live account since.
| Entry | Title |
|---|---|
| [B298](#b298--a-synced-folder-edit-whose-upload-lost-its-answer-is-kept-as-a-conflict-copy-of-itself) | A synced-folder edit whose upload lost its answer is kept as a conflict copy of itself |
| [B297](#b297--the-simulations-fail-and-hang-when-run-in-parallel-and-nothing-stops-that) | The simulations fail and hang when run in parallel, and nothing stops that |
| [B296](#b296--a-busy-database-stalls-reads-and-piles-up-diagnostics-threads) | A busy database stalls reads, and piles up diagnostics threads |
| [B294](#b294--a-mirror-folder-too-large-to-finish-in-one-run-never-syncs-and-holds-back-the-others) | A mirror folder too large to finish in one run never syncs, and holds back the others |
| [B66](#b66--local-only-pending-data-is-not-protected-at-shutdown-high-21) | Local-only pending data is not protected at shutdown (HIGH-21) |
@@ -310,7 +308,6 @@ a live account since.
| Entry | Title |
|---|---|
| [B295](#b295--a-resize-the-scratch-file-refused-still-succeeded) | A resize the scratch file refused still succeeded |
| [B293](#b293--a-large-trash-never-lists-and-empty-trash-never-empties-it) | A large trash never lists, and Empty Trash never empties it |
| [B292](#b292--two-programs-changing-settings-at-once-lose-one-of-the-changes) | Two programs changing settings at once lose one of the changes |
| [B290](#b290--reopening-the-database-right-after-closing-it-can-be-refused-as-another-daemon) | Reopening the database right after closing it can be refused as another daemon |
@@ -401,80 +398,6 @@ a live account since.
Newest first.
### B298 — A synced-folder edit whose upload lost its answer is kept as a conflict copy of itself
**Status:** Fixed (unverified)
**Found:** 2026-11-26, in the 4.0 review of the mirror planner. B155 fixed the same symptom in
the mount's drain; the mirror engine has its own path.
**Where:** `plan_file` in `crates/pdfs-sync/src/planner.rs`
**Repro:** Edit a file in a mirrored folder. Drive makes the new revision, but the answer to
the upload never comes back. The next pass sees the local file changed since the baseline,
and the file on Drive changed too, so it keeps the local file as `a (sync-conflict …).txt`
and downloads Drive's copy, which holds the same bytes. The simulation
`a_mirror_edit_whose_reply_was_lost_is_not_kept_as_a_conflict` does this with a lost
revision reply.
**Cause.** The planner hashed the local file against Drive's digest only on a first sync,
with no baseline. With a baseline, both sides changed always meant a conflict.
**Fix.** When both sides changed, the sizes match and Drive has a digest, the planner asks
for the same hash check whether or not there is a baseline. The same bytes record a new
baseline without a transfer. Different bytes take the conflict path as before.
**Verified:** `a_mirror_edit_whose_reply_was_lost_is_not_kept_as_a_conflict`, which fails
without the fix, and the planner test
`a_new_remote_revision_is_a_change_even_at_the_same_mtime_and_size`.
---
### B297 — The simulations fail and hang when run in parallel, and nothing stops that
**Status:** Fixed (unverified)
**Found:** 2026-11-25, while running the full simulation suite several times each for #134, #135
and the 4.0 crate moves, with `cargo test -p pdfs-fuse --lib -- --ignored sim::`. That command
leaves out `--test-threads=1`, which CI and [TESTING.md](TESTING.md) use, so libtest ran up to
eight simulations at once in one process.
**Where:** `crates/pdfs-fuse/src/sim/daemon.rs`, `Daemon::start` and `Daemon::shut_down`
**Repro:** Run the suite without `--test-threads=1`. Of 18 such runs on three branches based on
main, 6 passed, 10 failed and 2 hung until a 900 s timeout. The failures were timing asserts
in many tests, among them `a_write_that_failed_on_a_short_outage_goes_out_soon_after_the_link_returns`,
`three_clients_one_writer_each` and `one_client_with_stale_hashes_and_reordered_echoes`.
Each passes when run alone.
In a hung run, one test thread stayed in state D in `request_wait_answer`, waiting on a FUSE
request to a mount its own process serves. Killing the process left it a zombie and left its
mounts in place until their connections were aborted through
`/sys/fs/fuse/connections/<n>/abort`.
Run serially, the same branches pass in CI (#133 to #137).
**Cause.** The simulations share process-wide state: `isolate_from_the_developer` sets the XDG
variables once, which is sound only while no other test reads the environment, and every
daemon runs drain workers, a sync engine and a runtime on the same few cores. In parallel the
timing asserts miss their deadlines, and the harness has no way out of a mount that stops
answering.
**Fix.** `Daemon::start` takes a turn: a daemon started on one test thread waits while
another test thread still has one, so plain `cargo test` runs the simulations one after the
other. A daemon on the same thread, as in a restart or the multi-client runs, does not wait.
`--test-threads=1` stays the documented way, because it also keeps the parts of a test
before its first daemon apart.
A mount that does not stop within 60 s has its FUSE connection aborted through
`/sys/fs/fuse/connections/<n>/abort`, which the mounting user may write, and the stop fails
with that message. A daemon alive after 20 minutes gets the same, so a test blocked on a
request the mount never answers fails with `ENOTCONN` instead of hanging the run.
**Verified:** `a_simulation_on_another_thread_waits_for_this_ones_daemons`, which fails
without the turn.
Separately, CI on main (`0b9e849`) failed `a_move_blocked_by_trash_can_be_retried_after_restore`
once, serially ([run](https://github.com/narrrl/proton-drive-linux/actions/runs/45694939718)):
the assert at `daemon.rs:2209` found an empty list. It has not failed since.
---
### B296 — A busy database stalls reads, and piles up diagnostics threads
**Status:** Fixed (unverified)
-6
View File
@@ -15,9 +15,6 @@ Schema: **49**. New tables save a mirror folder's walk of Proton Drive (48). A f
kept, with a list of the folders that changed on Proton Drive since (49).
### Added
- **`pdfs diagnostics` counts every call the daemon makes to Proton Drive.** Per kind of call it
shows how many were made since start, how many failed, and their total and longest time. The
JSON report has them as `drive_calls`.
- **`pdfs diagnostics` and the journal say where a sync pass spends its time.** Each pass over a
synced folder records how long it took to walk this computer's copy, list Proton Drive, plan
and apply. It also records how many calls to Proton Drive it made of each kind, how long they
@@ -50,9 +47,6 @@ kept, with a list of the folders that changed on Proton Drive since (49).
first pass, and whenever the change feed lost track (#53).
### Fixed
- **An edit in a synced folder whose upload lost its answer is no longer kept as a conflict copy
of itself.** When the file on Drive has the same size and content as the local one, the
next sync records it as in step instead (B298).
- **A busy database no longer stalls reads or piles up threads.** A read that cannot get its own
connection fails instead of waiting behind a long write. `pdfs diagnostics` reports the
number of queued operations as unknown when the database does not answer in time, and no