AnyBot/src/chatarchive.rs

463 lines
21 KiB
Rust
Raw Normal View History

對話不再無限長大:長對話較早的部分收進封存檔,只留最近約 2000 則 jenny-Host 的對話 36 000 則、95 MB:整份放在記憶體,每次存檔整份重寫,每格畫面整份排過一次。 現在這段對話超過 2500 則、Bot 閒著(沒在做事、沒卡片、沒在通話)時,切在使用者說的一句之前、 不越過最新的摘要(Bot 讀到的不變),較早的寫進 chats/archive/bot-<id>/<起點>-<則數>.json (500 則一個、寫好就不再改、寫完同步到磁碟),記憶體和聊天檔只留最近約 2000 則。 - 整段對話的編號 = 封存數 + 記憶體裡的位置:手機的 index、載入更早的、表情回應、搜尋的前往都照整段算, 手機頁面和伺服器不用改。 - 桌面:最上面「更早的 N 則已封存/載入更早的」,載入的只看不存(畫在另一個 id 下); 搜尋到封存裡的那則就載入前後各 100 則並捲過去,下面有「載入後面的」。 - 搜尋、熱度圖、所有檔案:封存的話第一次在背景讀成精簡清單(chatarchive::said)。 - 開新對話、/rewind、/fork、匯出、備份、搬到大腦用整段;清除連封存一起;附件清理算進封存的附件 (讀不齊或有保留的封存時整晚不清)。分享匯出入、支線、團隊成員不帶封存欄位。 - 封存數、第一句、指紋(最後一則的時間)跟訊息寫在同一個聊天檔:任何時候停掉都對得上。 整理只在 App 自己啟動時做,只對聊天檔有寫封存數的 Bot;退役的封存只在對得上的那一個沒存好時找回, 對得上之後才刪其他的;舊版 AnyBot 寫的聊天檔照資料夾接回(緊接著才接); 讀不齊的、不屬於現在對話的封存移到 .kept- 資料夾,永遠不刪。設定讀不到時什麼都不刪;刪 Bot 時才刪它的封存。 - 寫不進去 10 分鐘後再試,不每格重試。 獨立審查(乾淨脈絡)四輪:第一輪 3 個 P0(停在聊天檔和設定之間、別的指令讀設定時清理、換對話後沒存好) 和 4 個 P1;第二輪 1 個 P0(兩個退役資料夾搬錯)、1 個 P1(舊版改寫聊天檔);第三輪 1 個 P0(設定讀不到時全刪); 第四輪剩 1 個 P1(沒接回的舊封存在下次封存被蓋掉),已修。每個都有測試。 已驗證: cargo test 全綠(938 通過,含 featuremap::、layout_audit::);新測試 chatarchive::、 a_long_chat_keeps_its_newest_and_comes_back_whole、a_stop_at_any_moment_loses_no_archived_message、 the_right_archive_comes_back_and_an_old_writer_loses_nothing、an_archived_head_is_still_the_same_conversation_everywhere; verify-anybot 實跑兩次(36 000 則:聊天檔 28 MB → 1.5 MB、68 個封存檔、手機 API 跨封存載入編號連續、 搜尋找得到封存、重開後還在;證據 target/verify-anybot/20261127-172809、20261127-175512)。 未驗證: 手機頁面點搜尋結果跳到很舊的一則(手機本來就只留最近的,提示「那則訊息太早了」,未改); 顯示大腦的另一台電腦上載入封存(設計上不提供);第二階段「過去的對話」(threads,88 MB)還沒拆。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:55:41 +00:00
//! 封存: the open conversation's oldest messages, kept on disk and out of memory.
//!
//! A bot that works all day never stopped growing its chat: jenny-Host's reached 36 000 messages
//! and 95 MB, held in memory, written whole on every save and laid out whole every frame — the
//! window stood at 90 % of a core. Now, once a chat passes ARCHIVE_AT messages and its bot is
//! idle, its head (up to the newest summary, at a message of the person's) goes to files of
//! SEGMENT messages each in `chats/archive/bot-<id>/`, named `<first index>-<count>.json`, each
//! written once and never changed. `Bot::archived` says how many there are: a message's place
//! in the whole conversation is `archived + its place in messages`, which is what the phone and
//! other devices go by — the same numbers as before.
//!
//! The model never notices: it reads from the newest summary on, and the cut never passes it.
use crate::model::Message;
use std::path::{Path, PathBuf};
/// A chat longer than this is cut, when its bot is idle.
pub const ARCHIVE_AT: usize = 2_500;
/// About this many newest messages stay (the cut lands at a message of the person's before them).
pub const LIVE_KEEP: usize = 2_000;
/// Messages per archive file (what one 「載入更早的」 brings).
pub const SEGMENT: usize = 500;
/// A cut moving fewer than this waits (not a file for a handful).
const MIN_CUT: usize = 200;
/// The folder of a bot's archive, beside its chat file. (Its own folder: an older AnyBot deletes
/// the `chats/bot-*.json` it doesn't know.)
pub fn dir_in(data: &Path, bot: u64) -> PathBuf {
data.join("chats").join("archive").join(format!("bot-{bot}"))
}
fn data_dir() -> PathBuf {
crate::model::State::path().parent().map(PathBuf::from).unwrap_or_default()
}
pub fn dir(bot: u64) -> PathBuf {
dir_in(&data_dir(), bot)
}
/// One archive file: messages `start..start + count` of the conversation.
#[derive(Clone, Debug, PartialEq)]
pub struct Segment {
pub start: usize,
pub count: usize,
pub path: PathBuf,
}
/// The files in `dir`, in order.
pub fn segments_in(dir: &Path) -> Vec<Segment> {
let mut out: Vec<Segment> = std::fs::read_dir(dir)
.map(|it| {
it.flatten()
.filter_map(|e| {
let name = e.file_name().to_str()?.to_string();
let (start, count) = name.strip_suffix(".json")?.split_once('-')?;
Some(Segment { start: start.parse().ok()?, count: count.parse().ok()?, path: e.path() })
})
.collect()
})
.unwrap_or_default();
out.sort_by_key(|s| s.start);
out
}
/// Write `msgs` as the conversation's messages from `start` on, in files of SEGMENT, each synced
/// to disk before this returns. A file left from a cut that never reached the chat file (the app
/// stopped in between) at or after `start` is replaced.
pub fn write_in(dir: &Path, start: usize, msgs: &[Message]) -> std::io::Result<()> {
crate::httpd::ensure_private_dir(dir);
for s in segments_in(dir).into_iter().filter(|s| s.start + s.count > start) {
let _ = std::fs::remove_file(&s.path);
}
for (k, part) in msgs.chunks(SEGMENT).enumerate() {
let first = start + k * SEGMENT;
let bytes = serde_json::to_vec(part).map_err(std::io::Error::other)?;
crate::httpd::write_private(&dir.join(format!("{first:09}-{}.json", part.len())), &bytes)?;
}
Ok(())
}
fn read_segment(s: &Segment) -> Vec<Message> {
std::fs::read(&s.path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
}
/// Messages `from..to` of the conversation, as far as the archive in `dir` has them.
pub fn read_in(dir: &Path, from: usize, to: usize) -> Vec<Message> {
let mut out = vec![];
for s in segments_in(dir).into_iter().filter(|s| s.start < to && s.start + s.count > from) {
let msgs = read_segment(&s);
let a = from.saturating_sub(s.start).min(msgs.len());
let b = (to - s.start).min(msgs.len());
out.extend(msgs.into_iter().take(b).skip(a));
}
out
}
/// Every archived message of a bot's open conversation (the first `archived`).
pub fn all(bot: u64, archived: usize) -> Vec<Message> {
if archived == 0 {
return vec![];
}
read_in(&dir(bot), 0, archived)
}
/// The whole open conversation: the archived head and what is in memory.
pub fn whole(b: &crate::model::Bot) -> Vec<Message> {
let mut out = all(b.id, b.archived);
out.extend(b.messages.iter().cloned());
out
}
/// A copy of the bot with its whole conversation in `messages` and nothing archived: for what
/// takes a bot elsewhere (a backup, a move to the brain), where its archive files aren't.
pub fn inlined(b: &crate::model::Bot) -> crate::model::Bot {
if b.archived == 0 {
return b.clone();
}
crate::model::Bot { messages: whole(b).into(), archived: 0, head_title: String::new(), archive_mark: 0, ..b.clone() }
}
/// The archive's files go with the conversation they belonged to (it was put aside, cleared,
/// rewound into 過去的對話 whole): the folder is renamed aside now. It is deleted at a start of
/// the app only once the chat file says the conversation has nothing archived (the save that
/// carried the conversation elsewhere is then on disk); a chat file that still counts on it
/// gets it back (see sweep).
pub fn retire(bot: u64) {
forget_said(bot);
let d = dir(bot);
if d.exists() {
let to = d.with_file_name(format!("bot-{bot}.retired-{}", crate::model::now_ms()));
let _ = std::fs::rename(&d, to);
}
}
/// An archive that couldn't all be read back is kept aside for good (never deleted by AnyBot):
/// `bot-<id>.kept-<ms>`. Returns its folder.
pub fn keep_aside(bot: u64) -> PathBuf {
forget_said(bot);
let d = dir(bot);
let to = d.with_file_name(format!("bot-{bot}.kept-{}", crate::model::now_ms()));
let _ = std::fs::rename(&d, &to);
to
}
/// Whether `dir`'s files hold exactly messages 0..n, with no gap.
fn covers(dir: &Path, n: usize) -> bool {
let mut next = 0;
for s in segments_in(dir) {
if s.start != next || next >= n {
return next == n && s.start >= n;
}
next = s.start + s.count;
}
next == n
}
/// The time of message n - 1 in `dir`'s files (what a chat file keeps as its archive_mark).
fn mark_of(dir: &Path, n: usize) -> Option<i64> {
(n > 0).then(|| read_in(dir, n - 1, n).first().map(|m| m.at)).flatten()
}
/// Whether `dir` is the archive the chat file means: messages 0..n, the last one at `mark`.
fn is_the_one(dir: &Path, n: usize, mark: i64) -> bool {
covers(dir, n) && mark_of(dir, n) == Some(mark)
}
/// An archive folder that runs whole from message 0 (no gap): how many, the last one's time
/// and the conversation's first line — for a chat file written without the archive's count.
pub fn whole_from_start(dir: &Path) -> Option<(usize, i64, String)> {
let segs = segments_in(dir);
let mut next = 0;
for s in &segs {
if s.start != next {
break;
}
next = s.start + s.count;
}
let mark = mark_of(dir, next)?;
Some((next, mark, crate::model::auto_title(&read_in(dir, 0, next.min(SEGMENT)))))
}
/// Whether a chat whose first message is at `first` goes on from an archive whose last one is
/// at `mark` (a cut lands just before a message of the person's: soon after, not days later —
/// a chat an older AnyBot started over since is another conversation).
pub fn goes_on_from(mark: i64, first: Option<i64>) -> bool {
first.is_some_and(|at| at > mark && at - mark <= 86_400_000)
}
/// At the app's own start (never from another process reading the settings while it runs).
/// Nothing is deleted on a count alone, and nothing of a bot the settings don't name (settings
/// that couldn't be read name none: their archives once went with them — a deleted bot's go
/// when it is deleted, see State::write_at):
/// - a bot whose chat file says what it archived (`on_disk`: how many, the last one's time):
/// when its own folder is missing, the retired one that is exactly that comes back (newest
/// first, one at most); once its archive is the one the file means (or it has none), the
/// other retired folders go; files past the count go only when their messages are in the
/// chat again (a cut the chat file never saw);
/// - any other bot (a chat file unread, or written without the archive): nothing is touched.
pub fn sweep(data: &Path, bots: &[crate::model::Bot], on_disk: &std::collections::HashMap<u64, (usize, i64)>) {
let root = data.join("chats").join("archive");
let entries: Vec<(String, PathBuf)> = std::fs::read_dir(&root).into_iter().flatten().flatten().map(|e| (e.file_name().to_string_lossy().to_string(), e.path())).collect();
let id_of = |name: &str| -> Option<(u64, Option<u64>)> {
let rest = name.strip_prefix("bot-")?;
match rest.split_once(".retired-") {
Some((id, ms)) => Some((id.parse().ok()?, Some(ms.parse().ok()?))),
None => rest.parse().ok().map(|id| (id, None)),
}
};
for b in bots {
let Some(&(n, mark)) = on_disk.get(&b.id) else { continue };
let live = dir_in(data, b.id);
let mut retired: Vec<(u64, PathBuf)> = entries.iter().filter_map(|(name, path)| match id_of(name) {
Some((id, Some(ms))) if id == b.id => Some((ms, path.clone())),
_ => None,
}).collect();
retired.sort_by_key(|r| std::cmp::Reverse(r.0));
if n > 0 && !live.exists() {
if let Some(i) = retired.iter().position(|(_, r)| is_the_one(r, n, mark)) {
let (_, r) = retired.remove(i);
log::warn!("AnyBot:Bot {} 的對話封存從 {} 找回(上次換對話後沒存好就停了)", b.id, r.display());
let _ = std::fs::rename(&r, &live);
}
}
let settled = if n == 0 { true } else { is_the_one(&live, n, mark) };
if !settled {
log::warn!("AnyBot:Bot {} 的對話封存跟聊天檔對不上({n} 則),先不整理", b.id);
continue;
}
for (_, r) in retired {
let _ = std::fs::remove_dir_all(r);
}
for s in segments_in(&live).into_iter().filter(|s| s.start + s.count > n) {
let first = read_in(&live, s.start.max(n), s.start.max(n) + 1).first().map(|m| m.at);
if first.is_some_and(|at| at != 0 && b.messages.iter().any(|m| m.at == at)) {
let _ = std::fs::remove_file(&s.path);
}
}
}
}
/// Before a cut writes messages `from..` to `dir`: files already there from `from` on whose
/// messages are not in the chat (`msgs`) are no leftover of an unsaved cut but the only copy of
/// something (an older AnyBot started the chat over and left them): they go to a folder kept
/// aside for good, not under the new files.
pub fn keep_strays(dir: &Path, from: usize, msgs: &[Message]) {
let strays: Vec<Segment> = segments_in(dir)
.into_iter()
.filter(|s| s.start + s.count > from)
.filter(|s| {
let first = read_in(dir, s.start.max(from), s.start.max(from) + 1).first().map(|m| m.at);
!first.is_some_and(|at| at != 0 && msgs.iter().any(|m| m.at == at))
})
.collect();
if strays.is_empty() {
return;
}
let kept = dir.with_file_name(format!("{}.kept-{}", dir.file_name().unwrap_or_default().to_string_lossy(), crate::model::now_ms()));
crate::httpd::ensure_private_dir(&kept);
for s in &strays {
if let Some(name) = s.path.file_name() {
let _ = std::fs::rename(&s.path, kept.join(name));
}
}
log::warn!("AnyBot:封存資料夾裡有 {} 個檔不屬於現在的對話,移到 {}(不刪)", strays.len(), kept.display());
}
/// A deleted bot's archive: its folder and any retired ones.
pub fn remove_all(data: &Path, bot: u64) {
let _ = std::fs::remove_dir_all(dir_in(data, bot));
let prefix = format!("bot-{bot}.retired-");
for e in std::fs::read_dir(data.join("chats").join("archive")).into_iter().flatten().flatten() {
if e.file_name().to_string_lossy().starts_with(&prefix) {
let _ = std::fs::remove_dir_all(e.path());
}
}
}
/// Whether any archive is kept aside (it couldn't all be read): its files' attachments can't
/// be known, so none may be swept as unused.
pub fn any_kept(data: &Path) -> bool {
std::fs::read_dir(data.join("chats").join("archive")).into_iter().flatten().flatten().any(|e| e.file_name().to_string_lossy().contains(".kept-"))
}
/// Where the head of `msgs` can be cut: at a message of the person's, no later than the newest
/// summary (the model reads from there) and leaving about LIVE_KEEP. None: not long enough, or
/// no summary yet (the model still reads it all).
pub fn cut_point(msgs: &[Message]) -> Option<usize> {
if msgs.len() < ARCHIVE_AT {
return None;
}
let view = crate::model::model_view_start(msgs);
let limit = (msgs.len() - LIVE_KEEP).min(view);
let cut = (1..=limit).rev().find(|&i| msgs[i].role == crate::model::Role::User)?;
(cut >= MIN_CUT).then_some(cut)
}
/// Every file path an archived message of a bot holds (its attachments), for the nightly sweep
/// of files no message uses any more. None when the archive can't all be read: then nothing may
/// be swept (its files would look unused).
pub fn attachment_paths(bot: u64, archived: usize) -> Option<Vec<String>> {
let msgs = all(bot, archived);
(msgs.len() == archived).then(|| msgs.iter().flat_map(|m| m.attachments.iter().map(|a| a.path.clone())).collect())
}
/// One archived message as search sees it: what the person or the bot said (not tool results,
/// not summaries) and the names of its files, with its place in the conversation.
#[derive(Clone, Debug)]
pub struct Said {
pub index: usize,
pub at: i64,
pub mine: bool,
/// AnyBot's own line, not the person's or the bot's words (the heat map leaves it out).
pub note: bool,
pub text: String,
pub files: Vec<crate::attach::Attachment>,
}
type SaidCache = std::collections::HashMap<u64, (usize, std::sync::Arc<Vec<Said>>)>;
fn said_cache() -> &'static std::sync::Mutex<SaidCache> {
static M: std::sync::OnceLock<std::sync::Mutex<SaidCache>> = std::sync::OnceLock::new();
M.get_or_init(Default::default)
}
/// Each bot's archive generation: up when its archive is retired, so a read that started before
/// doesn't put the old conversation's words back.
fn said_epoch() -> &'static std::sync::Mutex<std::collections::HashMap<u64, u64>> {
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<u64, u64>>> = std::sync::OnceLock::new();
M.get_or_init(Default::default)
}
fn forget_said(bot: u64) {
said_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(&bot);
*said_epoch().lock().unwrap_or_else(|e| e.into_inner()).entry(bot).or_default() += 1;
}
fn said_reading() -> &'static std::sync::Mutex<std::collections::HashSet<u64>> {
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<u64>>> = std::sync::OnceLock::new();
M.get_or_init(Default::default)
}
/// Goes up each time an archive's words are ready to search (a search waiting for them runs again).
static SAID_READY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
pub fn said_generation() -> u64 {
SAID_READY.load(std::sync::atomic::Ordering::SeqCst)
}
/// A bot's archived words, ready to search — or None while a thread of their own reads them
/// (the first search after a start or a cut; megabytes of files, never on the window's thread).
/// A cut that added to the archive reads only what it added.
pub fn said(bot: u64, archived: usize) -> Option<std::sync::Arc<Vec<Said>>> {
if archived == 0 {
return Some(Default::default());
}
let have = said_cache().lock().unwrap_or_else(|e| e.into_inner()).get(&bot).cloned();
if let Some((n, list)) = &have {
if *n == archived {
return Some(list.clone());
}
}
if !said_reading().lock().unwrap_or_else(|e| e.into_inner()).insert(bot) {
return None;
}
let d = dir(bot);
let epoch = said_epoch().lock().unwrap_or_else(|e| e.into_inner()).get(&bot).copied().unwrap_or(0);
std::thread::spawn(move || {
let (from, mut list) = match have {
Some((n, l)) if n < archived => (n, (*l).clone()),
_ => (0, vec![]),
};
for (k, m) in read_in(&d, from, archived).into_iter().enumerate() {
if matches!(m.role, crate::model::Role::User | crate::model::Role::Assistant) && !m.summary {
if !m.text.trim().is_empty() || !m.attachments.is_empty() {
list.push(Said { index: from + k, at: m.at, mine: m.role == crate::model::Role::User, note: m.note, text: m.text, files: m.attachments });
}
}
}
if said_epoch().lock().unwrap_or_else(|e| e.into_inner()).get(&bot).copied().unwrap_or(0) == epoch {
said_cache().lock().unwrap_or_else(|e| e.into_inner()).insert(bot, (archived, std::sync::Arc::new(list)));
}
said_reading().lock().unwrap_or_else(|e| e.into_inner()).remove(&bot);
SAID_READY.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
});
None
}
/// Tests that write archives under the shared test folder take turns (a sweep in one would
/// count another's bot as gone).
#[cfg(test)]
pub fn test_turn() -> std::sync::MutexGuard<'static, ()> {
static M: std::sync::Mutex<()> = std::sync::Mutex::new(());
M.lock().unwrap_or_else(|e| e.into_inner())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{Message, Role};
fn chat(n: usize, summary_at: usize) -> Vec<Message> {
(0..n)
.map(|i| {
let mut m = if i % 10 == 0 { Message::user(&format!("第 {i} 句")) } else { Message::assistant(&format!("回 {i}"), "x") };
m.at = i as i64 + 1;
m.summary = i == summary_at;
if m.summary {
m.role = Role::Assistant;
}
m
})
.collect()
}
#[test]
fn the_cut_lands_at_the_persons_message_and_never_past_the_summary() {
assert_eq!(cut_point(&chat(2_400, 2_300)), None, "short enough");
assert_eq!(cut_point(&chat(3_000, 0)), None, "no summary: the model reads it all");
// Summary late: about LIVE_KEEP stay, the cut at a message of the person's.
let c = chat(3_000, 2_900);
let cut = cut_point(&c).unwrap();
assert_eq!(c[cut].role, Role::User);
assert!(cut <= 1_000 && cut > 980, "{cut}");
// Summary early: the cut stops there.
let c = chat(3_000, 455);
let cut = cut_point(&c).unwrap();
assert!(cut <= 455 && c[cut].role == Role::User, "{cut}");
assert_eq!(cut_point(&chat(3_000, 150)), None, "too little to move");
}
#[test]
fn files_hold_their_part_and_read_back_by_place() {
let d = std::env::temp_dir().join(format!("anybot-archive-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
let c = chat(1_200, 0);
write_in(&d, 0, &c[..1_100]).unwrap();
let segs = segments_in(&d);
assert_eq!(segs.iter().map(|s| (s.start, s.count)).collect::<Vec<_>>(), vec![(0, 500), (500, 500), (1_000, 100)]);
let got = read_in(&d, 480, 520);
assert_eq!(got.iter().map(|m| m.at).collect::<Vec<_>>(), (481..=520).collect::<Vec<i64>>());
assert_eq!(read_in(&d, 0, 1_100).len(), 1_100);
// A cut the chat file never saw, then the same place again with another length: replaced.
write_in(&d, 1_000, &c[1_000..1_150]).unwrap();
assert_eq!(segments_in(&d).last().map(|s| (s.start, s.count)), Some((1_000, 150)));
// At start, past what the bot says it has: gone.
let data = std::env::temp_dir().join(format!("anybot-archive-sweep-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&data);
let mine = dir_in(&data, 7);
write_in(&mine, 0, &c[..1_100]).unwrap();
write_in(&dir_in(&data, 8), 0, &c[..10]).unwrap();
let mut seven = crate::model::State::samples().bots.remove(0);
seven.id = 7;
seven.messages = c[1_000..].to_vec().into();
sweep(&data, &[seven], &[(7, (1_000, c[999].at))].into_iter().collect());
assert_eq!(segments_in(&mine).len(), 2, "the part past 1 000 is in the chat again: gone");
assert!(dir_in(&data, 8).exists(), "a bot the settings don't name is left alone (settings that couldn't be read name none)");
remove_all(&data, 8);
assert!(!dir_in(&data, 8).exists(), "deleting the bot takes it");
let _ = std::fs::remove_dir_all(&d);
let _ = std::fs::remove_dir_all(&data);
}
}