From 879355d855794cecf7f1b6083a3102f5763a9805 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 21 Sep 2026 16:01:58 +0800 Subject: [PATCH] fix(store): request ids resume from the store, so a restart stops eating history MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every restart destroyed the oldest records, silently. `EventBus::new` starts the request counter at 1 and nothing ever seeded it from disk, while the recorder writes with `INSERT OR REPLACE` — it has to, because a request is written twice, once when it starts and once when it ends. Put together, the first request after a restart overwrites historical request 1, the second overwrites 2, and so on. The desktop app restarts on every update, so this ran regularly. Measured against v0.14.0 with a throwaway instance: eight requests, restart, eight more, restart, five more. Twenty-one requests, eight rows left. With the counter seeded: twenty-one rows. `Db::last_request_id` reads `MAX(id)`, and `build_store` hands it to the bus before `serve` starts, so the first request of the run already has a number above everything on disk. `resume_after` is a `fetch_max`: winding the counter backwards would be manufacturing collisions, which is the bug itself. Reading it can fail, and then the run carries on as before — losing a few old records is worse than recording nothing at all this session. Co-Authored-By: Claude Opus 5 --- bin/twcore/src/main.rs | 18 +++++++++++++ crates/tw-observe/src/bus.rs | 34 ++++++++++++++++++++++++ crates/tw-store/src/db.rs | 50 ++++++++++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+) diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index b2fa2d77..315aa054 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -881,6 +881,24 @@ fn build_store( return None; } }; + /* + **接着上次的号往下发。**这里是唯一同时看得见总线和库的地方, + 而且它跑在 `serve` 之前(见 `cmd_serve`)—— 第一个请求拿到号 + 的时候,计数器已经归位了。 + + 读不到就照常跑:那顶多是这一次重启又压掉几条历史,比起因为 + 一次查询失败而不记录任何东西要好得多。 + */ + match db.last_request_id() { + Ok(0) => {} + Ok(last) => { + tracing::debug!(last, "request ids resume from where they left off"); + bus.resume_after(last); + } + Err(e) => tracing::warn!( + "could not read the last request id, so this run may overwrite the oldest records: {e}" + ), + } let blobs = tw_store::Blobs::new(dir.join("blobs")); // 两边的 body 结构在这里对接。**一次移动,不复制** —— `Bytes` 的 // 克隆是引用计数。 diff --git a/crates/tw-observe/src/bus.rs b/crates/tw-observe/src/bus.rs index 7c1f1c16..d6b80810 100644 --- a/crates/tw-observe/src/bus.rs +++ b/crates/tw-observe/src/bus.rs @@ -50,6 +50,19 @@ impl EventBus { self.next_id.fetch_add(1, Ordering::Relaxed) } + /// 从这个号之后接着发。 + /// + /// **计数器出厂从 1 开始,而库是跨重启的。**存储层落库用的是 + /// `INSERT OR REPLACE`(同一个请求要写两次),所以重启后重新发出 + /// 的号会一条一条顶掉历史上的同号记录。启动时把已经用掉的最大号 + /// 交给它,那条路就断了。 + /// + /// **只进不退**:同一个进程里被调用两次,或者调用时已经发过号了, + /// 都不会把计数器往回拨 —— 往回拨就是在制造重号。 + pub fn resume_after(&self, id: u64) { + self.next_id.fetch_max(id + 1, Ordering::Relaxed); + } + /// 发一条。**没有订阅者不是错误** —— 没开 UI 的时候数据面照常跑。 pub fn emit(&self, ev: tw_api::Event) { let _ = self.tx.send(ev); @@ -68,6 +81,27 @@ impl EventBus { mod tests { use super::*; + #[test] + fn ids_resume_after_the_number_the_store_already_has() { + let b = EventBus::new(); + b.resume_after(1258); + assert_eq!(b.next_id(), 1259); + assert_eq!(b.next_id(), 1260); + } + + #[test] + fn resuming_never_hands_out_a_number_twice() { + // **只进不退。**往回拨就是在制造重号,而重号在存储层是覆盖。 + let b = EventBus::new(); + assert_eq!(b.next_id(), 1); + assert_eq!(b.next_id(), 2); + b.resume_after(0); + assert_eq!(b.next_id(), 3, "被拨回去了"); + b.resume_after(100); + b.resume_after(50); + assert_eq!(b.next_id(), 101); + } + #[tokio::test] async fn emitting_with_no_subscribers_is_not_an_error() { // 没开 UI 的时候数据面照常跑 —— 这是最常见的状态。 diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index 14feacaa..07d972e5 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -410,6 +410,23 @@ impl Db { Ok(()) } + /// 已经用掉的最大请求号。库是空的时候是 0。 + /// + /// **重启之后请求号要接着往下发。**号是进程里的一个计数器,每次 + /// 起来都从 1 开始;而写库走的是 `INSERT OR REPLACE`(一个请求要 + /// 写两次:开始一次、结束一次,见 `recorder`)。两件事凑在一起, + /// 重启后的第一条请求就顶掉了历史上的第 1 条,第二条顶掉第 2 条 + /// —— 最老的记录一条一条地无声消失,而应用每更新一次就重启一次。 + pub fn last_request_id(&self) -> Result { + // 空表时 MAX(id) 是 NULL,用 COALESCE 收掉 + let id: i64 = + self.conn + .query_row("SELECT COALESCE(MAX(id), 0) FROM requests", [], |r| { + r.get(0) + })?; + Ok(id.max(0) as u64) + } + /// 最近 N 条,新的在前。 pub fn recent(&self, limit: usize) -> Result, DbError> { let mut st = self @@ -1407,6 +1424,39 @@ mod tests { ); } + #[test] + fn the_last_request_id_is_where_the_next_run_has_to_start() { + let db = Db::in_memory().unwrap(); + assert_eq!(db.last_request_id().unwrap(), 0, "空库不该报一个假的号"); + db.insert(&row(1, 1)).unwrap(); + db.insert(&row(7, 2)).unwrap(); + db.insert(&row(3, 3)).unwrap(); + // **最大的那个,不是最后写进去的那个。**乱序写入照样成立 + assert_eq!(db.last_request_id().unwrap(), 7); + } + + #[test] + fn reusing_a_request_id_overwrites_the_older_record() { + /* + 这一条钉住的是**问题本身**,不是修法:写库走的是 + `INSERT OR REPLACE`(一个请求要写两次,见 `recorder`),所以 + 重号就是覆盖。计数器每次起来都从 1 开始,两件事凑在一起, + 重启后的第一条请求会顶掉历史上的第 1 条。 + + `last_request_id` 存在的全部理由就是让这件事不发生。 + */ + let db = Db::in_memory().unwrap(); + let old = row(1, 1_000); + db.insert(&old).unwrap(); + let mut newer = row(1, 9_000); + newer.model = "qwen3:8b".into(); + db.insert(&newer).unwrap(); + assert_eq!(db.recent(10).unwrap().len(), 1, "老的那条没了"); + assert_eq!(db.get(1).unwrap().unwrap().model, "qwen3:8b"); + // 从库里问一次号就够躲开:下一条该用 2 + assert_eq!(db.last_request_id().unwrap(), 1); + } + #[test] fn a_row_survives_a_round_trip_with_every_field_intact() { // 漏掉一个字段的表现是「详情页上少一个数」,而那种缺失在肉眼