perf: Save and Save As write on a worker thread (#3044) (#3146)

Save ran on the window's thread: about 130 ms on the Prusa Core One design,
and more than a second once saves keep the evaluated model. The toolbar's
Save and Save As now run the command on a scratch copy of the session on a
worker; the design waits for it as it waits for a file picker (commands are
refused meanwhile), and the outcome is taken up as running the command here
would have left it: the name and links the save gave the design, its file,
its saved state (`Session::adopt_save`), the echo, the error status, the
recent files and the home thumbnail. A tab closing or the app quitting after
Save waits for the write, as does the app's exit. Scripts, the control
channel and the browser build still save in place.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bherbruck
2026-10-20 00:19:29 +00:00
committed by GitHub
parent e661e6f809
commit 9e7a7b260b
8 changed files with 174 additions and 9 deletions
+2
View File
@@ -91,6 +91,8 @@ impl eframe::App for App {
fn on_exit(&mut self) {
// The agent chat's agent and everything it started end with the app.
solidcraft_ui_egui::agent_chat::shutdown(&mut self.solve);
// A save still being written ends before the app does.
solidcraft_ui_egui::save_job::tick(&mut self.solve, true);
solidcraft_ui_egui::recovery_ui::close(&mut self.solve);
solidcraft_engine::crash::end_session();
// An update asked to restart into the new version or to run its installer.
+44
View File
@@ -382,6 +382,22 @@ fn write_bytes(
}
impl Session {
/// Take up a save that ran on `done`, a [`Session::scratch`] copy of this session that
/// `file.save` or `file.save_as` ran on (on another thread, so the window keeps drawing)
/// while this one did not change: the name and link paths the save gave the design, its
/// file, and its saved state, as running the command here would have left them.
pub fn adopt_save(&mut self, done: &Session) {
if done.doc.name != self.doc.name {
let (from, to) = (self.doc.name.clone(), done.doc.name.clone());
rename_design(self, &from, &to);
}
if done.doc.links != self.doc.links {
self.doc_mut().links.clone_from(&done.doc.links);
}
self.path.clone_from(&done.path);
self.mark_saved();
}
/// Container bytes for desktop and browser saves. Only already evaluated bodies
/// and warm meshes are eligible; saving never forces evaluation or tessellation.
pub fn design_container(&self, compression: solidcraft_io::DesignCompression, preview: bool, cache: bool) -> solidcraft_io::Result<Vec<u8>> {
@@ -645,6 +661,34 @@ mod urdf_tests;
mod tests {
use super::*;
/// #3044: a save run on a scratch copy of the session (on a worker, so the window keeps
/// drawing) and taken up with `adopt_save` leaves the session as saving it directly does:
/// the design named after its first file, its file, and nothing unsaved; undo keeps the name.
#[test]
fn a_save_run_on_a_copy_and_adopted_matches_saving_directly() {
let dir = std::env::temp_dir().join(format!("solidcraft-adopt-save-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut direct = Session::default();
direct.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap();
let mut adopted = Session::new((*direct.doc).clone());
adopted.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap();
let a = dir.join("Bracket.solidcraft");
let b = dir.join("Bracket copy.solidcraft");
direct.execute("file.save_as", &json!({"path": a.to_string_lossy()})).unwrap();
let mut copy = adopted.scratch();
copy.path.clone_from(&adopted.path);
copy.execute("file.save_as", &json!({"path": b.to_string_lossy()})).unwrap();
assert!(adopted.is_dirty(), "nothing taken up yet");
adopted.adopt_save(&copy);
assert!(!adopted.is_dirty());
assert_eq!(adopted.path.as_deref(), b.to_str());
assert_eq!(adopted.doc.name, "Bracket copy");
assert_eq!(direct.doc.name, "Bracket");
assert_eq!(adopted.undo.iter().map(|u| u.doc.name.clone()).collect::<Vec<_>>(), vec!["Bracket copy".to_string(); adopted.undo.len()]);
assert_eq!(solidcraft_io::read_design(&std::fs::read(&b).unwrap()).unwrap(), *adopted.doc);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "manual warmed engine save and provisional-open benchmark"]
fn benchmark_warm_design_save_with_preview() {
+2
View File
@@ -761,6 +761,7 @@ mod tests {
assert_eq!(a.docs.closing, Some(0), "the first unsaved design is asked about first");
assert_eq!(a.docs.active, 0, "and shown");
answer_prompt(&mut a, Answer::Save);
crate::save_job::tick(&mut a, true);
assert!(!dirty(&a, 0), "saved");
assert_eq!(
std::fs::read(&file).ok().and_then(|b| solidcraft_engine::io::read_design(&b).ok()).map(|d| d.features.len()),
@@ -802,6 +803,7 @@ mod tests {
answer_prompt(&mut a, Answer::Save);
assert!(!a.quit_requested && a.file_picker_busy());
crate::file_picker::tick(&mut a, &egui::Context::default());
crate::save_job::tick(&mut a, true);
assert!(a.quit_requested && file.exists());
let _ = std::fs::remove_file(&file);
}
+4 -1
View File
@@ -29,8 +29,9 @@ impl Wake for Repaint {
impl SolveApp {
/// Keep the target design and editors unchanged until the picker answers.
/// (A save being written keeps it unchanged too, see [`crate::save_job`].)
pub fn file_picker_busy(&self) -> bool {
self.file_picker.is_some()
self.file_picker.is_some() || self.saving.is_some()
}
pub(crate) fn pick_open(&mut self, complete: impl FnOnce(&mut SolveApp, Option<String>) + 'static) {
@@ -175,6 +176,8 @@ mod tests {
waker.wake();
}
tick(app, &egui::Context::default());
// A save the answer started is written on a worker: wait for it.
crate::save_job::tick(app, true);
assert!(!app.file_picker_busy());
}
+17 -3
View File
@@ -141,6 +141,7 @@ pub mod render_workspace;
mod revolve_edit_tests;
#[cfg(test)]
mod revolve_manipulator_tests;
pub mod save_job;
pub mod scenario;
pub mod select_other;
pub mod selection;
@@ -311,6 +312,8 @@ pub struct SolveApp {
pub pre_sketch_marker: Option<Option<usize>>,
pub services: Services,
file_picker: Option<file_picker::Pending>,
/// A Save or Save As being written on a worker (see [`save_job`]).
saving: Option<save_job::Saving>,
pub viewport: viewport::ViewportState,
pub render_workspace: render_workspace::State,
pub tool: Option<tools::Tool>,
@@ -452,6 +455,7 @@ impl SolveApp {
pre_sketch_marker: None,
services,
file_picker: None,
saving: None,
viewport: viewport::ViewportState::default(),
render_workspace,
tool: None,
@@ -652,7 +656,7 @@ impl SolveApp {
/// Run a command programmatically (JSON parameters, no dialogs).
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
if self.file_load.busy() || self.file_picker.is_some() {
if self.file_load.busy() || self.file_picker.is_some() || self.saving.is_some() {
return Err("a file operation is in progress".into());
}
let t0 = now_ms();
@@ -683,7 +687,14 @@ impl SolveApp {
// Curves drawn in construction (or centerline) mode take that line type.
sketch_palette::apply_mode(self, id, v);
}
match &r {
self.finish_command(id, &r);
r
}
/// What follows a command's run, whether it ran here or on a worker (a save): its echo,
/// the status line when it failed, what opening and saving update, and the toolbar tab.
pub(crate) fn finish_command(&mut self, id: &str, r: &Result<Value, String>) {
match r {
Ok(v) => {
// Programmatic callers (the control channel, scripts) run outside a render
// language scope, so resolve the echo from the saved preference instead of the
@@ -735,7 +746,6 @@ impl SolveApp {
self.ui.tab = "SOLID".into();
self.tool = None;
}
r
}
/// Start a command the way a toolbar click does: interactive tools and dialogs for commands
@@ -1295,6 +1305,10 @@ impl SolveApp {
render_workspace::sync_backend(self);
render_workspace::tick(self, ctx);
file_load::tick(self, ctx);
save_job::tick(self, false);
if self.saving.is_some() {
ctx.request_repaint_after(std::time::Duration::from_millis(16));
}
self.esc_handled = false;
prefs::apply(self, ctx);
if !self.styled || theme::is_dark() != self.ui.dark || theme::vision() != self.preferences.color_vision {
+95
View File
@@ -0,0 +1,95 @@
//! Save and Save As off the window's thread (#3044): writing a large design (and the model a
//! save keeps with it) takes long enough that the window must keep drawing meanwhile. The
//! command runs on a copy of the session on a worker; the design waits for it like it waits for
//! a file picker, and the outcome is taken up as running the command here would have left it.
use serde_json::Value;
use solidcraft_engine::Session;
use crate::SolveApp;
/// A save being written on a worker thread.
pub struct Saving {
command: &'static str,
done: std::sync::mpsc::Receiver<(Session, Result<Value, String>)>,
}
/// Run `file.save` or `file.save_as` with `params`. On the desktop it runs on a worker and is
/// taken up by [`tick`] (true: it is under way); in the browser, or when no thread can start, it
/// runs here and is finished on return (false).
pub fn start(app: &mut SolveApp, command: &'static str, params: Value) -> bool {
#[cfg(not(target_arch = "wasm32"))]
if app.saving.is_none() && app.file_picker.is_none() && !app.file_load.busy() {
let mut copy = app.session.scratch();
// The copy has no file: the command saves to this session's (and names the design after it).
copy.path.clone_from(&app.session.path);
let (tx, rx) = std::sync::mpsc::channel();
let given = params.clone();
let job = std::thread::Builder::new().name("save".into()).spawn(move || {
let r = copy.execute(command, &given).map_err(|e| e.to_string());
let _ = tx.send((copy, r));
});
if job.is_ok() {
app.saving = Some(Saving { command, done: rx });
return true;
}
// No thread to write on: save here, as before.
}
let _ = app.run(command, params);
false
}
/// Take up a finished save (`wait`: wait for a running one).
pub fn tick(app: &mut SolveApp, wait: bool) {
let Some(saving) = app.saving.as_ref() else { return };
let outcome = if wait {
saving.done.recv().ok()
} else {
match saving.done.try_recv() {
Ok(outcome) => Some(outcome),
Err(std::sync::mpsc::TryRecvError::Empty) => return,
Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
}
};
let Some(Saving { command, .. }) = app.saving.take() else { return };
let r = match outcome {
Some((copy, Ok(v))) => {
app.session.adopt_save(&copy);
Ok(v)
}
Some((_, Err(e))) => Err(e),
None => Err(format!("{command}: the save stopped")),
};
app.finish_command(command, &r);
crate::documents::saved_for_close(app);
}
#[cfg(test)]
mod tests {
use serde_json::json;
/// #3044: Save writes on a worker while the window keeps drawing; the design waits (commands
/// are refused) until the save is taken up, which leaves it saved under its file, in the
/// recent files, with the command echoed, as a save run here does.
#[test]
fn save_writes_on_a_worker_and_is_taken_up_like_a_save_here() {
let mut h = crate::scenario::Harness::new();
h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
let path = h.dir.join("Plate.solidcraft");
assert!(super::start(&mut h.app, "file.save_as", json!({"path": path.to_string_lossy()})), "under way on a worker");
assert!(h.app.file_picker_busy() && h.app.run("solid.sphere", json!({"diameter": 4})).is_err(), "the design waits for it");
h.frame();
h.settle();
assert!(h.app.saving.is_none() && !h.app.session.is_dirty());
assert_eq!(h.app.session.path.as_deref(), path.to_str());
assert_eq!(h.app.session.doc.name, "Plate");
assert!(h.app.home.recent.iter().any(|r| r.as_str() == path.to_str().unwrap()), "{:?}", h.app.home.recent);
assert!(h.app.session.log.iter().any(|l| l.contains("Save As")), "{:?}", h.app.session.log);
// A failing save reports why, and leaves the changes unsaved.
h.app.run("solid.sphere", json!({"diameter": 4})).unwrap();
let bad = h.dir.join("missing").join("x.solidcraft");
super::start(&mut h.app, "file.save_as", json!({"path": bad.to_string_lossy()}));
super::tick(&mut h.app, true);
assert!(h.app.session.is_dirty() && h.app.status.as_ref().is_some_and(|(_, _, error)| *error));
}
}
+2 -2
View File
@@ -254,9 +254,9 @@ impl Harness {
}
self.frame();
}
// A file opening or recovering in the background: wait for it (as a person would).
// A file opening, recovering or saving in the background: wait for it (as a person would).
let began = std::time::Instant::now();
while !self.app.file_load.idle() && began.elapsed() < std::time::Duration::from_secs(120) {
while (!self.app.file_load.idle() || self.app.saving.is_some()) && began.elapsed() < std::time::Duration::from_secs(120) {
self.frame();
std::thread::sleep(std::time::Duration::from_millis(1));
}
+8 -3
View File
@@ -596,7 +596,7 @@ pub fn save(app: &mut SolveApp) {
return;
}
if app.session.path.is_some() {
let _ = app.run("file.save", json!({}));
crate::save_job::start(app, "file.save", json!({}));
} else {
save_as(app);
}
@@ -609,8 +609,11 @@ fn save_as(app: &mut SolveApp) {
fn save_as_with_extension(app: &mut SolveApp, extension: &str) {
let name = format!("{}.{extension}", app.session.doc.name);
app.pick_save(&name, &[solidcraft_engine::io::DESIGN_EXT, "json"], |app, path| {
if let Some(path) = path {
let _ = app.run("file.save_as", json!({"path": path}));
// A save under way answers a closing tab when it ends.
if let Some(path) = path
&& crate::save_job::start(app, "file.save_as", json!({"path": path}))
{
return;
}
crate::documents::saved_for_close(app);
});
@@ -1467,6 +1470,8 @@ mod header_report_tests {
h.frames(3);
h.step(&json!({"click":{"handle":"appbar:folder"}})).unwrap();
h.step(&json!({"widget":"Save As JSON…"})).unwrap();
// Written on a worker: the window keeps drawing until it is done.
h.settle();
let saved = h.app.session.path.clone().unwrap();
let bytes = std::fs::read(&saved).unwrap();
assert!(!solidcraft_engine::io::is_design_container(&bytes));