Compare commits

..
Author SHA1 Message Date
nvrl 7e12c747a0 fix(gui,fuse): name the deletion when stopping a sync deletes the Drive folder
With "Also delete from Proton Drive" on, the stop-sync dialog kept its
routine heading, button and toast, although the action also moves the
folder in Proton Drive to the trash, and for an online-only folder that
is the only copy. The heading and button now change with the switch, and
the toast names the deletion.

The daemon dropped the folder from the sync set first and then only
logged a failed trash, so a removal while offline answered "removed
synced folder" and the copy in Proton Drive stayed without a word. It
now answers with an error that says the folder stopped syncing but its
Drive folder was not moved to the trash.

New sim: stopping_sync_says_so_when_its_drive_folder_could_not_be_deleted.
The catalogs are regenerated with po/update.sh, which also marks one
string that main no longer uses as obsolete.
2026-11-28 03:25:59 +01:00
nvrl f975d9cf17 Merge pull request #198 from narrrl/perf/revision-over
perf(sync): check an edit's base revision through the upload's own read
2026-11-28 02:11:30 +01:00
nvrl deb15a3327 Merge pull request #197 from narrrl/feat/sdk-0.12.7
build(deps): proton-sdk and proton-drive-rs 0.12.7
2026-11-28 01:23:57 +01:00
nvrl 8c7a0a8a17 perf(sync): check an edit's base revision through the upload's own read
A mirror edit read the file's node before each upload to make sure no
other client had committed a revision since the pass looked (B249). The
SDK then read the same link again for the content key and the revision
id. proton-drive-rs 0.12.8 adds upload_new_revision_over, which makes
that check with its own read and creates the revision over the expected
one. The mirror now uses it whenever it knows the revision it saw, and
keeps the separate read only for rows without one.

0.12.8 also caches a folder's hash key, so a second upload into the same
folder reads none of its keys again.

The fake drive answers upload_new_revision_over with Moved, Trashed or
Sealed, and honors hold_next_read, so the B249 sim still covers the race.
2026-11-28 01:21:56 +01:00
nvrl 9533ebcdfc build(deps): proton-sdk and proton-drive-rs 0.12.7
The new SDK sends a file whose encrypted size is under 128 KiB, and a new
revision of one, in a single request instead of a draft, its block and a
commit. Synced folders and the drive mount both stream their uploads, so both
take the one-request path. The small_uploads switch turns it off.
2026-11-28 00:33:48 +01:00
nvrl ccc679eef5 Merge pull request #196 from narrrl/feat/small-uploads
fix(sync): take an unanswered upload's file on Drive as our own, not a conflict
2026-11-28 00:30:10 +01:00
nvrl 20603205d9 fix(sync): take an unanswered upload's file on Drive as our own, not a conflict
When a mirror upload's answer was lost and the file was edited again before
the next pass, the plan saw a path new on both sides with different bytes and
kept the newer local edit as a sync-conflict copy of this computer's own
upload (B305).

An upload or new revision that hears no success back now notes the SHA-1 of
the bytes it sent in its effect intent (schema 52, sync_intent.sent_sha1s).
Before keeping a conflict copy, the plan checks whether Drive's file holds
exactly bytes an unsettled upload of that path sent. If so, the local bytes go
up as a revision of it. A first-sync adopt of a same-size file with other
bytes does the same. Every other case is unchanged.
2026-11-28 00:21:47 +01:00
nvrl d1421a84b1 Merge pull request #195 from narrrl/feat/small-upload-switch
feat(config): switch for the one-request small upload
2026-11-28 00:16:50 +01:00
nvrl 670ec7db31 Merge pull request #194 from narrrl/fix/ci-apt-microsoft
ci: drop the runner's Microsoft apt source before the update
2026-11-28 00:16:36 +01:00
nvrl 30b20fc444 Merge pull request #193 from narrrl/feat/bench-small-files
test(bench): time many small files and count the requests they take
2026-11-28 00:16:23 +01:00
nvrl 5c6360e6e7 feat(config): switch for the one-request small upload
small_uploads in config.json, on when absent, decides whether the daemon's Drive client sends a small file in one request. It lets the path be turned off without a new build while it is new.
2026-11-28 00:09:40 +01:00
nvrl 21e7c03460 test(bench): time many small files and count the requests they take
live-bench.py gets a small scenario: a tree of small random files and a few images with thumbnails, a first sync, then a batch of edits. Each phase reports wall time, files per second, the daemon's CPU time and the requests it sent, counted from the SDK's telemetry. This is the baseline for the one-request small upload.
2026-11-27 23:26:07 +01:00
32 changed files with 4822 additions and 3703 deletions

No files matched your search

