存檔移到背景執行緒,長對話存得疏一點:視窗不再每 5 秒卡一下

jenny-Host 的 AnyBot 視窗執行緒 18 小時用了 15 小時 CPU:她現在這段對話 36 000 則、95 MB,Bot 工作時
每 5 秒在視窗執行緒上整份轉成文字、寫檔、同步到磁碟(2 核、沒有顯示卡,iowait 26%)。

- 存檔在自己的執行緒寫;視窗只拿一份快照(對話是共用的,寫的時候才複製)。
- 一次只有一個存檔在寫;比較晚拿的快照才算數,舊的不會蓋掉新的(關閉時同步存檔會等背景那個寫完)。
- Bot 工作時的存檔間隔:5 秒,對話每 2000 則加 1 秒,最多 30 秒。
- 打字送出的訊息,要等它所在的存檔真的寫好,工作紀錄才放掉它(關閉時也一樣)。

量測(本機 M 系列,release,perf_long_chat:36 000 則、153 MB):
  改前每次存檔視窗執行緒 160–230 ms;改後 0.05–0.3 ms 交出去,寫的時候剛好來一則訊息多 10–28 ms。
  畫面本身每格 0–12 ms(只畫看得到的那幾則),不是瓶頸。

已驗證: cargo test 全綠(930 通過);新測試 an_older_copy_never_lands_over_a_newer_one;
  perf_long_chat(#[ignore],量測用)。
未驗證: jenny-Host 實機的改善幅度(沒有 root 不能 perf;要等換版後看視窗執行緒的 CPU)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-27 16:07:47 +08:00
parent bf3a19fb08
commit 7ca0646881
3 changed files with 181 additions and 10 deletions

View File

@ -231,6 +231,8 @@ pub struct App {
delivered: Vec<(u64, String)>, delivered: Vec<(u64, String)>,
/// Save at the next frame (a typed message just entered a chat), not up to 2 s later. /// Save at the next frame (a typed message just entered a chat), not up to 2 s later.
save_now: bool, save_now: bool,
/// A save writing on its own thread, and the typed messages it carries (see `delivered`).
saving: Option<(Receiver<bool>, Vec<(u64, String)>)>,
/// 設定 › 一般 › 文件索引: the path being typed for a new folder. /// 設定 › 一般 › 文件索引: the path being typed for a new folder.
doc_new: String, doc_new: String,
/// The folder typed in 設定 › 一般 wasn't found. /// The folder typed in 設定 › 一般 wasn't found.
@ -577,6 +579,7 @@ impl App {
pending_turns: vec![], pending_turns: vec![],
delivered: vec![], delivered: vec![],
save_now: false, save_now: false,
saving: None,
doc_new: String::new(), doc_new: String::new(),
doc_new_bad: false, doc_new_bad: false,
interrupted, interrupted,
@ -7275,16 +7278,33 @@ impl App {
} }
fn save_if_dirty(&mut self) { fn save_if_dirty(&mut self) {
// (While a bot works, every 5 s: each save writes that bot's whole chat — megabytes on a // The save on its own thread: done, its typed messages are on disk in their chats and
// long one — and the work log already keeps what happened in between.) // the work log can let them go; still writing, the next one waits for it.
if self.dirty && !self.demo && (self.streams.is_empty() || self.save_now || self.last_save.elapsed().as_secs() >= 5) { if let Some((rx, _)) = &self.saving {
if self.mir.on { match rx.try_recv() {
self.mirror_save(); Err(std::sync::mpsc::TryRecvError::Empty) => return,
} else if self.state.save() { got => {
// Typed messages now on disk in their chats: the work log can let them go. let carried = self.saving.take().map(|(_, c)| c).unwrap_or_default();
for (bot, id) in std::mem::take(&mut self.delivered) { if got == Ok(true) {
for (bot, id) in carried {
crate::oplog::OpLog::for_bot(bot).append(&crate::oplog::Record::QueueConsumed { id }); crate::oplog::OpLog::for_bot(bot).append(&crate::oplog::Record::QueueConsumed { id });
} }
} else {
self.delivered.splice(0..0, carried);
}
}
}
}
// (While a bot works, every 5 s — longer on a long chat, up to 30 s: each save writes
// that bot's whole chat, megabytes on a long one, and the work log already keeps what
// happened in between.)
let longest = self.streams.keys().filter_map(|id| self.state.bot(*id)).map(|b| b.messages.len()).max().unwrap_or(0);
let every = (longest as u64 / 2_000).clamp(5, 30);
if self.dirty && !self.demo && (self.streams.is_empty() || self.save_now || self.last_save.elapsed().as_secs() >= every) {
if self.mir.on {
self.mirror_save();
} else {
self.saving = Some((self.state.save_in_background(), std::mem::take(&mut self.delivered)));
} }
self.dirty = false; self.dirty = false;
self.save_now = false; self.save_now = false;
@ -7725,6 +7745,9 @@ impl eframe::App for App {
self.save_if_dirty(); self.save_if_dirty();
if !self.demo { if !self.demo {
ctx.request_repaint_after(std::time::Duration::from_secs(if self.streams.is_empty() && self.model_fetch.is_empty() { 15 } else { 1 })); ctx.request_repaint_after(std::time::Duration::from_secs(if self.streams.is_empty() && self.model_fetch.is_empty() { 15 } else { 1 }));
if self.saving.is_some() {
ctx.request_repaint_after(std::time::Duration::from_millis(200));
}
} }
} }
@ -7877,8 +7900,13 @@ impl eframe::App for App {
if self.mir.on { if self.mir.on {
self.mirror_save(); self.mirror_save();
self.mirror_flush_copy(true); self.mirror_flush_copy(true);
} else { } else if self.state.save() {
self.state.save(); // (Waits for a save still writing on its own thread; then the typed messages
// of both are on disk.)
let carried = self.saving.take().map(|(_, c)| c).unwrap_or_default();
for (bot, id) in carried.into_iter().chain(std::mem::take(&mut self.delivered)) {
crate::oplog::OpLog::for_bot(bot).append(&crate::oplog::Record::QueueConsumed { id });
}
} }
} }
} }

View File

@ -983,3 +983,80 @@ fn a_handed_files_mark_tells_where_it_was_seen() {
assert_eq!(b.messages.last().unwrap().attachments[0].seen.len(), 3); assert_eq!(b.messages.last().unwrap().attachments[0].seen.len(), 3);
assert!(b.messages[b.messages.len() - 2].attachments[0].seen.is_empty()); assert!(b.messages[b.messages.len() - 2].attachments[0].seen.is_empty());
} }
/// How long a frame and a save take on a chat as long as jenny-Host's (36 000 messages, ~95 MB):
/// a measurement, not a check. `cargo test --release perf_long_chat -- --ignored --nocapture`.
#[test]
#[ignore]
fn perf_long_chat() {
let ctx = egui::Context::default();
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-perf.png")));
let sel = app.state.selected;
let long = "這是一段工具結果,貼文內容與留言清單。".repeat(120);
let think = "我要先打開貼文再找回覆框。".repeat(30);
let mut msgs = vec![];
for i in 0..18_000i64 {
let id = format!("c{i}");
let args = format!("{{\"profile\":\"女生(Firefox)\",\"url\":\"https://www.threads.com/@someone/post/{i}\"}}");
let mut a = Message::assistant("", "OpenCode Go · deepseek-v4.1-flash");
a.thinking = think.clone();
a.at = 1_700_000_000_000 + i * 2_000;
a.tool_calls = vec![crate::model::ToolCall { id: id.clone(), name: "browser_open".into(), args, status: crate::model::ToolStatus::Done }];
let mut r = Message::tool_result(&id, "browser_open", &long);
r.at = a.at + 1_000;
r.folded = i < 9_000;
msgs.push(a);
msgs.push(r);
}
app.state.bot_mut(sel).unwrap().messages = msgs.into();
app.state.bot_mut(sel).unwrap().messages.push(Message::user("最後一句"));
app.streams.insert(sel, Live { cancel: Arc::new(AtomicBool::new(false)), started: Instant::now(), last: Instant::now(), produced: true, status: Some("執行中".into()), paused: false, paused_at: None, unattended: false, steer: Arc::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "perf".into(), turn: 0 });
let size = egui::vec2(1280.0, 800.0);
let mut frame = eframe::Frame::_new_kittest();
let mut times = vec![];
for f in 0..12 {
if f >= 6 {
app.state.bot_mut(sel).unwrap().messages.push(Message::tool_result("x", "browser_open", "新的一步"));
}
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() };
let t = std::time::Instant::now();
let mut out = ctx.run_ui(input, |ui| app.ui(ui, &mut frame));
times.push(t.elapsed().as_millis());
let texts = out.shapes.iter().filter(|c| matches!(c.shape, egui::epaint::Shape::Text(_))).count();
if times.len() == 12 {
println!("PERF last frame shapes {} texts {texts}", out.shapes.len());
}
out.textures_delta.clear();
}
println!("PERF frames ms: {times:?}");
let dir = std::env::temp_dir().join(format!("anybot-perf-{}", std::process::id()));
let p = dir.join("state.json");
for k in 0..3 {
app.state.bot_mut(sel).unwrap().messages.last_mut().unwrap().text.push_str("x");
let t = std::time::Instant::now();
app.state.save_at(&p);
println!("PERF save {k} ms: {}", t.elapsed().as_millis());
}
for k in 0..3 {
let t = std::time::Instant::now();
let rx = app.state.save_in_background();
let start = t.elapsed().as_micros();
let t = std::time::Instant::now();
app.state.bot_mut(sel).unwrap().messages.push(Message::user("寫入中又來一句"));
let during = t.elapsed().as_millis();
let t = std::time::Instant::now();
let ok = rx.recv().unwrap();
println!("PERF background save {k}: window thread {start} µs to start, {during} ms for a message arriving while it writes; written in {} ms more ({ok})", t.elapsed().as_millis());
}
let msgs = app.state.bot(sel).unwrap().messages.clone();
let t = std::time::Instant::now();
let bytes = serde_json::to_vec(&*msgs).unwrap();
println!("PERF serialize ms: {} ({} MB)", t.elapsed().as_millis(), bytes.len() / 1_000_000);
let t = std::time::Instant::now();
let copy: Vec<Message> = (*msgs).clone();
println!("PERF deep copy ms: {} ({})", t.elapsed().as_millis(), copy.len());
let t = std::time::Instant::now();
crate::httpd::write_private(&dir.join("x.json"), &bytes).unwrap();
println!("PERF write+fsync ms: {}", t.elapsed().as_millis());
let _ = std::fs::remove_dir_all(&dir);
}

