Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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` 的
// 克隆是引用计数。
Expand Down
34 changes: 34 additions & 0 deletions crates/tw-observe/src/bus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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 的时候数据面照常跑 —— 这是最常见的状态。
Expand Down
50 changes: 50 additions & 0 deletions crates/tw-store/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,23 @@ impl Db {
Ok(())
}

/// 已经用掉的最大请求号。库是空的时候是 0。
///
/// **重启之后请求号要接着往下发。**号是进程里的一个计数器,每次
/// 起来都从 1 开始;而写库走的是 `INSERT OR REPLACE`(一个请求要
/// 写两次:开始一次、结束一次,见 `recorder`)。两件事凑在一起,
/// 重启后的第一条请求就顶掉了历史上的第 1 条,第二条顶掉第 2 条
/// —— 最老的记录一条一条地无声消失,而应用每更新一次就重启一次。
pub fn last_request_id(&self) -> Result<u64, DbError> {
// 空表时 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<Vec<RequestRow>, DbError> {
let mut st = self
Expand Down Expand Up @@ -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() {
// 漏掉一个字段的表现是「详情页上少一个数」,而那种缺失在肉眼
Expand Down
Loading