Generated
+4 -4
View File
@@ -4071,9 +4071,9 @@ dependencies = [
[[package]]
name = "proton-drive-rs"
version = "0.12.6"
version = "0.12.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b1a71d0e737a9bd6cff07105218e7bef3bddcfd9d6651646d7302cdbba71961"
checksum = "11c09c245784d7253072b751e43b1919140fdbc8641c5328a7e2801889c86041"
dependencies = [
"async-trait",
"base64 0.23.1",
@@ -4191,9 +4191,9 @@ dependencies = [
[[package]]
name = "proton-sdk"
version = "0.12.6"
version = "0.12.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81edef2b4b174e936a3537793ee901b92dd7c0484eb7fed09ad69432f407f86b"
checksum = "7a6ed261fbcabf35abe67ebf8c8aff85b01fc43aef5b298380a6e6f7d3dd31d3"
dependencies = [
"aes-gcm 0.11.1",
"async-trait",
+2 -2
View File
@@ -15,8 +15,8 @@ keywords = ["proton", "drive", "fuse", "sync", "linux"]
categories = ["filesystem", "command-line-utilities"]
[workspace.dependencies]
proton-sdk = { version = "0.12.6" }
proton-drive-rs = { version = "0.12.6" }
proton-sdk = { version = "0.12.8" }
proton-drive-rs = { version = "0.12.8" }
proton-gallery-app-rs = "0.1.0"
proton-gallery-rs = "0.1.5"
proton-map-rs = "0.1.0"
+8
View File
@@ -278,6 +278,12 @@ pub struct AppConfig {
/// the field.
#[serde(default)]
pub local_first: Option<bool>,
/// Send a file small enough, with its thumbnails, to fit 128 KiB in one
/// request instead of three or more. `None` means on. `false` uploads
/// every file in blocks, the way all files went before. Defaulted for
/// configs predating the field.
#[serde(default)]
pub small_uploads: Option<bool>,
/// Ask GitHub once a day whether a newer release is out, and say so in the
/// desktop app. Off by default: GitHub then sees the address and version
/// asking. Never used where a package manager installs updates (see
@@ -1077,6 +1083,7 @@ mod tests {
language: Some("de".to_string()),
online_map: true,
local_first: Some(false),
small_uploads: Some(false),
update_check: true,
update_last_checked: Some(1_760_000_000),
update_latest: Some("3.6.0".to_string()),
@@ -1096,6 +1103,7 @@ mod tests {
assert_eq!(decoded.update_latest.as_deref(), Some("3.6.0"));
assert_eq!(decoded.language.as_deref(), Some("de"));
assert_eq!(decoded.upload_limit, Some(500_000));
assert_eq!(decoded.small_uploads, Some(false));
assert_eq!(decoded.download_limit, None);
assert_eq!(decoded.files_view, config.files_view);
assert_eq!(decoded.photos_view, config.photos_view);
+7
View File
@@ -241,6 +241,13 @@ pub fn mount_once(mountpoint: Option<PathBuf>) -> Result<pdfs_fuse::MountOutcome
let (client, session) = rt
.block_on(auth::resume_client())
.context("resume session (run `pdfs login` first)")?;
// On unless the config turns it off: the one-request upload for small
// files is new, and this lets it be switched off without a new build.
let small_uploads = config.small_uploads.unwrap_or(true);
if !small_uploads {
tracing::info!("small files are uploaded in blocks: small_uploads is off in the config");
}
let client = client.with_small_file_upload(small_uploads);
// Token updates are persisted automatically in real-time. The SDK session has
// a token refresh callback registered during `resume_client` that writes updated
+25 -1
View File
@@ -23,7 +23,7 @@ use proton_drive_rs::{
Thumbnail, ThumbnailType, TrashedNode,
};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload};
/// Every kind of call [`DriveApi`] makes, one per method.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -393,6 +393,30 @@ impl DriveApi for Counted {
.await
}
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
// Counted with the other revision uploads: it is one, with its check.
self.timed(
DriveCall::UploadNewRevision,
self.inner.upload_new_revision_over_dyn(
file_uid,
expected,
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
+55
View File
@@ -33,6 +33,8 @@ use proton_drive_rs::{
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
};
pub use proton_drive_rs::{RevisionUpload, SealedUpload};
pub mod counted;
pub mod digest;
@@ -120,6 +122,18 @@ pub trait DriveApi: Send + Sync {
last_modification_time: Option<i64>,
) -> Result<()>;
/// A new revision of `file_uid`, only over the revision `expected`. See
/// [`ProtonDriveClient::upload_new_revision_over`].
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload>;
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>>;
/// The file's thumbnail of `thumbnail_type`, or `None` when its revision
@@ -287,6 +301,26 @@ impl dyn DriveApi {
.await
}
pub async fn upload_new_revision_over<R: Read + Send>(
&self,
file_uid: &NodeUid,
expected: &str,
mut reader: R,
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
self.upload_new_revision_over_dyn(
file_uid,
expected,
&mut reader,
intended_size,
thumbnails,
last_modification_time,
)
.await
}
pub async fn download_file_to<W: Write + Send>(
&self,
uid: &NodeUid,
@@ -468,6 +502,27 @@ impl DriveApi for ProtonDriveClient {
.await
}
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
ProtonDriveClient::upload_new_revision_over(
self,
file_uid,
expected,
reader,
intended_size,
thumbnails,
last_modification_time.and_then(pdfs_core::timestamp::modification_time),
)
.await
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
let reader = ProtonDriveClient::open_revision(self, uid).await?;
Ok(Arc::new(reader))
+52 -1
View File
@@ -67,7 +67,7 @@ use proton_drive_rs::{
use sha1::{Digest as _, Sha1};
use super::rng::Rng;
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload, SealedUpload};
/// The volume every fake node lives on.
pub const VOLUME: &str = "simvol";
@@ -1531,6 +1531,57 @@ impl DriveApi for FakeClient {
Ok(())
}
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
// The SDK reads the file's link for its keys and checks the revision
// on that read, so it is held, lags and counts like any other read.
self.wait_if_held(&self.0.hold, std::slice::from_ref(file_uid))
.await;
let lag = self.lag();
let seen = self
.request(false, |server| {
Ok(server
.visible(file_uid, lag, Instant::now())
.map(|remote| (remote.trashed, remote.file.map(|file| file.revision))))
})
.await?;
match seen {
None => return Err(api(ResponseCode::DoesNotExist, "file not found")),
Some((true, _)) => return Ok(RevisionUpload::Trashed),
Some((false, revision)) if revision.as_deref() != Some(expected) => {
return Ok(RevisionUpload::Moved);
}
Some(_) => {}
}
self.upload_new_revision_from_dyn(
file_uid,
reader,
intended_size,
thumbnails,
last_modification_time,
)
.await?;
let revision_id = self
.0
.drive
.server
.lock()
.current(file_uid)
.and_then(|remote| remote.file.as_ref().map(|file| file.revision.clone()))
.unwrap_or_default();
Ok(RevisionUpload::Sealed(SealedUpload {
node_uid: file_uid.clone(),
revision_id,
}))
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
let file = self
.request(false, |server| {
+16 -2
View File
@@ -130,12 +130,26 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
CtlRequest::RemoveSyncFolder { id, delete_remote } => {
match core.remove_sync_folder(id, delete_remote) {
Ok(()) => {
Ok(None) => {
core.profile().touch_profile();
CtlResponse::Ok {
message: "removed synced folder".to_string(),
message: if delete_remote {
"removed synced folder and moved its folder in Proton Drive to the trash"
} else {
"removed synced folder"
}
.to_string(),
}
}
// The folder no longer syncs, but its copy in Proton Drive is
// still there. That is not what was asked, so it is an error,
// and the message says which half happened.
Ok(Some(trash_error)) => {
core.profile().touch_profile();
CtlResponse::error(CoreError::remote(format!(
"stopped syncing the folder, but its folder in Proton Drive was not moved to the trash: {trash_error}"
)))
}
Err(e) => CtlResponse::error(e),
}
}
+28 -11
View File
@@ -765,9 +765,18 @@ impl Core {
jobs
}
/// Remove a synced folder from the sync set. `delete_remote` also deletes its
/// folder under the device root; otherwise the cloud copy is left in place.
pub(crate) fn remove_sync_folder(&self, id: i64, delete_remote: bool) -> CoreResult<()> {
/// Remove a synced folder from the sync set. `delete_remote` also moves its
/// folder under the device root to the trash; otherwise the cloud copy is
/// left in place.
///
/// The folder is out of the sync set before the trash is asked, so a trash
/// that fails does not fail the removal. It comes back as `Some(error)`,
/// for the caller to say that the cloud copy is still there.
pub(crate) fn remove_sync_folder(
&self,
id: i64,
delete_remote: bool,
) -> CoreResult<Option<String>> {
let lock = self.sync.lock(id);
// A pass holds the lock for as long as it runs, hours on a large
// folder. Ask it to stop at its next checkpoint rather than wait it
@@ -823,16 +832,24 @@ impl Core {
self.clear_sync_folder_paused(id);
// Stop watching the folder we just dropped.
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
if delete_remote
&& let Some(uid) = parse_uid(&folder.remote_uid)
&& let Err(e) = self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit)
if !delete_remote {
return Ok(None);
}
let Some(uid) = parse_uid(&folder.remote_uid) else {
warn!(id, remote = %folder.remote_uid, "delete remote device folder: bad uid");
return Ok(Some(format!("bad folder id {}", folder.remote_uid)));
};
match self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit)
{
warn!(id, error = %e, "delete remote device folder failed");
Ok(()) => Ok(None),
Err(e) => {
warn!(id, error = %e, "delete remote device folder failed");
Ok(Some(e.to_string()))
}
}
Ok(())
}
/// Trigger a reconcile: one folder by id, or every folder when `id` is `None`.
+115
View File
@@ -2490,6 +2490,70 @@ 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_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands() {
// Drive made the file, but the answer never came back, and the daemon
// stopped before it tried again. While it was stopped the file was
// written again. A one-request small upload makes this the common way
// a create goes unanswered: it leaves a whole file, never a draft. The
// start must find that file, take it as this one, and put the newer
// bytes on it: one file, no conflict copy.
take_logged();
let drive = FakeDrive::new();
let dir = scratch("mirror-lost-create-restart");
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
let local = dir.join("local");
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
client.lose_reply_to_next_create();
std::fs::write(local.join("new.txt"), b"first").unwrap();
assert!(wait_until(Duration::from_secs(30), || {
on_drive(&drive, "mirrored/new.txt").is_some_and(|bytes| bytes == b"first")
}));
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
std::fs::write(local.join("new.txt"), b"second, written while stopped").unwrap();
let daemon = Daemon::start(&dir, client).unwrap();
let landed = wait_until(Duration::from_secs(60), || {
on_drive(&drive, "mirrored/new.txt")
.is_some_and(|bytes| bytes == b"second, written while stopped")
});
let logged = take_logged();
assert!(
landed,
"{:#?}\n{:#?}",
drive.tree(),
logged
.iter()
.filter(|l| l.contains("sync") || l.contains("new"))
.collect::<Vec<_>>()
);
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
assert!(conflict_copies(&local, "new").is_empty());
let tree = drive.tree();
assert!(
!tree.keys().any(|k| k.contains("sync-conflict")),
"{tree:?}"
);
assert_eq!(
tree.keys().filter(|k| k.contains("new")).count(),
1,
"{tree:?}"
);
assert_eq!(
std::fs::read(local.join("new.txt")).unwrap(),
b"second, written while stopped"
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
assert!(
reopen(&dir).sync_intents(Some(folder)).unwrap().is_empty(),
"every intent settled"
);
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() {
@@ -4421,6 +4485,57 @@ mod tests {
id
}
/// Stop syncing with "Also delete from Proton Drive" on, while Drive cannot
/// be reached. The folder stops syncing, but its copy in Proton Drive
/// stays. The reply was a plain success, so the app said "Stopped syncing
/// folder" and nothing told the user the cloud copy was still there.
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn stopping_sync_says_so_when_its_drive_folder_could_not_be_deleted() {
let drive = FakeDrive::new();
let dir = scratch("stop-sync-delete-offline");
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
let local = dir.join("docs");
let id = sync_folder(&daemon, &local, "mirror");
std::fs::write(local.join("keep.txt"), b"keep").unwrap();
daemon.request(&Request::SyncNow { id: Some(id) }).unwrap();
let on_drive = || {
drive.tree().iter().any(|(path, entry)| {
path.ends_with("docs/keep.txt") && *entry == Entry::File(Arc::new(b"keep".to_vec()))
})
};
assert!(
wait_until(Duration::from_secs(30), || on_drive()
&& listed_folder(&daemon, id).is_some_and(|f| f.state == "idle")),
"the folder synced: {:?}",
listed_folder(&daemon, id)
);
daemon.client.set_online(false);
let error = daemon
.request(&Request::RemoveSyncFolder {
id,
delete_remote: true,
})
.unwrap_err()
.to_string();
daemon.client.set_online(true);
assert!(
error.contains("stopped syncing the folder")
&& error.contains("was not moved to the trash"),
"{error}"
);
assert!(
listed_folder(&daemon, id).is_none(),
"the folder still syncs"
);
assert!(on_drive(), "the copy in Proton Drive is gone after all");
assert_eq!(std::fs::read(local.join("keep.txt")).unwrap(), b"keep");
daemon.stop().unwrap();
let _ = std::fs::remove_dir_all(dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_move_out_of_an_on_demand_folder_refuses_a_file_still_open_for_writing() {
+44 -10
View File
@@ -1007,20 +1007,54 @@ pub(crate) fn prompt_remove_sync_folder(
dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);
dialog.set_default_response(Some("cancel"));
dialog.set_close_response("cancel");
let ui = ui.clone();
dialog.connect_response(None, move |_, resp| {
if resp == "remove" {
run_devices_mutation(
&ui,
Request::RemoveSyncFolder {
id,
delete_remote: !attached && delete_remote.is_active(),
// With the switch on, the button does more than stop syncing, so it says
// so: the heading, the button and the outcome all name the deletion.
delete_remote.connect_active_notify({
let dialog = dialog.clone();
move |row| {
let deleting = row.is_active();
dialog.set_heading(Some(&if deleting {
gettext("Stop Syncing and Delete Folder?")
} else {
gettext("Stop Syncing Folder?")
}));
dialog.set_response_label(
"remove",
&if deleting {
gettext("Stop Syncing and Delete")
} else {
gettext("Stop Syncing")
},
&gettext("Stopped syncing folder"),
&gettext("Couldn't stop syncing the folder"),
);
}
});
let ui = ui.clone();
dialog.connect_response(None, move |_, resp| {
if resp != "remove" {
return;
}
let deleting = !attached && delete_remote.is_active();
let (done, failed) = if deleting {
(
gettext("Stopped syncing and moved the folder in Proton Drive to the trash"),
gettext("Couldn't stop syncing and delete the folder"),
)
} else {
(
gettext("Stopped syncing folder"),
gettext("Couldn't stop syncing the folder"),
)
};
run_devices_mutation(
&ui,
Request::RemoveSyncFolder {
id,
delete_remote: deleting,
},
&done,
&failed,
);
});
dialog.present(win.as_ref());
}
+23 -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 = 51;
pub(super) const SCHEMA_VERSION: i64 = 52;
impl Db {
pub(super) fn migrate(&self) -> Result<()> {
@@ -563,6 +563,21 @@ impl Db {
tx.execute_batch(MIGRATION_V51)?;
}
}
if current < 52 {
let has_intents: bool = tx.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sync_intent'",
[],
|row| row.get::<_, i64>(0).map(|n| n > 0),
)?;
let has_column: bool = tx.query_row(
"SELECT COUNT(*) FROM pragma_table_info('sync_intent') WHERE name = 'sent_sha1s'",
[],
|row| row.get::<_, i64>(0).map(|n| n > 0),
)?;
if has_intents && !has_column {
tx.execute_batch(MIGRATION_V52)?;
}
}
tx.execute(
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
@@ -1627,6 +1642,13 @@ BEGIN
END;
";
/// v52: the SHA-1s of the bytes each unsettled mirror upload sent, space
/// separated. A reply that never came may hide an upload that landed, and its
/// digest is how a later pass knows the file on Drive for its own.
const MIGRATION_V52: &str = "
ALTER TABLE sync_intent ADD COLUMN sent_sha1s TEXT;
";
/// See [`MIGRATION_V49_COLUMNS`].
const MIGRATION_V49: &str = "
CREATE TABLE IF NOT EXISTS sync_remote_dirty (
+31 -1
View File
@@ -34,6 +34,9 @@ pub struct StoredIntent {
/// When it was last sent, in seconds since the epoch.
pub issued_at: i64,
pub last_error: Option<String>,
/// For an upload: the SHA-1s of the bytes its attempts streamed without
/// hearing a success back, lowercase. One of them may have landed.
pub sent_sha1s: Vec<String>,
}
/// What a mirror pass has walked of Drive, saved so a pass cut short
@@ -901,6 +904,29 @@ impl Db {
Ok(())
}
/// Note that the upload `kind` of `rel_path` streamed bytes with SHA-1
/// `sha1` and heard no success back. Nothing happens without an intent for
/// it. A digest already noted is not added again.
pub fn sync_intent_sent(
&self,
folder_id: i64,
rel_path: &str,
kind: &str,
sha1: &str,
) -> Result<()> {
let sha1 = sha1.to_ascii_lowercase();
let conn = self.conn.lock();
conn.execute(
"UPDATE sync_intent SET sent_sha1s = CASE
WHEN sent_sha1s IS NULL OR sent_sha1s = '' THEN ?4
WHEN instr(' ' || sent_sha1s || ' ', ' ' || ?4 || ' ') > 0 THEN sent_sha1s
ELSE sent_sha1s || ' ' || ?4 END
WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3",
params![folder_id, rel_path, kind, sha1],
)?;
Ok(())
}
/// Every intent not settled, oldest first; only `folder_id`'s when given.
pub fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>> {
let conn = self.read()?;
@@ -970,7 +996,7 @@ impl Db {
}
const INTENT_COLUMNS: &str =
"id, folder_id, rel_path, kind, state, attempts, issued_at, last_error";
"id, folder_id, rel_path, kind, state, attempts, issued_at, last_error, sent_sha1s";
fn intent_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoredIntent> {
Ok(StoredIntent {
@@ -982,6 +1008,10 @@ fn intent_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoredIntent> {
attempts: u32::try_from(row.get::<_, i64>(5)?).unwrap_or(u32::MAX),
issued_at: row.get(6)?,
last_error: row.get(7)?,
sent_sha1s: row
.get::<_, Option<String>>(8)?
.map(|s| s.split_whitespace().map(str::to_owned).collect())
.unwrap_or_default(),
})
}
+27
View File
@@ -8456,6 +8456,33 @@ fn a_deletion_window_is_kept_per_folder_until_the_folder_changes() {
/// An intent is one row per folder, path and kind: sent again, it counts the
/// attempt and says what state it was left in. It goes once settled, and with
/// the folder.
#[test]
fn an_upload_notes_each_digest_it_sent_once() {
let db = Db::open_in_memory().unwrap();
let id = db.sync_folder_add("/home/me/Docs", "v~root", "s").unwrap();
// Nothing to note without an intent.
db.sync_intent_sent(id, "a.txt", "upload", "AA").unwrap();
assert!(db.sync_intents(Some(id)).unwrap().is_empty());
db.sync_intent_issue(id, "a.txt", "upload", 10).unwrap();
db.sync_intent_sent(id, "a.txt", "upload", "AA").unwrap();
db.sync_intent_sent(id, "a.txt", "upload", "aa").unwrap();
// Sent again with other bytes: both may have landed.
db.sync_intent_issue(id, "a.txt", "upload", 20).unwrap();
db.sync_intent_sent(id, "a.txt", "upload", "bb").unwrap();
// Another kind of the same path keeps its own.
db.sync_intent_issue(id, "a.txt", "upload-revision", 21)
.unwrap();
let intents = db.sync_intents(Some(id)).unwrap();
let upload = intents.iter().find(|i| i.kind == "upload").unwrap();
assert_eq!(upload.sent_sha1s, ["aa", "bb"]);
let revision = intents
.iter()
.find(|i| i.kind == "upload-revision")
.unwrap();
assert!(revision.sent_sha1s.is_empty());
}
#[test]
fn an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes() {
let db = Db::open_in_memory().unwrap();
+12
View File
@@ -852,6 +852,18 @@ impl Syncer {
}
FilePlan::Conflict => {
let remote = r.expect("conflict requires a remote file");
if self.landed_unanswered(folder_id, rel, remote.sha1.as_deref()) {
info!(
rel,
"sync: the file on Drive is an upload of ours that went unanswered; sending the newer local bytes as a revision of it"
);
batch.push(Pending::UploadRevision {
rel: rel.clone(),
uid: remote.uid.clone(),
seen: RemoteSeen::from(remote),
});
continue;
}
batch.push(Pending::Conflict {
rel: rel.clone(),
uid: remote.uid.clone(),
+110 -25
View File
@@ -194,6 +194,47 @@ impl Syncer {
}
}
/// Note that an upload of `rel` streamed bytes with SHA-1 `sha1` and did
/// not hear a success back. They may have landed all the same.
fn note_sent(&self, folder_id: i64, rel: &str, kind: &str, sha1: &str) {
if let Err(error) = self.store.sync_intent_sent(folder_id, rel, kind, sha1) {
debug!(rel, error = ?error, "sync: cannot note what an upload sent");
}
}
/// Whether the file Drive holds at `rel`, with SHA-1 `remote_sha1`, is one
/// of this daemon's own uploads whose answer never came: an upload of
/// `rel` not yet settled streamed exactly those bytes.
///
/// Then the file is ours, not another computer's, and a newer local edit
/// is not a conflict with it: it goes up as a revision. A file that only
/// happens to hold the same bytes loses nothing by that either.
pub(super) fn landed_unanswered(
&self,
folder_id: i64,
rel: &str,
remote_sha1: Option<&str>,
) -> bool {
let Some(remote_sha1) = remote_sha1 else {
return false;
};
let intents = match self.store.sync_intents(Some(folder_id)) {
Ok(intents) => intents,
Err(error) => {
debug!(rel, error = ?error, "sync: cannot read the effect intents");
return false;
}
};
intents.iter().any(|intent| {
intent.rel_path == rel
&& matches!(intent.kind.as_str(), "upload" | "upload-revision")
&& intent
.sent_sha1s
.iter()
.any(|sent| sent.eq_ignore_ascii_case(remote_sha1))
})
}
/// Settle the intents of `folder_id` that a pass begun at `began` did
/// not send again, though it looked at every path: what they were for has
/// changed, or is done.
@@ -323,6 +364,15 @@ impl Syncer {
return Ok(Applied::Vanished);
}
if !digest.eq_ignore_ascii_case(sha1) {
if self.landed_unanswered(folder_id, rel, Some(sha1)) {
info!(
rel,
"sync: the file on Drive is an upload of ours that went unanswered; sending the newer local bytes as a revision of it"
);
return self
.upload_revision(folder_id, local_root, rel, uid, remote)
.await;
}
info!(
rel,
"sync: same size as on Drive but different content; keeping a conflict copy"
@@ -444,8 +494,14 @@ impl Syncer {
Some(mtime),
false,
)
.await
.map_err(|e| format!("upload {rel}: {e}"))?;
.await;
let uid = match uid {
Ok(uid) => uid,
Err(e) => {
self.note_sent(folder_id, rel, "upload", &sent.digest());
return Err(format!("upload {rel}: {e}"));
}
};
// The parent has gained a child that no cached listing of it knows
// about. Without this, a folder later switched to on-demand serves a
// snapshot that predates this upload (B86).
@@ -465,9 +521,13 @@ impl Syncer {
/// folder may have committed a revision since, and uploading over it would
/// leave that edit only in the revision history. So Drive is asked first,
/// and a file that moved on is left for the next pass, which keeps the
/// local edit as a conflict copy (B249). A revision committed between this
/// check and the upload's own draft is not caught here; the read-back after
/// the upload catches one committed after it.
/// local edit as a conflict copy (B249). A revision committed after the
/// upload is caught by the read-back.
///
/// When the pass knows the revision id, the check rides on the read of the
/// file the upload makes for its keys (`upload_new_revision_over`), and the
/// revision is created over that id, so Drive refuses one committed in
/// between. A baseline without an id still reads the node first.
pub(super) async fn upload_revision(
&self,
folder_id: i64,
@@ -480,22 +540,16 @@ impl Syncer {
let Some(file) = open_to_upload(&path, rel)? else {
return Ok(Applied::Vanished);
};
let current = self
.drive
.enumerate_nodes(std::slice::from_ref(uid))
.await
.map_err(|e| format!("check {rel} on Drive: {e}"))?;
match current.first() {
Some(node) if !node.trashed && seen.still_current(node) => {}
Some(node) if !node.trashed => {
return Err(format!(
"{rel} changed on Drive since this pass looked; it is compared again on the next pass"
));
}
_ => {
return Err(format!(
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
));
if seen.revision.is_none() {
let current = self
.drive
.enumerate_nodes(std::slice::from_ref(uid))
.await
.map_err(|e| format!("check {rel} on Drive: {e}"))?;
match current.first() {
Some(node) if !node.trashed && seen.still_current(node) => {}
Some(node) if !node.trashed => return Err(moved_on_drive(rel)),
_ => return Err(gone_from_drive(rel)),
}
}
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
@@ -513,10 +567,28 @@ impl Syncer {
meta.len(),
),
));
self.drive
.upload_new_revision_from(uid, reader, meta.len() as i64, thumbnails, Some(mtime))
.await
.map_err(|e| format!("upload revision {rel}: {e}"))?;
let size = meta.len() as i64;
let uploaded = match seen.revision.as_deref() {
Some(expected) => self
.drive
.upload_new_revision_over(uid, expected, reader, size, thumbnails, Some(mtime))
.await
.map(Some),
None => self
.drive
.upload_new_revision_from(uid, reader, size, thumbnails, Some(mtime))
.await
.map(|()| None),
};
match uploaded {
Ok(None | Some(pdfs_drive::RevisionUpload::Sealed(_))) => {}
Ok(Some(pdfs_drive::RevisionUpload::Moved)) => return Err(moved_on_drive(rel)),
Ok(Some(pdfs_drive::RevisionUpload::Trashed)) => return Err(gone_from_drive(rel)),
Err(e) => {
self.note_sent(folder_id, rel, "upload-revision", &sent.digest());
return Err(format!("upload revision {rel}: {e}"));
}
}
warn_if_torn(rel, &path, streamed);
let remote = self
.landed_as_sent(rel, uid, &sent.digest(), streamed)
@@ -685,3 +757,16 @@ impl Syncer {
.map_err(|e| format!("baseline {rel}: {e:?}"))
}
}
/// Why a revision was not sent: Drive's file moved on since the pass looked.
fn moved_on_drive(rel: &str) -> String {
format!("{rel} changed on Drive since this pass looked; it is compared again on the next pass")
}
/// Why a revision was not sent: the file is no longer on Drive where the pass
/// saw it.
fn gone_from_drive(rel: &str) -> String {
format!(
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
)
}
+18
View File
@@ -96,6 +96,15 @@ pub trait SyncStore: Send + Sync {
fn sync_intent_settle(&self, id: i64) -> Result<()>;
/// Move an intent to `state`, with the error that put it there.
fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()>;
/// Note that upload `kind` of `rel_path` streamed bytes with SHA-1 `sha1`
/// and heard no success back.
fn sync_intent_sent(
&self,
folder_id: i64,
rel_path: &str,
kind: &str,
sha1: &str,
) -> Result<()>;
/// Every intent not settled; only `folder_id`'s when given.
fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>>;
/// Move every intent in state `from` to `to`.
@@ -197,6 +206,15 @@ impl SyncStore for Db {
fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()> {
Db::sync_intent_set(self, id, state, error)
}
fn sync_intent_sent(
&self,
folder_id: i64,
rel_path: &str,
kind: &str,
sha1: &str,
) -> Result<()> {
Db::sync_intent_sent(self, folder_id, rel_path, kind, sha1)
}
fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>> {
Db::sync_intents(self, folder_id)
}
+31
View File
@@ -108,6 +108,7 @@ a live account since.
| Entry | Title |
|---|---|
| [B305](#b305--a-mirrored-file-whose-upload-went-unanswered-gets-a-conflict-copy-of-its-own-edit) | A mirrored file whose upload went unanswered gets a conflict copy of its own edit |
| [B304](#b304--a-write-released-while-its-files-create-lands-is-kept-as-a-conflict-copy) | A write released while its file's create lands is kept as a conflict copy |
| [B303](#b303--a-file-made-where-a-withdrawn-create-was-listed-refuses-every-write) | A file made where a withdrawn create was listed refuses every write |
| [B302](#b302--a-stop-during-a-replacing-rename-leaves-the-replaced-file-in-the-trash) | A stop during a replacing rename leaves the replaced file in the trash |
@@ -407,6 +408,36 @@ a live account since.
Newest first.
### B305 — A mirrored file whose upload went unanswered gets a conflict copy of its own edit
**Status:** Fixed (unverified)
**Found:** 2026-11-27, writing the simulation for the case the effect reducer is meant to handle
(`FURTHER_IMPROVEMENTS.md`): a create accepted by Drive, the reply lost, a restart, and a newer
local edit. The simulation failed on the first run. Drive held `new.txt` with the first bytes and
`new (sync-conflict …).txt` with the edit.
**Where:** the `FilePlan::Conflict` arm of the plan in `crates/pdfs-sync/src/mirror.rs`, and
`Pending::Adopt` in `crates/pdfs-sync/src/mirror/apply.rs`
**Repro:** In a mirror folder, write a new file. Lose the answer to its upload after Drive has
made the file. Stop the daemon, write the file again, and start the daemon.
**Cause.** The upload failed as far as the daemon knew, so no baseline was recorded. The next pass
found the path on both sides with no baseline and different bytes, which is what two computers
writing one new file look like, so it kept the local copy as a conflict copy. The edit itself is
not lost. The one-request small upload makes this ending of a lost reply the usual one: it
leaves a whole file, never a draft for the next attempt to replace.
**Fix.** An upload that hears no success back notes the SHA-1 of the bytes it streamed in its
effect intent (`sent_sha1s`, schema 52). Before keeping a conflict copy, the plan checks the
intents. If Drive's file holds exactly bytes an unsettled upload of that path sent, the file is
this daemon's own. The local bytes then go up as a revision of it. A first-sync adopt of a
same-size file with other bytes does the same. A file that holds those bytes by chance loses
nothing either: they are what this computer sent.
**Verified:** `a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands`
fails without the fix and passes with it. `an_upload_notes_each_digest_it_sent_once` covers the
store.
### B304 — A write released while its file's create lands is kept as a conflict copy
**Status:** Fixed (unverified)
+28 -2
View File
@@ -11,12 +11,21 @@ scratch (user data in `staging/` and `recovery/` is never touched by this).
## [Unreleased]
Schema: **51**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
Schema: **52**. 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). Each upload, download or folder a mirror pass
sends is recorded until its result is in (51).
sends is recorded until its result is in (51), and an upload that heard no answer keeps the
digest of what it sent (52).
### Added
- **Small files go up to Proton Drive in one request.** A file whose encrypted size is under
128 KiB, and a new revision of one, is now sent in a single request instead of a draft, its
block and a commit. This covers synced folders and the drive mount. On a test account, a first
sync of 200 small files ran 58% faster, and 50 edits of them 97% faster. Larger files go up in
blocks as before. `proton-sdk` and `proton-drive-rs` are now 0.12.7.
- **`small_uploads` in `config.json` turns off the one-request upload for small files.** It is
on by default. Set it to `false` to send every file as a draft, its blocks and a commit, as
before. The service reads it at start. See [Configuration](CONFIGURATION.md#small_uploads).
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
ends while the drive is mounted, for example the sync engine after a crash, the journal says
so once, by name, instead of saying nothing until a restart. It also lists the jobs running
@@ -46,6 +55,11 @@ sends is recorded until its result is in (51).
any more.
### Changed
- **An upload into a folder and an edit of a synced file make fewer requests.** The key that
hashes a folder's file names is now read once per folder, not once per upload. A synced
folder no longer reads a file again before it sends an edit. It checks that nobody else
changed the file through the read the upload already makes, and it still sends nothing over
a revision it has not seen. `proton-sdk` and `proton-drive-rs` are now 0.12.8.
- **A sync pass over a quiet folder no longer reads the whole folder on disk.** While the
filesystem watcher has been running without a break, a pass reads again only the folders and
files it reported changed, and takes the rest from the pass before. The whole folder is still
@@ -72,6 +86,18 @@ sends is recorded until its result is in (51).
first pass, and whenever the change feed lost track (#53).
### Fixed
- **Stopping a sync with "Also delete from Proton Drive" says that it deletes, and says so when
the deletion failed.** With the switch on, the dialog now reads "Stop Syncing and Delete
Folder?" and its button "Stop Syncing and Delete". If the folder stopped syncing but its folder
in Proton Drive could not be moved to the trash, for example while offline, the app and
`pdfs sync rm --delete-remote` now report an error that says so. Before, they reported plain
success, and the copy in Proton Drive stayed without a word.
- **A mirrored file whose upload went unanswered no longer gets a conflict copy of its own
edit.** Proton Drive can make a file and lose the answer. If the file was then written again
before the next sync, for example while the daemon was stopped, that sync saw two different
files under one name. It kept this computer's newer edit as a conflict copy next to its own
first upload. Now an upload that hears no answer keeps the digest of the bytes it sent. When
Proton Drive holds exactly those bytes, the newer edit goes up as a new version of that file.
- **A stop ends the loops that follow Proton Drive's change feed before the daemon exits.**
The loops that read the Drive and photos event streams, and the gallery refresh, kept
running after every other service had stopped, and could still write to the database while
+11
View File
@@ -88,6 +88,7 @@ fix it.
| `device_uid` | string | none | Computers → Continue This Backup Here… or Sync With This Computer… | The computer this machine syncs into. Unset means "match by hostname" |
| `conflict_sweep` | `off` / `report` / `enforce` | `report` | Sync → Conflict Copies | See [`conflict_sweep`](#conflict_sweep) |
| `local_first` | bool | `true` | — | See [`local_first`](#local_first) |
| `small_uploads` | bool | `true` | — | See [`small_uploads`](#small_uploads) |
| `language` | gettext code | system | General → Appearance | Language of the app, tray and prompt, such as `de` or `pt_BR` |
| `proton_theme` | bool | follow system | General → Appearance | Proton's colours instead of the system theme |
| `online_map` | bool | `false` | General → Appearance | Street map for Places from OpenFreeMap |
@@ -145,6 +146,16 @@ call returns at once. The change goes to Drive from the queue, the same way it d
Set it to `false` to have these calls wait for Drive again, as before 3.0.0. The switch is there
for one release, in case the queued path misbehaves for you; please report it if it does.
### `small_uploads`
A file that fits in 128 KiB with its thumbnails goes to Proton Drive in one request. A larger one
goes as a draft, its blocks, and a commit, which takes three requests or more. Most synced files
are small, so this is what decides how fast a folder of many small files syncs.
Set it to `false` to upload every file in blocks again. The setting is read when the service
starts. The journal says `small files are uploaded in blocks` while it is off. Please report it if
you need to turn it off.
### `open_with`
Decides how files picked in the search launcher or the app are opened. Rules are tried in order;
+31 -7
View File
@@ -282,14 +282,38 @@ decides what happens next:
is logged at info.
- A change to what the folder is, or its removal, drops its rows.
The intents are kept in shadow for now: nothing reads them to decide what to send. The apply
step's own checks still decide whether an effect that may have landed is sent again (B266 for a
create, B39 for a download). Deletions on either side are not recorded yet. Trace counts:
`unsure resent`, `retried`, `superseded`.
The intents decide one thing so far: whether a file on Drive is an upload of this daemon's
that went unanswered.
- An upload that does not hear a success back notes the SHA-1 of the bytes it streamed in its
intent (`sent_sha1s`, schema 52). Each attempt adds its digest.
- When a later pass would keep a conflict copy, it checks the intent first. The path may be new
on both sides, or changed on both sides since the baseline. If Drive's file holds exactly
bytes an unsettled upload of that path sent, the file is ours. The newer local bytes then go up
as a revision of it, with no conflict copy. The same holds for a first-sync adopt of a
same-size file whose bytes differ.
- This is the usual end of a lost reply to a one-request small upload. Such an upload leaves a
whole file, never a draft. If the file was written again before the next pass, for example
while the daemon was stopped, the next pass used to see two different files and fork a
conflict copy of this computer's own edit.
- A file that only happens to hold the same bytes loses nothing either: its content is what
this computer sent.
- A daemon killed in the middle of an upload notes no digest, so that case still ends in a
conflict copy when the file is edited before the next pass. It is kept, and nothing is lost.
**Tests:** the `effect::tests` unit tests, `an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes`
(DB), and `an_effect_left_unsure_by_a_stop_is_sent_again_or_settled` (sim: of two uploads a
stopped daemon left unsure, the one still needed is sent again and the other is settled).
Otherwise nothing reads the intents to decide what to send. The apply step's own checks still
decide whether an effect that may have landed is sent again (B266 for a create, B39 for a
download). Deletions on either side are not recorded yet. Trace counts: `unsure resent`,
`retried`, `superseded`.
**Tests:**
- the `effect::tests` unit tests;
- DB: `an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes`, and
`an_upload_notes_each_digest_it_sent_once`;
- sim `an_effect_left_unsure_by_a_stop_is_sent_again_or_settled`: of two uploads a stopped daemon
left unsure, the one still needed is sent again and the other is settled;
- sim `a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands`:
Drive makes the file and the answer is lost, then the daemon stops and the file is written
again. After the start there is one file, holding the newer bytes, and no conflict copy.
## Plan of work (separate PRs)
+26 -3
View File
@@ -307,9 +307,32 @@ instance's keyring entry so the next run does not sign in again; `--logout` forg
Proton asks for a CAPTCHA, sign in once by hand with `PDFS_INSTANCE=bench pdfs login`.
The script refuses a `pdfs` built without `PDFS_INSTANCE`, which would act on your own account.
A new folder's first sync uploads about one small file every four seconds, so with a 500-file
tree the edit is timed about 35 minutes in. A run that is cut short leaves its folder behind; the
next run removes it.
A new folder's first sync uploads about two small files a second (eight at a time), so with a
500-file tree the edit is timed a few minutes in. A run that is cut short leaves its folder behind;
the next run removes it.
### The small-file benchmark
`--scenario small` times many small files instead, the case that the API's one-request small
upload is for. For each tree size (200 by default) it makes files of `--small-size` random bytes
(4096 by default), plus `--images` noise PNGs that get thumbnails (10 by default). It then:
- times the first sync, until every file is uploaded and the folder is quiet
- rewrites `--edits` of the files at once (50 by default) and times until all are uploaded again
For each phase it reports wall time, files per second, the daemon's CPU time, and the requests
the daemon sent. The requests are API calls by method, plus storage uploads. It counts them from
the SDK's telemetry: the daemon runs with `RUST_LOG=info,pgp=error,proton_sdk::telemetry=debug`,
and its log goes to the work directory. If the SDK tags each request with its endpoint, the JSON
output also counts requests per endpoint.
```bash
scripts/live-bench.py --account-env path/to/.env --pdfs target/release/pdfs --scenario small \
--json small.json
```
Wall time varies by 2x between runs against the live service. Compare medians of three runs,
and treat the request counts as the stable measure.
## Before a release
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+420 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+290 -6
View File
@@ -2,7 +2,10 @@
"""Time one edit in a synced folder, from the write to the new revision on Drive.
Runs against a real account on a separate instance (`PDFS_INSTANCE`), so the
user's own daemon and session are never touched. For each tree size it:
user's own daemon and session are never touched. There are two scenarios,
picked with `--scenario`.
`edit` (the default) times one edit. For each tree size it:
1. makes a disposable folder in My files and a local tree of that many files,
2. attaches the local tree to it and waits for the first sync to finish,
@@ -12,6 +15,19 @@ user's own daemon and session are never touched. For each tree size it:
- verify: the pass end until `pdfs versions list` shows the new revision,
4. detaches the folder and trashes the remote copy.
`small` times many small files, the case Proton's one-request small upload is
for. For each tree size it:
1. makes a tree of files of `--small-size` random bytes, plus `--images` noise
PNGs that get thumbnails, and attaches it,
2. times the first sync until every file is uploaded and the folder is quiet,
3. rewrites `--edits` of the files at once and times until all of them are
uploaded again,
4. reports, for each phase, the wall time, files per second, the daemon's CPU
time and the requests it sent: API calls by method, and storage uploads.
The requests come from the SDK's telemetry, so the daemon runs with
`proton_sdk::telemetry=debug`.
The account comes from an env file with `username=`, `password=` and, for an
account with two-factor sign-in, `PROTON_TOTP_SECRET=`. It is read here and
typed into `pdfs login` over a pseudo-terminal; it is never printed or written
@@ -33,6 +49,8 @@ import hashlib
import hmac
import json
import os
import random
import re
import pty
import select
import shutil
@@ -43,6 +61,7 @@ import sys
import tempfile
import time
import uuid
import zlib
from pathlib import Path
POLL = 0.1
@@ -300,6 +319,259 @@ def bench_one(
shutil.rmtree(local, ignore_errors=True)
ANSI = re.compile(r"\x1b\[[0-9;]*m")
OPERATION = re.compile(r"operation=\W*(\w+)")
METHOD = re.compile(r"method=(\w+)")
ENDPOINT = re.compile(r"endpoint=(\S+)")
SDK_LOG = "info,pgp=error,proton_sdk::telemetry=debug"
# Slower than `POLL`: each poll is a diagnostics request to the daemon, and the
# small-file scenario measures the daemon's CPU time.
SMALL_POLL = 0.5
class Requests:
"""Counts the requests the daemon logs through the SDK's telemetry, from a
byte offset of its log on."""
def __init__(self, log: Path) -> None:
self.log = log
self.offset = log.stat().st_size
def take(self) -> dict[str, int]:
with self.log.open("rb") as file:
file.seek(self.offset)
chunk = file.read()
self.offset = file.tell()
counts: dict[str, int] = {}
for line in ANSI.sub("", chunk.decode(errors="replace")).splitlines():
if "proton_sdk::telemetry" not in line:
continue
found = OPERATION.search(line)
if not found:
continue
operation = found.group(1)
if operation == "http_request":
method = METHOD.search(line)
key = f"api {method.group(1) if method else '?'}"
# SDKs that tag the endpoint also get a count per endpoint.
route = ENDPOINT.search(line)
if route:
detail = f"endpoint {method.group(1) if method else '?'} {route.group(1)}"
counts[detail] = counts.get(detail, 0) + 1
elif operation.startswith("storage_"):
key = operation.replace("_", " ")
else:
key = f"op {operation}"
counts[key] = counts.get(key, 0) + 1
return counts
def cpu_seconds(pid: int) -> float:
"""User and system CPU time of `pid` so far."""
fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
return (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK")
def noise_png(path: Path, side: int, rng: random.Random) -> None:
"""A PNG of random pixels: it does not compress, so its size is known, and
the daemon makes thumbnails for it."""
def chunk(kind: bytes, data: bytes) -> bytes:
body = kind + data
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
rows = b"".join(b"\x00" + rng.randbytes(side * 3) for _ in range(side))
path.write_bytes(
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", side, side, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(rows, 1))
+ chunk(b"IEND", b"")
)
def make_small_tree(
root: Path, files: int, size: int, images: int, rng: random.Random, per_dir: int = 50
) -> list[Path]:
paths = []
for index in range(files):
directory = root / f"d{index // per_dir:04d}"
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"f{index:06d}.bin"
path.write_bytes(rng.randbytes(size))
paths.append(path)
if images:
(root / "pictures").mkdir()
for index in range(images):
noise_png(root / "pictures" / f"p{index:04d}.png", 120, rng)
return paths
class Passes:
"""The passes over one folder that ended, as the diagnostics show them.
They keep only the last one, so poll often enough to see each."""
def __init__(self, pdfs: Pdfs, folder_id: int, stale: set[str]) -> None:
self.pdfs = pdfs
self.folder_id = folder_id
self.stale = stale
self.last: str | None = None
self.ended: list[dict] = []
def poll(self) -> dict:
state = sync_state(self.pdfs)
trace = trace_for(state, self.folder_id)
if trace and trace.get("ended") and state.get("pass_folder") != self.folder_id:
key = json.dumps(trace, sort_keys=True)
if key != self.last and key not in self.stale:
self.last = key
self.ended.append(trace)
return state
def calls(self, name: str, since: int = 0) -> int:
return sum(
call["count"]
for trace in self.ended[since:]
for call in trace.get("calls", [])
if call["name"] == name
)
def totals(self, since: int = 0) -> dict[str, dict[str, int]]:
totals: dict[str, dict[str, int]] = {}
for trace in self.ended[since:]:
for kind in ("phases", "calls"):
for stat in trace.get(kind, []):
entry = totals.setdefault(f"{kind[:-1]} {stat['name']}", {"count": 0, "ms": 0})
entry["count"] += stat["count"]
entry["ms"] += stat["total_ms"]
return totals
def wait_for(
self, what: str, name: str, at_least: int, since: int, quiet: float, timeout: float
) -> float:
"""Wait until the passes since `since` made `at_least` calls of `name`,
then until no pass ran for `quiet` seconds. Returns when the last pass
that did work was seen to end."""
deadline = time.monotonic() + timeout
while self.calls(name, since) < at_least:
if time.monotonic() > deadline:
raise TimeoutError(
f"timed out waiting for {what}: {self.calls(name, since)} of {at_least}"
)
self.poll()
time.sleep(SMALL_POLL)
done = time.monotonic()
seen = len(self.ended)
while time.monotonic() - done < quiet:
if time.monotonic() > deadline:
raise TimeoutError(f"the folder did not go quiet after {what}")
state = self.poll()
if state.get("pass_folder") == self.folder_id or len(self.ended) != seen:
seen = len(self.ended)
done = time.monotonic()
time.sleep(SMALL_POLL)
return done
def phase_result(
files: int, wall: float, cpu: float, requests: dict[str, int], passes: Passes, since: int
) -> dict:
sent = sum(n for key, n in requests.items() if key.startswith(("api ", "storage upload")))
return {
"files": files,
"wall_s": round(wall, 2),
"files_per_s": round(files / wall, 3) if wall else None,
"cpu_s": round(cpu, 2),
"cpu_ms_per_file": round(cpu * 1000 / files) if files else None,
"requests": requests,
"requests_per_file": round(sent / files, 2) if files else None,
"passes": len(passes.ended) - since,
"totals": passes.totals(since),
}
def bench_small(
pdfs: Pdfs, daemon_pid: int, mount: Path, work: Path, files: int, args: argparse.Namespace
) -> dict:
rng = random.Random(files)
name = f"pdfs-bench-small-{files}-{uuid.uuid4().hex[:8]}"
local = work / name
local.mkdir()
paths = make_small_tree(local, files, args.small_size, args.images, rng)
uploads = files + args.images
pdfs.run("mkdir", str(mount), name)
folder_id = None
try:
stale = {json.dumps(t, sort_keys=True) for t in sync_state(pdfs).get("traces", [])}
requests = Requests(work / "daemon.log")
cpu = cpu_seconds(daemon_pid)
started = time.monotonic()
pdfs.run("sync", "attach", "--to", name, str(local))
folder = next(
item
for item in pdfs.json("sync", "list")["items"]
if Path(item["local_path"]).resolve() == local.resolve()
)
folder_id = folder["id"]
passes = Passes(pdfs, folder_id, stale)
done = passes.wait_for("the first sync", "upload", uploads, 0, args.quiet, args.timeout)
first = phase_result(
uploads, done - started, cpu_seconds(daemon_pid) - cpu, requests.take(), passes, 0
)
edits = min(args.edits, files)
edited = rng.sample(paths, edits)
since = len(passes.ended)
cpu = cpu_seconds(daemon_pid)
started = time.monotonic()
for path in edited:
path.write_bytes(rng.randbytes(args.small_size))
done = passes.wait_for(
"the edits", "upload revision", edits, since, args.quiet, args.timeout
)
edit = phase_result(
edits, done - started, cpu_seconds(daemon_pid) - cpu, requests.take(), passes, since
)
# The counts say the edits were sent; a few read back say they landed.
for path in edited[:3]:
remote_path = f"{name}/{path.relative_to(local)}"
wait("the edit on Drive", lambda p=remote_path: revisions(pdfs, p) >= 2, args.timeout)
return {
"scenario": "small",
"files": files,
"images": args.images,
"size": args.small_size,
"first_sync": first,
"edits": edit,
}
finally:
if folder_id is not None:
for _ in range(20):
try:
pdfs.run("sync", "rm", str(folder_id))
break
except Exception as error: # noqa: BLE001
print(f" sync rm: {error}; retrying", file=sys.stderr)
time.sleep(6)
with contextlib.suppress(Exception):
pdfs.run("rm", f"{mount}/{name}")
shutil.rmtree(local, ignore_errors=True)
def print_small(result: dict) -> None:
print(f"{result['files']:>6} files of {result['size']} B and {result['images']} images:")
for phase in ("first_sync", "edits"):
r = result[phase]
sent = ", ".join(
f"{k} {v}" for k, v in sorted(r["requests"].items()) if not k.startswith(("op ", "endpoint "))
)
print(
f" {phase}: {r['files']} files in {r['wall_s']} s ({r['files_per_s']}/s), "
f"CPU {r['cpu_s']} s ({r['cpu_ms_per_file']} ms/file), "
f"{r['requests_per_file']} requests/file over {r['passes']} passes"
)
print(f" requests: {sent}")
def refuse_without_instances(binary: str) -> None:
"""Stop unless `binary` honours PDFS_INSTANCE. One built before it existed
ignores the variable and would sign in, attach and delete on the default
@@ -348,7 +620,11 @@ def main() -> int:
parser.add_argument("--account-env", type=Path, required=True, help="env file with the test account")
parser.add_argument("--pdfs", default="pdfs", help="the pdfs CLI to run")
parser.add_argument("--instance", default="bench", help="PDFS_INSTANCE to run under")
parser.add_argument("--sizes", default="20,500", help="tree sizes, comma-separated")
parser.add_argument("--scenario", choices=("edit", "small"), default="edit", help="what to time")
parser.add_argument("--sizes", help="tree sizes, comma-separated (default 20,500; 200 for small)")
parser.add_argument("--small-size", type=int, default=4096, help="bytes per file (small)")
parser.add_argument("--images", type=int, default=10, help="noise PNGs with thumbnails (small)")
parser.add_argument("--edits", type=int, default=50, help="files rewritten at once (small)")
parser.add_argument("--timeout", type=float, default=3600, help="seconds per wait")
parser.add_argument(
"--quiet", type=float, default=15, help="seconds without a pass before the edit"
@@ -368,8 +644,11 @@ def main() -> int:
work = args.work or Path(tempfile.mkdtemp(prefix="pdfs-bench-"))
work.mkdir(parents=True, exist_ok=True)
log = (work / "daemon.log").open("w")
daemon_env = dict(pdfs.env)
if args.scenario == "small":
daemon_env["RUST_LOG"] = SDK_LOG
daemon = subprocess.Popen(
[args.pdfs, "daemon"], env=pdfs.env, stdin=subprocess.DEVNULL, stdout=log, stderr=log
[args.pdfs, "daemon"], env=daemon_env, stdin=subprocess.DEVNULL, stdout=log, stderr=log
)
results = []
try:
@@ -380,9 +659,14 @@ def main() -> int:
)
mount = Path(status["mount"].get("mountpoint") or Path.home() / f"ProtonDrive-{args.instance}")
remove_leftovers(pdfs, mount)
for size in (int(s) for s in args.sizes.split(",")):
result = bench_one(pdfs, mount, work, size, args.timeout, args.quiet)
print_result(result)
sizes = args.sizes or ("200" if args.scenario == "small" else "20,500")
for size in (int(s) for s in sizes.split(",")):
if args.scenario == "small":
result = bench_small(pdfs, daemon.pid, mount, work, size, args)
print_small(result)
else:
result = bench_one(pdfs, mount, work, size, args.timeout, args.quiet)
print_result(result)
results.append(result)
if args.json:
args.json.write_text(json.dumps(results, indent=2))