View File

@ -305,6 +305,18 @@ fn chat_mark(b: &Bot) -> u64 {
} }
/// What each chat file holds now (its mark), so an unchanged chat isn't written again. /// What each chat file holds now (its mark), so an unchanged chat isn't written again.
/// The order saves were asked for (a copy taken later is newer).
fn next_save() -> u64 {
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
N.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1
}
/// Each place's newest save on disk (see save_in_order).
fn saves_done() -> &'static std::sync::Mutex<std::collections::HashMap<PathBuf, u64>> {
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<PathBuf, u64>>> = std::sync::OnceLock::new();
M.get_or_init(Default::default)
}
fn chat_marks() -> &'static std::sync::Mutex<std::collections::HashMap<(PathBuf, u64), u64>> { fn chat_marks() -> &'static std::sync::Mutex<std::collections::HashMap<(PathBuf, u64), u64>> {
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<(PathBuf, u64), u64>>> = std::sync::OnceLock::new(); static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<(PathBuf, u64), u64>>> = std::sync::OnceLock::new();
M.get_or_init(Default::default) M.get_or_init(Default::default)
@ -1240,8 +1252,40 @@ impl State {
self.save_at(&Self::path()) self.save_at(&Self::path())
} }
/// Write everything to disk on a thread of its own; the receiver says whether it got there.
/// The copy is taken now and costs little (the chats are shared, copied only when written
/// to); writing it is what cost: jenny-Host's chat of 36 000 messages, 95 MB, was turned to
/// text and synced to disk on the window's thread every 5 s while her bot worked — the
/// window stood still for a second or more each time (a 2-core computer, no graphics card).
pub fn save_in_background(&self) -> std::sync::mpsc::Receiver<bool> {
let (copy, p, order) = (self.clone(), Self::path(), next_save());
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(copy.save_in_order(&p, order));
});
rx
}
/// Write the settings to `p` and each chat that changed to its own file beside it. /// Write the settings to `p` and each chat that changed to its own file beside it.
pub fn save_at(&self, p: &std::path::Path) -> bool { pub fn save_at(&self, p: &std::path::Path) -> bool {
self.save_in_order(p, next_save())
}
/// One save at a time to a place, and never an older copy over a newer one: a save on its
/// own thread may still be writing when the window saves at quitting.
fn save_in_order(&self, p: &std::path::Path, order: u64) -> bool {
let mut done = saves_done().lock().unwrap_or_else(|e| e.into_inner());
if done.get(p).is_some_and(|d| *d > order) {
return true;
}
let ok = self.write_at(p);
if ok {
done.insert(p.to_path_buf(), order);
}
ok
}
fn write_at(&self, p: &std::path::Path) -> bool {
let p = p.to_path_buf(); let p = p.to_path_buf();
// (The save that couldn't be read at start, nor moved aside, is still there.) // (The save that couldn't be read at start, nor moved aside, is still there.)
if KEEP_UNREAD_SAVE.load(std::sync::atomic::Ordering::SeqCst) && p.exists() { if KEEP_UNREAD_SAVE.load(std::sync::atomic::Ordering::SeqCst) && p.exists() {
@ -1731,6 +1775,28 @@ mod start_tests {
/// The settings are one small file; each chat is its own, written only when it changed, and /// The settings are one small file; each chat is its own, written only when it changed, and
/// a save from before (chats inside the settings) is taken as it is. /// a save from before (chats inside the settings) is taken as it is.
/// A save writing on its own thread and one asked for later: the later copy is what stays
/// on disk, whichever finishes writing last.
#[test]
fn an_older_copy_never_lands_over_a_newer_one() {
let dir = std::env::temp_dir().join(format!("anybot-save-order-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let p = dir.join("state.json");
let mut old = State::samples();
let a = old.bots[0].id;
old.bots[0].messages = vec![Message::user("舊的")].into();
let (first, second) = (next_save(), next_save());
let mut new = old.clone();
new.bots[0].messages.push(Message::user("新的"));
assert!(new.save_in_order(&p, second));
assert!(old.save_in_order(&p, first), "nothing lost: a newer copy is there");
assert!(std::fs::read_to_string(chat_path(&p, a)).unwrap().contains("新的"));
// And in order, as always.
assert!(old.save_at(&p));
assert!(!std::fs::read_to_string(chat_path(&p, a)).unwrap().contains("新的"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test] #[test]
fn chats_are_saved_apart_and_only_when_they_change() { fn chats_are_saved_apart_and_only_when_they_change() {
let dir = std::env::temp_dir().join(format!("anybot-chats-apart-{}", std::process::id())); let dir = std::env::temp_dir().join(format!("anybot-chats-apart-{}", std::process::id()));