From e7f59823312971427ccb24aba9a749a5e4f0aea2 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 21 Sep 2026 16:50:10 +0800 Subject: [PATCH 1/2] feat(api): history and sessions take a time window MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two list endpoints only took a limit, so the desktop app's traffic page could only ever say "the last 200" while its overview offers live / 24h / 7d / 30d. "What happened last Tuesday" was not a question the traffic page could be asked. The window is optional, and its absence does not mean today. The aggregating endpoints default to midnight because "how much did I spend" needs a period and today is the right one; a list does not — "the most recent N" is already a complete answer, and defaulting to today would empty the table at midnight while the user did nothing. Sessions filter by session, not by turn. Filtering turns and then grouping would report fewer turns and less cost for a task that straddles the boundary, and "what did that refactor cost" asks about the whole task, not the slice of it inside some window. So the aggregate is computed over everything and a session is kept when any of its turns falls inside. Co-Authored-By: Claude Opus 5 --- crates/tw-control/src/diagnostics.rs | 2 +- crates/tw-control/src/lib.rs | 46 ++++++++++-- crates/tw-control/tests/sessions.rs | 32 ++++++++ crates/tw-store/src/db.rs | 105 ++++++++++++++++++++++----- crates/tw-store/src/recorder.rs | 2 +- 5 files changed, 158 insertions(+), 29 deletions(-) diff --git a/crates/tw-control/src/diagnostics.rs b/crates/tw-control/src/diagnostics.rs index 71afe460..54370519 100644 --- a/crates/tw-control/src/diagnostics.rs +++ b/crates/tw-control/src/diagnostics.rs @@ -188,7 +188,7 @@ pub async fn bundle(State(s): State) -> String { format!("{} bytes", g.blobs().total_bytes()), ); - let recent = g.db().recent(200).unwrap_or_default(); + let recent = g.db().recent(None, 200).unwrap_or_default(); let failed: Vec<_> = recent .iter() .filter(|r| r.error.is_some()) diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 875e0807..9bf445e7 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -648,14 +648,11 @@ async fn summary( /// 最近的请求。**实时列表走内存 ring buffer,这个是给「翻历史」的**。 async fn history( State(s): State, - axum::extract::Query(q): axum::extract::Query, + axum::extract::Query(q): axum::extract::Query, ) -> Result>, Fail> { let store = need_store(&s)?; let g = store.lock().await; - let rows = g - .db() - .recent(q.limit.unwrap_or(200).min(2000)) - .map_err(internal)?; + let rows = g.db().recent(q.within(), q.limit()).map_err(internal)?; Ok(Json(rows.into_iter().map(history_row).collect())) } @@ -1094,6 +1091,36 @@ struct Limit { limit: Option, } +/// 一张列表要的两样:看哪一段,最多几条。 +/// +/// **时间窗是可选的,而且缺省不是「今天」。**聚合类的端点缺省到今天是 +/// 对的(见 [`Window`]);列表类的不是 —— 「最近 N 条」本身就是一个 +/// 完整的回答,而缺省成今天的话,过了零点这张表会空掉,那时用户什么 +/// 都没做。 +/// +/// 两端各自可缺:只给 `from_ms` 就是「从那时起到现在」。 +/// +/// 字段摊平写、不用 `#[serde(flatten)]`,理由见 [`Window`] 上面那段。 +#[derive(Debug, serde::Deserialize)] +struct ListQuery { + from_ms: Option, + to_ms: Option, + limit: Option, +} + +impl ListQuery { + fn within(&self) -> Option<(i64, i64)> { + match (self.from_ms, self.to_ms) { + (None, None) => None, + (f, t) => Some((f.unwrap_or(i64::MIN), t.unwrap_or_else(now_ms))), + } + } + + fn limit(&self) -> usize { + self.limit.unwrap_or(200).min(2000) + } +} + /// 当前配置的原文。**文本模式直接显示它。** async fn get_config(State(s): State) -> Result, Fail> { let c = s.cfg.current().map_err(internal)?; @@ -1335,14 +1362,17 @@ fn turn_view(t: &tw_store::db::TurnRow) -> tw_api::TurnView { /// /// **观测层没起来时返回空列表,不是错误**:那时网关照常转发, /// 界面上少一块统计,而不是弹一个错。 -async fn sessions(State(s): State) -> Json> { +async fn sessions( + State(s): State, + axum::extract::Query(q): axum::extract::Query, +) -> Json> { let Some(store) = &s.store else { return Json(Vec::new()); }; let g = store.lock().await; Json( g.db() - .sessions(200) + .sessions(q.within(), q.limit()) .unwrap_or_default() .iter() .map(session_view) @@ -1363,7 +1393,7 @@ async fn session_detail( let g = store.lock().await; let session = g .db() - .sessions(500) + .sessions(None, 500) .unwrap_or_default() .iter() .find(|x| x.id == id) diff --git a/crates/tw-control/tests/sessions.rs b/crates/tw-control/tests/sessions.rs index 5f59d5f1..42c796bd 100644 --- a/crates/tw-control/tests/sessions.rs +++ b/crates/tw-control/tests/sessions.rs @@ -158,3 +158,35 @@ async fn a_request_in_the_history_says_which_session_it_belongs_to() { let list = get(&app, "/sessions").await; assert_eq!(list[0]["id"], "s1"); } + +/// 时间窗走到端点上是不是还成立。 +/// +/// **query string 这一层单独验。**`Window` 上面那段注释记着一次教训: +/// 不带参数时一切正常,带上时间窗才 400 —— 而单元测试看不见它,它只在 +/// 真的经过一次 query string 解析时才发生。 +#[tokio::test] +async fn the_endpoints_take_a_time_window_off_the_query_string() { + // turn(id) 的 at_ms 是 1000 + id + let (_d, app) = app(&[turn(1, "per-token"), turn(2, "per-token")]); + + let all = get(&app, "/history?limit=10").await; + assert_eq!(all.as_array().unwrap().len(), 2); + + let narrowed = get(&app, "/history?from_ms=1002&to_ms=1002&limit=10").await; + let narrowed = narrowed.as_array().unwrap(); + assert_eq!(narrowed.len(), 1, "{narrowed:?}"); + assert_eq!(narrowed[0]["id"], 2); + + // 只给一端:从那时起到现在 + let from_only = get(&app, "/history?from_ms=1002").await; + assert_eq!(from_only.as_array().unwrap().len(), 1); + + // 会话那一端:窗口只盖住第二轮,整条会话照样两轮 + let s = get(&app, "/sessions?from_ms=1002&to_ms=1002").await; + assert_eq!(s.as_array().unwrap().len(), 1); + assert_eq!(s[0]["turns"], 2, "跨边界的会话被截断了:{s}"); + + // 完全错开的窗口筛得掉 + let none = get(&app, "/sessions?from_ms=9000&to_ms=9999").await; + assert!(none.as_array().unwrap().is_empty(), "{none}"); +} diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index 07d972e5..b5b649c1 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -427,12 +427,24 @@ impl Db { Ok(id.max(0) as u64) } - /// 最近 N 条,新的在前。 - pub fn recent(&self, limit: usize) -> Result, DbError> { - let mut st = self - .conn - .prepare("SELECT * FROM requests ORDER BY at_ms DESC, id DESC LIMIT ?1")?; - let rows = st.query_map([limit as i64], row_from)?; + /// 最近 N 条,新的在前。`within` 给了就只看那段时间。 + /// + /// **不给时间窗不等于「今天」。**别的端点是在做聚合,「这段时间花了 + /// 多少」必须有个默认的段,而那个段该是今天;这个端点给的是一张 + /// 列表,「最近 N 条」本身就是一个完整的回答。默认成今天的话, + /// 过了零点这张表会空掉,而那时用户什么都没做。 + pub fn recent( + &self, + within: Option<(i64, i64)>, + limit: usize, + ) -> Result, DbError> { + let (from, to) = within.unwrap_or((i64::MIN, i64::MAX)); + let mut st = self.conn.prepare( + "SELECT * FROM requests + WHERE at_ms >= ?1 AND at_ms <= ?2 + ORDER BY at_ms DESC, id DESC LIMIT ?3", + )?; + let rows = st.query_map([from, to, limit as i64], row_from)?; Ok(rows.collect::, _>>()?) } } @@ -498,7 +510,17 @@ impl Db { /// /// **本地应答的那些不算轮次**:它们没经过上游,把它们算进 /// 「这次任务跑了多少轮」会让每个数字都偏大一点,而偏得毫无规律。 - pub fn sessions(&self, limit: usize) -> Result, DbError> { + /// `within` 给了就只看在那段时间里活动过的会话。 + /// + /// **筛的是会话,不是轮次。**把轮次按时间筛掉再聚合的话,一次跨过 + /// 窗口边界的任务会少算几轮、少算一截钱 —— 而「那次重构花了多少」 + /// 问的是整次任务,不是它落在某个窗口里的那一段。所以先整体聚合, + /// 再按「有没有任何一轮落在窗口里」留下整条。 + pub fn sessions( + &self, + within: Option<(i64, i64)>, + limit: usize, + ) -> Result, DbError> { let mut st = self.conn.prepare(&format!( "SELECT session, client, @@ -520,10 +542,12 @@ impl Db { FROM requests WHERE session IS NOT NULL AND local = 0 GROUP BY session + HAVING MAX(at_ms) >= ?1 AND MIN(at_ms) <= ?2 ORDER BY MAX(at_ms) DESC - LIMIT ?1" + LIMIT ?3" ))?; - let rows = st.query_map([limit as i64], |r| { + let (from, to) = within.unwrap_or((i64::MIN, i64::MAX)); + let rows = st.query_map([from, to, limit as i64], |r| { Ok(SessionRow { id: r.get(0)?, client: r.get(1)?, @@ -1424,6 +1448,49 @@ mod tests { ); } + #[test] + fn a_window_narrows_the_history_and_no_window_means_the_most_recent() { + let db = Db::in_memory().unwrap(); + for (id, at) in [(1, 1_000), (2, 5_000), (3, 9_000)] { + db.insert(&row(id, at)).unwrap(); + } + let ids = |w| { + let mut v: Vec = db.recent(w, 10).unwrap().iter().map(|r| r.id).collect(); + v.sort_unstable(); + v + }; + // **不给窗口不是「今天」。**列表的默认答案是「最近 N 条」 + assert_eq!(ids(None), vec![1, 2, 3]); + assert_eq!(ids(Some((4_000, 6_000))), vec![2]); + // 两端都是闭区间 —— 边界上那一条属于窗口里 + assert_eq!(ids(Some((5_000, 9_000))), vec![2, 3]); + assert!(ids(Some((20_000, 30_000))).is_empty()); + } + + #[test] + fn a_session_that_straddles_the_window_is_kept_whole() { + /* + **筛的是会话,不是轮次。**把轮次先按时间筛掉再聚合的话,一次 + 跨过边界的任务会少算几轮、少算一截钱 —— 而「那次重构花了多少」 + 问的是整次任务,不是它落在某个窗口里的那一段。 + */ + let db = Db::in_memory().unwrap(); + for (id, at) in [(1, 1_000), (2, 5_000), (3, 9_000)] { + let mut r = row(id, at); + r.session = Some("s".into()); + db.insert(&r).unwrap(); + } + // 窗口只盖住中间那一轮,整条会话照样在,而且三轮都算上了 + let got = db.sessions(Some((4_000, 6_000)), 10).unwrap(); + assert_eq!(got.len(), 1); + assert_eq!(got[0].turns, 3, "跨边界的会话被截断了"); + assert_eq!(got[0].started_ms, 1_000); + assert_eq!(got[0].ended_ms, 9_000); + + // 完全错开的窗口才筛得掉它 + assert!(db.sessions(Some((20_000, 30_000)), 10).unwrap().is_empty()); + } + #[test] fn the_last_request_id_is_where_the_next_run_has_to_start() { let db = Db::in_memory().unwrap(); @@ -1451,7 +1518,7 @@ mod tests { 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.recent(None, 10).unwrap().len(), 1, "老的那条没了"); assert_eq!(db.get(1).unwrap().unwrap().model, "qwen3:8b"); // 从库里问一次号就够躲开:下一条该用 2 assert_eq!(db.last_request_id().unwrap(), 1); @@ -1491,7 +1558,7 @@ mod tests { for i in 1..=5 { db.insert(&row(i, i * 1000)).unwrap(); } - let got: Vec = db.recent(3).unwrap().iter().map(|r| r.id).collect(); + let got: Vec = db.recent(None, 3).unwrap().iter().map(|r| r.id).collect(); assert_eq!(got, vec![5, 4, 3]); } @@ -1655,7 +1722,7 @@ mod tests { r.input_tokens = input; db.insert(&r).unwrap(); } - let s = &db.sessions(10).unwrap()[0]; + let s = &db.sessions(None, 10).unwrap()[0]; assert_eq!(s.turns, 3); assert_eq!(s.cost_micros, 3000); assert_eq!(s.unpriced_turns, 1, "没价格的那轮得单独说"); @@ -1678,7 +1745,7 @@ mod tests { b.session = Some("s1".into()); b.local = true; db.insert(&b).unwrap(); - assert_eq!(db.sessions(10).unwrap()[0].turns, 1); + assert_eq!(db.sessions(None, 10).unwrap()[0].turns, 1); assert_eq!(db.turns("s1").unwrap().len(), 1); } @@ -1702,7 +1769,7 @@ mod tests { let db = Db::open(&d.path().join("data.db")).unwrap(); db.insert(&row(1, 100)).unwrap(); db.insert(&row(2, 200)).unwrap(); - assert!(db.sessions(10).unwrap().is_empty()); + assert!(db.sessions(None, 10).unwrap().is_empty()); } #[test] @@ -1848,7 +1915,7 @@ mod tests { } let db = Db::open(&p).unwrap(); assert_eq!(db.count().unwrap(), 2, "迁移把老记录弄丢了"); - let got = db.recent(10).unwrap(); + let got = db.recent(None, 10).unwrap(); // 老记录没有旁证,那就是 None —— 不是空字符串 assert!(got.iter().all(|r| r.client_hint.is_none())); // 升级之前取消的请求根本不落库,所以老记录一条都不该是「已取消」 @@ -1861,7 +1928,7 @@ mod tests { fresh.client_hint = Some("codex".into()); fresh.session = Some("abc-100".into()); db.insert(&fresh).unwrap(); - let back = &db.recent(1).unwrap()[0]; + let back = &db.recent(None, 1).unwrap()[0]; assert_eq!(back.client_hint.as_deref(), Some("codex")); assert_eq!(back.session.as_deref(), Some("abc-100")); } @@ -2057,7 +2124,7 @@ mod cost_state_tests { assert_eq!((b[0].unpriced_requests, b[0].no_usage_requests), (0, 0)); let g = db.cost_by(tw_api::CostDim::Model, 0, 1000).unwrap(); assert_eq!((g[0].unpriced_requests, g[0].no_usage_requests), (0, 0)); - let s = &db.sessions(10).unwrap()[0]; + let s = &db.sessions(None, 10).unwrap()[0]; assert_eq!((s.unpriced_turns, s.no_usage_turns), (0, 0)); assert_eq!(s.priced_turns, 0, "订阅制那一轮没有价格可言"); } @@ -2081,7 +2148,7 @@ mod cost_state_tests { db.insert(&r).unwrap(); } - let s = &db.sessions(10).unwrap()[0]; + let s = &db.sessions(None, 10).unwrap()[0]; assert_eq!(s.subscription_turns, 2); assert_eq!( (s.priced_turns, s.unpriced_turns, s.no_usage_turns), @@ -2165,7 +2232,7 @@ mod cost_state_tests { db.insert(&r).unwrap(); } - let s = &db.sessions(10).unwrap()[0]; + let s = &db.sessions(None, 10).unwrap()[0]; assert_eq!(s.cost_micros, 1_300); assert_eq!(s.cost_micros_estimated, 300, "合计里的估算部分没有单独说"); assert_eq!(s.priced_turns, 2); diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 9c95baf7..11768f3b 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -1558,7 +1558,7 @@ mod cancellation_tests { }); r.on_event(&cancelled(1, partial())); - let sessions = r.db().sessions(10).unwrap(); + let sessions = r.db().sessions(None, 10).unwrap(); assert_eq!(sessions.len(), 1); assert_eq!(sessions[0].errors, 0, "取消被算成了会话里的失败"); let turns = r.db().turns(&sessions[0].id).unwrap(); From 910a2e675a67db034a55209f2d8e573b2d7ea96e Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 21 Sep 2026 16:51:58 +0800 Subject: [PATCH 2/2] refactor: drop Limit, ListQuery replaced its only caller Co-Authored-By: Claude Opus 5 --- crates/tw-control/src/lib.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 9bf445e7..62164a97 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -1086,11 +1086,6 @@ fn now_ms() -> i64 { .unwrap_or(0) } -#[derive(Debug, serde::Deserialize)] -struct Limit { - limit: Option, -} - /// 一张列表要的两样:看哪一段,最多几条。 /// /// **时间窗是可选的,而且缺省不是「今天」。**聚合类的端点缺省到今天是