From 513703f775835a50defaba0ddaeb65b0009a2543 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Wed, 2 Dec 2026 15:54:38 +0800 Subject: [PATCH 1/4] feat(agents): reuse daily statistics for usage overviews --- rust/contracts/rust-core-api.md | 2 +- rust/crates/agent-runtime/src/records.rs | 43 +- rust/crates/agent-runtime/src/tests.rs | 40 ++ rust/crates/agent-sessions/Cargo.toml | 8 +- .../agent-sessions/benches/daily_overview.rs | 129 ++++ rust/crates/agent-sessions/src/pricing.rs | 7 +- rust/crates/agent-sessions/src/stats.rs | 191 +++--- .../agent-sessions/src/stats/overview.rs | 590 ++++++++++++++++++ rust/crates/agent-sessions/src/store.rs | 95 ++- rust/crates/agent-sessions/src/tests/store.rs | 242 +++++++ rust/fixtures/ai/agent-usage-overview-v1.json | 22 + shared/plugins/contract/v1/README.md | 15 + shared/plugins/reference/api-catalog.md | 4 +- .../plugins/reference/protocol-changelog.md | 1 + 14 files changed, 1286 insertions(+), 103 deletions(-) create mode 100644 rust/crates/agent-sessions/benches/daily_overview.rs create mode 100644 rust/crates/agent-sessions/src/stats/overview.rs create mode 100644 rust/fixtures/ai/agent-usage-overview-v1.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 4eb1c36d..814eebfb 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -499,7 +499,7 @@ or removing a command fails until the table changes in the same commit. | `agentSessions.search` | Search recorded agent session text | | `agentSessions.read` | Read one recorded range as messages and where the next page starts | | `agentSessions.page` | Read a bounded whole-line window before or after a recorded byte cursor, growing only for a long source line | -| `agentSessions.stats` | Sum recorded agent usage with the latest rate limits; `groupBy: "hour"` returns sparse `{kind: "hour", startMs}` keys aligned to the fixed UTC offset or optional `hourAnchorMs` | +| `agentSessions.stats` | Sum recorded agent usage with the latest rate limits. Optional `overview` returns totals, breakdown and time series in one snapshot; `groupBy: "hour"` returns sparse `{kind: "hour", startMs}` keys aligned to the fixed UTC offset or optional `hourAnchorMs` | | `agentSessions.calls` | List a page of recorded agent calls, most recent first, with their cost, cache hit rate and speed | | `agentLibrary.configure` | Open the agent library in the platform's application data | | `agentLibrary.read` | Read the library and what each configurable agent's instructions, skills, MCP servers and hooks hold; optional `query`, `agent` with `presence`, and `sort` add the keys of the matching items as `matches` | diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index 0d204abc..8e2bd571 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -20,7 +20,7 @@ use crate::events::{check_rate_limits, RateLimits, RateWindow, MAX_RATE_WINDOWS} use crate::{log, now_ms, Runtime}; use lithe_agent_sessions::pricing::{call_cost, PriceTable}; use lithe_agent_sessions::stats::{ - call_speed, model_name, CallSelector, GroupBy, SpeedRanker, Summarizer, + call_speed, model_name, CallSelector, GroupBy, Overview, OverviewQuery, SpeedRanker, Summarizer, }; use lithe_agent_sessions::{ discover, ByteRange, CallEntry, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionFilter, @@ -904,6 +904,8 @@ impl Records { search: Option, #[serde(default)] detail: bool, + #[serde(default)] + overview: Option, } let request: StatsRequest = crate::decode(payload)?; let group_by = parse_group_by( @@ -938,7 +940,44 @@ impl Records { request.failed, request.search.as_deref(), )?; - let (summaries, speeds) = match allowed_agents(runtime, request.agents) { + let readable = allowed_agents(runtime, request.agents); + if let Some(calendar) = request.overview { + let split = split_by + .filter(|_| { + request.detail + && calendar.valid() + && matches!(group_by, GroupBy::Day { .. } | GroupBy::Hour { .. }) + }) + .ok_or_else(|| { + refusal(ErrorCode::InvalidRequest, "agentSessions.invalidGroup", + "An overview needs a day or hour series, a split, detail and a valid calendar.") + })?; + let result = if let Some(agents) = readable { + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner); + store.usage_overview( + &CallFilter { + agents, + session_id: request.session_id, + since_ms: request.since_ms, + until_ms: request.until_ms, + }, + &selector, + prices.as_ref(), + group_by, + split, + &calendar, + )? + } else { + Overview::default() + }; + return Ok( + json!({"summaries": result.summaries, "groups": result.groups, + "series": result.series, "rateLimits": self.rate_limit_entries(runtime)}), + ); + } + let (summaries, speeds) = match readable { None => (json!([]), json!([])), Some(agents) => { let filter = CallFilter { diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 8b744297..77496e73 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -3034,3 +3034,43 @@ fn records_page_contract_examples_match_the_runtime() { ); } } + +#[test] +fn overview_matches_the_shared_calendar_and_legacy_totals() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../fixtures/ai/agent-usage-overview-v1.json" + )) + .expect("overview fixture"); + let harness = Harness::new("overview-calendar", ALL_GRANTS); + write_session_file( + &harness, + fixture["callStartMs"].as_i64().expect("call time"), + ); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + let query = &fixture["query"]; + let total = harness.run( + "agentSessions.stats", + json!({"groupBy":"all","detail":true}), + ); + let groups = harness.run( + "agentSessions.stats", + json!({"groupBy":"model","detail":true}), + ); + for _ in 0..2 { + let result = harness.run("agentSessions.stats", query.clone()); + assert_eq!(result["summaries"], total["summaries"]); + assert_eq!(result["groups"], groups["summaries"]); + assert_eq!(result["series"][0]["key"]["date"], fixture["date"]); + assert_eq!(result["series"][0]["speed"], total["summaries"][0]["speed"]); + assert_eq!(result["rateLimits"], total["rateLimits"]); + } + let mut denied = query.clone(); + denied["agents"] = json!([]); + let result = harness.run("agentSessions.stats", denied); + for key in ["summaries", "groups", "series"] { + assert_eq!(result[key], json!([])); + } +} diff --git a/rust/crates/agent-sessions/Cargo.toml b/rust/crates/agent-sessions/Cargo.toml index e1fa0460..98c52282 100644 --- a/rust/crates/agent-sessions/Cargo.toml +++ b/rust/crates/agent-sessions/Cargo.toml @@ -11,8 +11,12 @@ globset = "0.4" lithe-protocol = { path = "../protocol" } # SQLite is bundled because Windows has no system library, and the cache needs # FTS5 with contentless deletes (SQLite 3.43 or later). -rusqlite = { version = "0.32", features = ["bundled"] } +rusqlite = { version = "0.32", features = ["bundled", "blob"] } serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" +serde_json = { version = "1.0", features = ["float_roundtrip"] } sha2 = "0.10" walkdir = "2" + +[[bench]] +name = "daily_overview" +harness = false diff --git a/rust/crates/agent-sessions/benches/daily_overview.rs b/rust/crates/agent-sessions/benches/daily_overview.rs new file mode 100644 index 00000000..94bb6c9f --- /dev/null +++ b/rust/crates/agent-sessions/benches/daily_overview.rs @@ -0,0 +1,129 @@ +//! Local synthetic baseline for record ingestion, three exact scans and a cached overview. +//! Run with `cargo bench -p lithe-agent-sessions --bench daily_overview`. + +use lithe_agent_sessions::pricing::PriceTable; +use lithe_agent_sessions::stats::{CallSelector, GroupBy, OverviewQuery, Summarizer}; +use lithe_agent_sessions::{database_file_name, CallFilter, SessionStore}; +use rusqlite::{params, Connection}; +use std::{fs, hint::black_box, time::Instant}; + +const DAY: i64 = 86_400_000; + +fn measure(name: &str, work: impl FnOnce() -> T) -> T { + let start = Instant::now(); + let result = work(); + println!("{name}: {:.2} ms", start.elapsed().as_secs_f64() * 1000.); + result +} + +fn run(days: i64) { + let root = + std::env::temp_dir().join(format!("lithe-usage-bench-{}-{days}", std::process::id())); + fs::create_dir(&root).expect("create a fresh benchmark directory"); + let store = SessionStore::open(&root).unwrap(); + let database = root.join(database_file_name()); + let db = Connection::open(&database).unwrap(); + let count = days * 1000; + db.execute("INSERT INTO files(id,agent,path,cursor_offset,fingerprint,generation) VALUES(1,'bench','sample',0,x'',1)", []).unwrap(); + measure("ingest", || { + db.execute( + "WITH RECURSIVE n(i) AS (VALUES(0) UNION ALL SELECT i+1 FROM n WHERE i+1 < ?1) + INSERT INTO calls(file_id,call_key,session_id,started_at_ms,model,input_tokens,output_tokens, + cache_read_tokens,first_token_ms,duration_ms,compaction,range_start,range_end) + SELECT 1,printf('c%d',i),'s',(i/1000)*86400000+i%1000,printf('m%d',i%4),500,100+i%809, + 20,100+i%17,1200+i%391,0,i,i+1 FROM n", [count]).unwrap() + }); + let filter = CallFilter { + agents: vec!["bench".into()], + ..CallFilter::default() + }; + let calendar = OverviewQuery { + today_ms: days * DAY, + initial_offset: 0, + offsets: vec![], + }; + let day = GroupBy::Day { + utc_offset_seconds: 0, + }; + let overview = |selector: &CallSelector, prices: Option<&PriceTable>| { + store + .usage_overview(&filter, selector, prices, day, GroupBy::Model, &calendar) + .unwrap() + }; + let all = CallSelector::default(); + let legacy = measure("three detail scans", || { + [GroupBy::All, GroupBy::Model, day].map(|group| { + let mut sums = Summarizer::new(group, None).detailed(); + if group == day { + sums = sums.split_by(GroupBy::Model); + } + store + .for_each_call(&filter, |entry| { + sums.add(&entry); + Ok(()) + }) + .unwrap(); + sums.finish() + }) + }); + let size = || { + db.query_row( + "SELECT page_count * page_size FROM pragma_page_count, pragma_page_size", + [], + |r| r.get::<_, i64>(0), + ) + .unwrap() + }; + let before = size(); + let cold = measure("cold overview", || overview(&all, None)); + assert_eq!(cold.summaries, legacy[0]); + assert_eq!(cold.groups, legacy[1]); + assert_eq!(cold.series, legacy[2]); + println!( + "{count} calls over {days} days, database {before} -> {} bytes", + size() + ); + for _ in 0..3 { + let warm = measure("warm overview", || overview(&all, None)); + assert_eq!(black_box(warm.summaries), legacy[0]); + } + let today = OverviewQuery { + today_ms: (days - 1) * DAY, + initial_offset: 0, + offsets: Vec::new(), + }; + let live = measure("warm overview with 1000 calls today", || { + store + .usage_overview(&filter, &all, None, day, GroupBy::Model, &today) + .unwrap() + }); + assert_eq!(live.summaries, legacy[0]); + measure("late insert", || { + db.execute( + "INSERT INTO calls(file_id,call_key,session_id,started_at_ms,model,output_tokens,compaction,range_start,range_end) + VALUES(1,'late','s',?1,'m0',100,0,0,1)", params![DAY+7]).unwrap() + }); + let changed = measure("refresh after late insert", || overview(&all, None)); + assert_eq!(changed.summaries[0].calls, count as u64 + 1); + let prices = + PriceTable::from_models_dev(br#"{"p":{"models":{"m0":{"cost":{"input":1,"output":2}}}}}"#) + .unwrap(); + measure("new price table", || overview(&all, Some(&prices))); + measure("text search", || { + overview(&CallSelector::default().with_search("m1"), Some(&prices)) + }); + drop(db); + drop(store); + fs::remove_file(database).unwrap(); + fs::remove_dir(root).unwrap(); +} + +fn main() { + // Cargo also runs custom harnesses under test --all-targets. + if !std::env::args_os().any(|arg| arg == "--bench") { + return; + } + for days in [175, 350] { + run(days); + } +} diff --git a/rust/crates/agent-sessions/src/pricing.rs b/rust/crates/agent-sessions/src/pricing.rs index 95a1acbc..9cb0daa9 100644 --- a/rust/crates/agent-sessions/src/pricing.rs +++ b/rust/crates/agent-sessions/src/pricing.rs @@ -8,6 +8,7 @@ use std::collections::HashMap; use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::model::Tokens; @@ -19,7 +20,7 @@ pub const MAX_PRICE_TABLE_BYTES: usize = 32 * 1024 * 1024; const CONTEXT_OVER_200K_TOKENS: u64 = 200_000; /// Prices of one model in one context range, in US dollars per million tokens. -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub struct Rates { /// Uncached input. pub input: f64, @@ -34,7 +35,7 @@ pub struct Rates { } /// Prices that apply when a prompt is larger than `above_prompt_tokens`. -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub struct Tier { /// Prompt tokens (input, cache reads and cache writes) the prompt must exceed. pub above_prompt_tokens: u64, @@ -43,7 +44,7 @@ pub struct Tier { } /// Prices of one model. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Price { /// Prices of prompts no larger than the first tier. pub base: Rates, diff --git a/rust/crates/agent-sessions/src/stats.rs b/rust/crates/agent-sessions/src/stats.rs index b9a332e2..53c71bdf 100644 --- a/rust/crates/agent-sessions/src/stats.rs +++ b/rust/crates/agent-sessions/src/stats.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use crate::model::CallRecord; use crate::pricing::{call_cost, PriceTable}; @@ -69,7 +69,7 @@ pub enum GroupBy { } /// The group a [`Summary`] covers. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)] #[serde(rename_all = "camelCase", tag = "kind")] pub enum GroupKey { /// A calendar day, as `YYYY-MM-DD`. @@ -128,7 +128,7 @@ pub enum GroupKey { } /// Sums of the token counts calls report. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TokenTotals { /// Uncached input tokens. @@ -146,7 +146,7 @@ pub struct TokenTotals { } /// What a cost stands for. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub enum CostBasis { /// The tokens priced at the provider's API prices, whatever the user @@ -155,7 +155,7 @@ pub enum CostBasis { } /// The cost of a group of calls. -#[derive(Debug, Clone, Copy, PartialEq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CostTotal { /// US dollars, over the priced calls. @@ -174,7 +174,7 @@ pub struct CostTotal { /// The median output speed of a group of calls, over the calls a speed /// ranking uses (see [`MIN_RANKED_OUTPUT_TOKENS`]). -#[derive(Debug, Clone, PartialEq, Serialize)] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SpeedSummary { /// Calls the median covers. @@ -186,7 +186,7 @@ pub struct SpeedSummary { } /// The average wait for the first output token of a group of calls. -#[derive(Debug, Clone, PartialEq, Serialize)] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct FirstTokenSummary { /// Successful calls that report the time of their first token. @@ -196,7 +196,7 @@ pub struct FirstTokenSummary { } /// Statistics of one group of calls. -#[derive(Debug, Clone, PartialEq, Serialize)] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Summary { /// The group. @@ -245,11 +245,12 @@ pub struct Summarizer<'a> { groups: BTreeMap<(GroupKey, Option), Accumulator>, } -#[derive(Debug)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct Accumulator { summary: Summary, cache_read: u64, cache_input: u64, + #[serde(skip)] speeds: Vec, lower_bound: bool, first_token_total_ms: u128, @@ -290,35 +291,103 @@ impl<'a> Summarizer<'a> { let accumulator = self .groups .entry((key.clone(), split.clone())) - .or_insert_with(|| Accumulator { - summary: Summary { - key, - split, - calls: 0, - failed_calls: 0, - compaction_calls: 0, - tokens: TokenTotals::default(), - cache_hit_rate: None, - cost: self.prices.map(|_| CostTotal { - usd: 0.0, - basis: CostBasis::ApiPriceEquivalent, - priced_calls: 0, - unpriced_calls: 0, - approximate_calls: 0, - }), - first_started_at_ms: call.started_at_ms, - last_started_at_ms: call.started_at_ms, - speed: None, - first_token: None, - }, - cache_read: 0, - cache_input: 0, - speeds: Vec::new(), - lower_bound: false, - first_token_total_ms: 0, - first_token_calls: 0, + .or_insert_with(|| Accumulator::new(key, split, self.prices)); + accumulator.add(call, self.prices, self.detailed); + } + + /// The groups, in order of their keys, then of their second keys. + pub fn finish(self) -> Vec { + self.groups.into_values().map(Accumulator::finish).collect() + } +} + +impl Accumulator { + fn new(key: GroupKey, split: Option, prices: Option<&PriceTable>) -> Self { + Self { + summary: Summary { + key, + split, + calls: 0, + failed_calls: 0, + compaction_calls: 0, + tokens: TokenTotals::default(), + cache_hit_rate: None, + cost: prices.map(|_| CostTotal { + usd: 0.0, + basis: CostBasis::ApiPriceEquivalent, + priced_calls: 0, + unpriced_calls: 0, + approximate_calls: 0, + }), + first_started_at_ms: i64::MAX, + last_started_at_ms: i64::MIN, + speed: None, + first_token: None, + }, + cache_read: 0, + cache_input: 0, + speeds: Vec::new(), + lower_bound: false, + first_token_total_ms: 0, + first_token_calls: 0, + } + } + + fn finish(mut self) -> Summary { + let mut summary = self.summary; + summary.cache_hit_rate = + (self.cache_input > 0).then(|| self.cache_read as f64 / self.cache_input as f64); + if !self.speeds.is_empty() { + summary.speed = Some(SpeedSummary { + calls: self.speeds.len() as u64, + median_tokens_per_second: median(&mut self.speeds), + lower_bound: self.lower_bound, }); - let summary = &mut accumulator.summary; + } + if self.first_token_calls > 0 { + summary.first_token = Some(FirstTokenSummary { + calls: self.first_token_calls, + average_ms: self.first_token_total_ms as f64 / self.first_token_calls as f64, + }); + } + summary + } + + fn merge_counts(&mut self, other: &Self) { + let dst = &mut self.summary; + let src = &other.summary; + dst.calls += src.calls; + dst.failed_calls += src.failed_calls; + dst.compaction_calls += src.compaction_calls; + dst.first_started_at_ms = dst.first_started_at_ms.min(src.first_started_at_ms); + dst.last_started_at_ms = dst.last_started_at_ms.max(src.last_started_at_ms); + dst.tokens.input = dst.tokens.input.saturating_add(src.tokens.input); + dst.tokens.output = dst.tokens.output.saturating_add(src.tokens.output); + dst.tokens.cache_read = dst.tokens.cache_read.saturating_add(src.tokens.cache_read); + dst.tokens.cache_write_5m = dst + .tokens + .cache_write_5m + .saturating_add(src.tokens.cache_write_5m); + dst.tokens.cache_write_1h = dst + .tokens + .cache_write_1h + .saturating_add(src.tokens.cache_write_1h); + dst.tokens.reasoning = dst.tokens.reasoning.saturating_add(src.tokens.reasoning); + if let (Some(a), Some(b)) = (&mut dst.cost, &src.cost) { + a.usd += b.usd; + a.priced_calls += b.priced_calls; + a.unpriced_calls += b.unpriced_calls; + a.approximate_calls += b.approximate_calls; + } + self.cache_read = self.cache_read.saturating_add(other.cache_read); + self.cache_input = self.cache_input.saturating_add(other.cache_input); + self.first_token_total_ms += other.first_token_total_ms; + self.first_token_calls += other.first_token_calls; + self.lower_bound |= other.lower_bound; + } + + fn add(&mut self, call: &CallRecord, prices: Option<&PriceTable>, detailed: bool) { + let summary = &mut self.summary; summary.calls += 1; summary.failed_calls += u64::from(call.error_category.is_some()); summary.compaction_calls += u64::from(call.compaction); @@ -339,8 +408,8 @@ impl<'a> Summarizer<'a> { } if tokens.reports_cache() { let read = tokens.cache_read.unwrap_or(0); - accumulator.cache_read = accumulator.cache_read.saturating_add(read); - accumulator.cache_input = [ + self.cache_read = self.cache_read.saturating_add(read); + self.cache_input = [ tokens.input, Some(read), tokens.cache_write_5m, @@ -348,10 +417,10 @@ impl<'a> Summarizer<'a> { ] .into_iter() .flatten() - .fold(accumulator.cache_input, u64::saturating_add); + .fold(self.cache_input, u64::saturating_add); } - if let (Some(prices), Some(cost)) = (self.prices, summary.cost.as_mut()) { + if let (Some(prices), Some(cost)) = (prices, summary.cost.as_mut()) { let priced = model_name(call) .and_then(|model| prices.lookup(call.provider.as_deref(), model)) .and_then(|price| call_cost(price, tokens)); @@ -365,44 +434,17 @@ impl<'a> Summarizer<'a> { } } - if self.detailed { + if detailed { if let Some(speed) = ranked_speed(call) { - accumulator.speeds.push(speed.tokens_per_second()); - accumulator.lower_bound |= matches!(speed, Speed::AtLeast(_)); + self.speeds.push(speed.tokens_per_second()); + self.lower_bound |= matches!(speed, Speed::AtLeast(_)); } if let (None, Some(first)) = (&call.error_category, call.first_token_ms) { - accumulator.first_token_total_ms += u128::from(first); - accumulator.first_token_calls += 1; + self.first_token_total_ms += u128::from(first); + self.first_token_calls += 1; } } } - - /// The groups, in order of their keys, then of their second keys. - pub fn finish(self) -> Vec { - self.groups - .into_values() - .map(|mut accumulator| { - let mut summary = accumulator.summary; - summary.cache_hit_rate = (accumulator.cache_input > 0) - .then(|| accumulator.cache_read as f64 / accumulator.cache_input as f64); - if !accumulator.speeds.is_empty() { - summary.speed = Some(SpeedSummary { - calls: accumulator.speeds.len() as u64, - median_tokens_per_second: median(&mut accumulator.speeds), - lower_bound: accumulator.lower_bound, - }); - } - if accumulator.first_token_calls > 0 { - summary.first_token = Some(FirstTokenSummary { - calls: accumulator.first_token_calls, - average_ms: accumulator.first_token_total_ms as f64 - / accumulator.first_token_calls as f64, - }); - } - summary - }) - .collect() - } } /// Groups `entries` by `group_by`; see [`Summarizer`]. @@ -688,3 +730,6 @@ pub(crate) fn civil_date(at_ms: i64, utc_offset_seconds: i32) -> String { let year = year_of_era + era * 400 + i64::from(month <= 2); format!("{year:04}-{month:02}-{day:02}") } + +mod overview; +pub use overview::{CalendarOffset, Overview, OverviewQuery}; diff --git a/rust/crates/agent-sessions/src/stats/overview.rs b/rust/crates/agent-sessions/src/stats/overview.rs new file mode 100644 index 00000000..d1e66de9 --- /dev/null +++ b/rust/crates/agent-sessions/src/stats/overview.rs @@ -0,0 +1,590 @@ +//! Daily usage shared by the overview totals, breakdown and chart. +//! Each finished local day contains only observed model/provider/outcome combinations. +//! Its counts and speed block bounds can be read without loading the speed samples. + +use super::*; +use crate::store::{sql_error, CallFilter, SessionStore}; +use lithe_protocol::{cancellation, CoreError, ErrorCode}; +use rusqlite::{params, OptionalExtension}; +use std::rc::Rc; + +/// One change in the calendar's UTC offset. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CalendarOffset { + /// First instant using the new offset. + pub at_ms: i64, + /// Seconds east of UTC. + pub seconds: i32, +} + +/// Local calendar supplied by the desktop for an overview read. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OverviewQuery { + /// Midnight starting the still-changing day. + pub today_ms: i64, + /// Offset before the first change. + pub initial_offset: i32, + /// Subsequent changes in chronological order. + #[serde(default)] + pub offsets: Vec, +} + +impl OverviewQuery { + /// Checks bounds before using the supplied calendar in date arithmetic. + pub fn valid(&self) -> bool { + let valid_offset = |v: i32| (-86400..86400).contains(&v); + self.offsets.len() <= 4096 + && valid_offset(self.initial_offset) + && self.offsets.iter().all(|o| valid_offset(o.seconds)) + && self.offsets.windows(2).all(|w| w[0].at_ms < w[1].at_ms) + } + + fn day(&self, at: i64) -> (i64, i64, String) { + let index = self.offsets.partition_point(|o| o.at_ms <= at); + let offset = |i: usize| { + if i == 0 { + self.initial_offset + } else { + self.offsets[i - 1].seconds + } + }; + let date = civil_date(at, offset(index)); + let midnight = |ms: i64, seconds: i32| { + let shift = i64::from(seconds) * 1000; + ms.saturating_sub( + (ms.rem_euclid(MILLISECONDS_PER_DAY) + shift).rem_euclid(MILLISECONDS_PER_DAY), + ) + }; + let mut start = midnight(at, offset(index)); + for i in (1..=index).rev() { + let transition = self.offsets[i - 1].at_ms; + if start > transition { + break; + } + let previous = transition.saturating_sub(1); + if civil_date(previous, offset(i - 1)) != date { + start = transition; + break; + } + start = midnight(previous, offset(i - 1)); + } + let mut end = midnight(at, offset(index)).saturating_add(MILLISECONDS_PER_DAY); + for change in &self.offsets[index..] { + if end < change.at_ms { + break; + } + if civil_date(change.at_ms, change.seconds) != date { + end = change.at_ms; + break; + } + end = midnight(change.at_ms, change.seconds).saturating_add(MILLISECONDS_PER_DAY); + } + (start, end, date) + } +} + +/// Three projections of the same filtered records, from one database snapshot. +#[derive(Default, Serialize)] +pub struct Overview { + /// Period totals (empty when there are no matching calls). + pub summaries: Vec, + /// Breakdown by the selected dimension. + pub groups: Vec, + /// Sparse hour or local day buckets, split by that dimension. + pub series: Vec, +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +struct CellKey { + agent: String, + model: Option, + provider: Option, + failed: bool, +} + +impl CellKey { + fn of(entry: &CallEntry) -> Self { + Self { + agent: entry.agent.clone(), + model: model_name(&entry.call).map(str::to_owned), + provider: entry.call.provider.clone(), + failed: entry.call.error_category.is_some(), + } + } + + fn keeps(&self, selector: &CallSelector) -> bool { + let matches = |names: &[String], value: Option<&str>| { + names.is_empty() || names.iter().any(|s| s == value.unwrap_or("")) + }; + matches(&selector.models, self.model.as_deref()) + && matches(&selector.providers, self.provider.as_deref()) + && selector.failed.is_none_or(|f| f == self.failed) + } + + fn group(&self, by: GroupBy) -> GroupKey { + match by { + GroupBy::Agent => GroupKey::Agent { + agent: self.agent.clone(), + }, + GroupBy::Model => GroupKey::Model { + model: self.model.clone(), + }, + GroupBy::Provider => GroupKey::Provider { + provider: self.provider.clone(), + }, + GroupBy::ModelProvider => GroupKey::ModelProvider { + model: self.model.clone(), + provider: self.provider.clone(), + }, + _ => unreachable!("validated overview split"), + } + } +} + +/// Bounds let the median read just blocks that can contain a middle value. +#[derive(Clone, Serialize, Deserialize)] +struct Block { + low: f64, + high: f64, + count: usize, + offset: usize, +} + +#[derive(Serialize, Deserialize)] +struct Cell { + key: CellKey, + counts: Accumulator, + blocks: Vec, +} + +#[derive(Clone)] +enum Samples { + Stored(i64), + Fresh(Rc<[u8]>), +} + +impl Samples { + fn read(&self, store: &SessionStore, block: &Block) -> Result, CoreError> { + let size = block.count * 8; + match self { + Self::Stored(id) => { + let blob = store + .connection + .blob_open( + rusqlite::DatabaseName::Main, + "usage_days", + "samples", + *id, + true, + ) + .map_err(db_error)?; + let mut bytes = vec![0; size]; + blob.read_at_exact(&mut bytes, block.offset) + .map_err(db_error)?; + Ok(bytes) + } + Self::Fresh(bytes) => Ok(bytes[block.offset..block.offset + size].to_vec()), + } + } +} + +struct Group { + counts: Accumulator, + blocks: Vec<(Block, Samples)>, +} + +#[derive(Default)] +struct Projection { + groups: BTreeMap<(GroupKey, Option), Group>, +} + +impl Projection { + fn add(&mut self, key: GroupKey, split: Option, cell: &Cell, samples: &Samples) { + use std::collections::btree_map::Entry; + let blocks = match self.groups.entry((key.clone(), split.clone())) { + Entry::Occupied(mut entry) => { + entry.get_mut().counts.merge_counts(&cell.counts); + &mut entry.into_mut().blocks + } + Entry::Vacant(entry) => { + let mut counts = cell.counts.clone(); + counts.summary.key = key; + counts.summary.split = split; + &mut entry + .insert(Group { + counts, + blocks: Vec::new(), + }) + .blocks + } + }; + blocks.extend(cell.blocks.iter().map(|b| (b.clone(), samples.clone()))); + } + + fn finish(self, store: &SessionStore) -> Result, CoreError> { + self.groups + .into_values() + .map(|Group { mut counts, blocks }| { + if !blocks.is_empty() { + let n: usize = blocks.iter().map(|(b, _)| b.count).sum(); + counts.summary.speed = Some(SpeedSummary { + calls: n as u64, + median_tokens_per_second: block_median(store, &blocks, n)?, + lower_bound: counts.lower_bound, + }); + } + Ok(counts.finish()) + }) + .collect() + } +} + +fn block_median( + store: &SessionStore, + blocks: &[(Block, Samples)], + n: usize, +) -> Result { + let bound = |upper: bool, rank: usize| { + let mut ends: Vec<_> = blocks + .iter() + .map(|(b, _)| (if upper { b.high } else { b.low }, b.count)) + .collect(); + ends.sort_unstable_by(|a, b| a.0.total_cmp(&b.0)); + let mut remaining = rank; + for (value, count) in ends { + if remaining < count { + return value; + } + remaining -= count; + } + unreachable!("bounds cover every sample") + }; + let low = bound(false, (n - 1) / 2); + let high = bound(true, n / 2); + if low == high { + return Ok(low); + } + let mut below = 0; + let mut middle = Vec::new(); + for (block, source) in blocks { + cancellation::check()?; + if block.high < low { + below += block.count; + } else if block.low <= high { + let bytes = source.read(store, block)?; + if bytes.len() != block.count * 8 { + return Err(cache_error()); + } + for value in bytes.as_chunks::<8>().0 { + let speed = f64::from_le_bytes(*value); + if speed < low { + below += 1; + } else if speed <= high { + middle.push(speed); + } + } + } + } + middle.sort_unstable_by(f64::total_cmp); + Ok((middle[(n - 1) / 2 - below] + middle[n / 2 - below]) / 2.0) +} + +fn db_error(e: rusqlite::Error) -> CoreError { + sql_error("Could not read or update daily agent usage", e) +} + +fn cache_error() -> CoreError { + CoreError::new(ErrorCode::ParseFailed, "Invalid daily agent usage data.") +} + +fn pack(groups: BTreeMap) -> (Vec, Vec) { + let mut bytes = Vec::new(); + let cells = groups + .into_iter() + .map(|(key, mut counts)| { + let mut speeds = std::mem::take(&mut counts.speeds); + speeds.sort_unstable_by(f64::total_cmp); + let mut blocks = Vec::new(); + for part in speeds.chunks(32) { + blocks.push(Block { + low: part[0], + high: part[part.len() - 1], + count: part.len(), + offset: bytes.len(), + }); + for speed in part { + bytes.extend_from_slice(&speed.to_le_bytes()); + } + } + Cell { + key, + counts, + blocks, + } + }) + .collect(); + (cells, bytes) +} + +struct Period<'a> { + filter: &'a CallFilter, + calendar: &'a OverviewQuery, + prices: Option<&'a PriceTable>, +} + +impl Period<'_> { + // Only the rates used by this day's models matter. Updating an unrelated + // model in the price catalog keeps every statistic of this day reusable. + fn day_prices(&self, cells: &[Cell]) -> Result, CoreError> { + let used = self.prices.map(|table| { + cells + .iter() + .filter_map(|cell| Some((cell.key.model.as_deref()?, cell.key.provider.as_deref()))) + .collect::>() + .into_iter() + .map(|(model, provider)| (model, provider, table.lookup(provider, model))) + .collect::>() + }); + serde_json::to_vec(&used).map_err(|_| cache_error()) + } + + fn prices_match(&self, saved: &[u8]) -> Result { + let Some(table) = self.prices else { + return Ok(saved == b"null"); + }; + type ModelPrice = (String, Option, Option); + let used: Option> = + serde_json::from_slice(saved).map_err(|_| cache_error())?; + Ok(used.is_some_and(|rows| { + rows.iter().all(|(model, provider, price)| { + table.lookup(provider.as_deref(), model) == price.as_ref() + }) + })) + } + + fn visit_days( + &self, + store: &SessionStore, + mut visit: impl FnMut(&str, i64, i64, String, bool) -> Result<(), CoreError>, + ) -> Result<(), CoreError> { + let mut next = store.connection.prepare_cached( + "SELECT started_at_ms FROM selected_calls WHERE agent = ?1 AND started_at_ms >= ?2 AND started_at_ms <= ?3 ORDER BY started_at_ms LIMIT 1" + ).map_err(db_error)?; + for agent in self + .filter + .agents + .iter() + .collect::>() + { + let mut from = self.filter.since_ms.unwrap_or(i64::MIN); + let last = match self.filter.until_ms { + Some(ms) => match ms.checked_sub(1) { + Some(ms) => ms, + None => continue, + }, + None => i64::MAX, + }; + while from <= last { + cancellation::check()?; + let at: Option = next + .query_row(params![agent, from, last], |r| r.get(0)) + .optional() + .map_err(db_error)?; + let Some(at) = at else { + break; + }; + let (start, end, date) = self.calendar.day(at); + let complete = start >= self.filter.since_ms.unwrap_or(i64::MIN) + && end <= self.filter.until_ms.unwrap_or(i64::MAX) + && end <= self.calendar.today_ms + && end > at; + visit(agent, start, end, date, complete)?; + if end <= at || end == i64::MAX { + break; + } + from = end; + } + } + Ok(()) + } + + fn warm(&self, store: &SessionStore) -> Result<(), CoreError> { + self.visit_days(store, |agent, start, end, _, complete| { + if complete { + self.warm_day(store, agent, start, end)?; + } + Ok(()) + }) + } + + fn warm_day( + &self, + store: &SessionStore, + agent: &str, + start: i64, + end: i64, + ) -> Result<(), CoreError> { + let tx = store.connection.unchecked_transaction().map_err(db_error)?; + let saved: Option> = tx + .query_row( + "SELECT prices FROM usage_days WHERE agent=?1 AND start_ms=?2 AND end_ms=?3", + params![agent, start, end], + |row| row.get(0), + ) + .optional() + .map_err(db_error)?; + if let Some(saved) = saved { + if self.prices_match(&saved)? { + return Ok(()); + } + } + let filter = CallFilter { + agents: vec![agent.to_owned()], + since_ms: Some(start), + until_ms: Some(end), + session_id: None, + }; + let mut cells = BTreeMap::new(); + store.for_each_call(&filter, |entry| { + cells + .entry(CellKey::of(&entry)) + .or_insert_with(|| Accumulator::new(GroupKey::All, None, self.prices)) + .add(&entry.call, self.prices, true); + Ok(()) + })?; + // A sync can remove the last copy between discovering a day and opening + // its snapshot. In particular, never recreate a forgotten agent's cache row. + if cells.is_empty() { + return Ok(()); + } + let (cells, bytes) = pack(cells); + let data = serde_json::to_vec(&cells).map_err(|_| cache_error())?; + + // Build under a read snapshot. If a sync has taken the writer or changed + // that snapshot, skip publishing. The final read still has its exact path. + let publish = tx.execute( + "DELETE FROM usage_days WHERE agent=?1 AND start_ms < ?3 AND end_ms > ?2", + params![agent, start, end], + ); + if publish + .as_ref() + .is_err_and(|e| e.sqlite_error_code() == Some(rusqlite::ErrorCode::DatabaseBusy)) + { + return Ok(()); + } + publish.map_err(db_error)?; + tx.execute( + "INSERT INTO usage_days(agent,start_ms,end_ms,prices,counts,samples) + VALUES(?1,?2,?3,?4,?5,?6)", + params![agent, start, end, self.day_prices(&cells)?, data, bytes], + ) + .map_err(db_error)?; + tx.commit().map_err(db_error) + } +} + +impl SessionStore { + /// Reads the three overview projections. The caller supplies the readable agents, + /// a day or hour series and a validated non-temporal split dimension. + pub fn usage_overview( + &self, + filter: &CallFilter, + selector: &CallSelector, + prices: Option<&PriceTable>, + series: GroupBy, + split: GroupBy, + calendar: &OverviewQuery, + ) -> Result { + if !calendar.valid() + || !matches!(series, GroupBy::Day { .. } | GroupBy::Hour { .. }) + || !matches!( + split, + GroupBy::Model | GroupBy::Agent | GroupBy::Provider | GroupBy::ModelProvider + ) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid usage overview grouping or calendar.", + )); + } + let period = Period { + filter, + calendar, + prices, + }; + let reusable = matches!(series, GroupBy::Day { .. }) + && selector.words.is_empty() + && filter.session_id.is_none(); + if reusable { + period.warm(self)?; + } + let snapshot = self.connection.unchecked_transaction().map_err(db_error)?; + let (mut totals, mut groups, mut chart) = ( + Projection::default(), + Projection::default(), + Projection::default(), + ); + let mut consume = |cell: &Cell, time: &GroupKey, samples: &Samples| { + let group = cell.key.group(split); + totals.add(GroupKey::All, None, cell, samples); + groups.add(group.clone(), None, cell, samples); + chart.add(time.clone(), Some(group), cell, samples); + }; + period.visit_days(self, |agent, start, end, date, complete| { + let day = GroupKey::Day { date }; + if reusable && complete { + let cached = snapshot.query_row( + "SELECT id, counts, prices FROM usage_days WHERE agent=?1 AND start_ms=?2 AND end_ms=?3", + params![agent, start, end], + |row| Ok((row.get::<_, i64>(0)?, row.get::<_, Vec>(1)?, row.get::<_,Vec>(2)?)), + ).optional().map_err(db_error)?; + if let Some((id, bytes, rates)) = cached { + if period.prices_match(&rates)? { + let cells: Vec = serde_json::from_slice(&bytes).map_err(|_| cache_error())?; + for cell in cells.iter().filter(|cell| cell.key.keeps(selector)) { + consume(cell, &day, &Samples::Stored(id)); + } + return Ok(()); + } + } + } + + let mut part = filter.clone(); + part.agents = vec![agent.to_owned()]; + part.since_ms = Some(start.max(filter.since_ms.unwrap_or(i64::MIN))); + if end < i64::MAX { + part.until_ms = Some(end.min(filter.until_ms.unwrap_or(i64::MAX))); + } + let mut buckets = BTreeMap::>::new(); + self.for_each_call(&part, |entry| { + if selector.keeps(&entry) { + let time = match series { + GroupBy::Hour { .. } => group_key(series, &entry), + _ => day.clone(), + }; + buckets.entry(time).or_default().entry(CellKey::of(&entry)) + .or_insert_with(|| Accumulator::new(GroupKey::All, None, prices)) + .add(&entry.call, prices, true); + } + Ok(()) + })?; + for (time, entries) in buckets { + let (cells, bytes) = pack(entries); + let samples = Samples::Fresh(bytes.into()); + for cell in &cells { + consume(cell, &time, &samples); + } + } + Ok(()) + })?; + let answer = Overview { + summaries: totals.finish(self)?, + groups: groups.finish(self)?, + series: chart.finish(self)?, + }; + snapshot.commit().map_err(db_error)?; + Ok(answer) + } +} diff --git a/rust/crates/agent-sessions/src/store.rs b/rust/crates/agent-sessions/src/store.rs index 1c02a0db..3e39c6b7 100644 --- a/rust/crates/agent-sessions/src/store.rs +++ b/rust/crates/agent-sessions/src/store.rs @@ -29,7 +29,7 @@ use crate::text; /// Version of the database layout. A cache of another version is deleted and /// rebuilt from the session files, so it is never migrated. -pub const SCHEMA_VERSION: u32 = 2; +pub const SCHEMA_VERSION: u32 = 3; /// Longest identifier, in bytes: agent, session, call, thread and request IDs. pub const MAX_ID_BYTES: usize = 256; @@ -144,6 +144,69 @@ CREATE TABLE calls ( ) STRICT, WITHOUT ROWID; CREATE INDEX calls_by_key ON calls (call_key); +-- Keep the same first copy as the former ROW_NUMBER query. Readers can then +-- seek to a time range without ranking the whole history first. +CREATE TABLE selected_calls ( + agent TEXT NOT NULL, + call_key TEXT NOT NULL, + file_id INTEGER NOT NULL, + started_at_ms INTEGER NOT NULL, + PRIMARY KEY (agent, call_key) +) STRICT, WITHOUT ROWID; +CREATE INDEX selected_by_time ON selected_calls(started_at_ms, agent, call_key); +CREATE VIEW first_copies AS + SELECT f.agent, c.call_key, c.file_id, c.started_at_ms, f.path + FROM calls c JOIN files f ON f.id = c.file_id; + +-- The payload holds counts and offsets into the sorted speed samples. +CREATE TABLE usage_days ( + id INTEGER PRIMARY KEY, + agent TEXT NOT NULL, + start_ms INTEGER NOT NULL, + end_ms INTEGER NOT NULL, + prices BLOB NOT NULL, + counts BLOB NOT NULL, + samples BLOB NOT NULL, + UNIQUE(agent, start_ms) +) STRICT; +CREATE INDEX selected_by_agent_time ON selected_calls(agent, started_at_ms); +CREATE TRIGGER select_inserted_call AFTER INSERT ON calls +WHEN NEW.file_id = ( + SELECT file_id FROM first_copies WHERE call_key = NEW.call_key + AND agent = (SELECT agent FROM files WHERE id = NEW.file_id) + ORDER BY path LIMIT 1 +) +BEGIN + DELETE FROM selected_calls WHERE agent = (SELECT agent FROM files WHERE id = NEW.file_id) + AND call_key = NEW.call_key; + INSERT INTO selected_calls SELECT agent, NEW.call_key, NEW.file_id, NEW.started_at_ms + FROM files WHERE id = NEW.file_id; +END; +CREATE TRIGGER replace_removed_call AFTER DELETE ON calls +WHEN EXISTS (SELECT 1 FROM selected_calls WHERE call_key = OLD.call_key + AND agent = (SELECT agent FROM files WHERE id = OLD.file_id) AND file_id = OLD.file_id) +BEGIN + DELETE FROM selected_calls WHERE agent = (SELECT agent FROM files WHERE id = OLD.file_id) + AND call_key = OLD.call_key; + INSERT INTO selected_calls + SELECT agent, call_key, file_id, started_at_ms FROM first_copies + WHERE call_key = OLD.call_key AND agent = (SELECT agent FROM files WHERE id = OLD.file_id) + ORDER BY path LIMIT 1; +END; + +-- Days for one agent never overlap. Seek to the one preceding the instant +-- instead of checking every historical day on every write. +CREATE TRIGGER invalidate_old_day AFTER DELETE ON selected_calls BEGIN + DELETE FROM usage_days WHERE id = (SELECT id FROM usage_days + WHERE agent = OLD.agent AND start_ms <= OLD.started_at_ms ORDER BY start_ms DESC LIMIT 1) + AND end_ms > OLD.started_at_ms; +END; +CREATE TRIGGER invalidate_new_day AFTER INSERT ON selected_calls BEGIN + DELETE FROM usage_days WHERE id = (SELECT id FROM usage_days + WHERE agent = NEW.agent AND start_ms <= NEW.started_at_ms ORDER BY start_ms DESC LIMIT 1) + AND end_ms > NEW.started_at_ms; +END; + CREATE TABLE spans ( id INTEGER PRIMARY KEY, file_id INTEGER NOT NULL, @@ -166,7 +229,7 @@ CREATE VIRTUAL TABLE span_terms USING fts5 ( /// The local cache of session records. pub struct SessionStore { - connection: Connection, + pub(crate) connection: Connection, pub(crate) limits: ChunkLimits, } @@ -565,22 +628,12 @@ impl SessionStore { mut visit: impl FnMut(CallEntry) -> Result<(), CoreError>, ) -> Result { const SQL: &str = " - WITH ranked AS ( - SELECT f.agent, f.path, c.*, - ROW_NUMBER() OVER ( - PARTITION BY f.agent, c.call_key - ORDER BY f.path, c.range_start - ) AS copy_rank - FROM calls c JOIN files f ON f.id = c.file_id - WHERE json_array_length(?1) = 0 - OR f.agent IN (SELECT value FROM json_each(?1)) - ) - SELECT r.agent, r.path, + SELECT w.agent, f.path, COALESCE( (SELECT s.cwd FROM sessions s WHERE s.file_id = r.file_id AND s.session_id = r.session_id), (SELECT s.cwd FROM sessions s JOIN files sf ON sf.id = s.file_id - WHERE s.session_id = r.session_id AND sf.agent = r.agent + WHERE s.session_id = r.session_id AND sf.agent = w.agent AND s.cwd IS NOT NULL ORDER BY sf.path LIMIT 1)), r.call_key, r.session_id, r.thread_id, r.started_at_ms, @@ -589,12 +642,14 @@ impl SessionStore { r.cache_write_5m_tokens, r.cache_write_1h_tokens, r.reasoning_tokens, r.first_token_ms, r.duration_ms, r.compaction, r.request_id, r.error_category, r.range_start, r.range_end - FROM ranked r - WHERE r.copy_rank = 1 + FROM selected_calls w + JOIN calls r ON r.file_id = w.file_id AND r.call_key = w.call_key + JOIN files f ON f.id = w.file_id + WHERE (json_array_length(?1) = 0 OR w.agent IN (SELECT value FROM json_each(?1))) AND (?2 IS NULL OR r.session_id = ?2) - AND (?3 IS NULL OR r.started_at_ms >= ?3) - AND (?4 IS NULL OR r.started_at_ms < ?4) - ORDER BY r.started_at_ms, r.agent, r.call_key"; + AND w.started_at_ms >= COALESCE(?3, -9223372036854775808) + AND w.started_at_ms <= COALESCE(?4, 9223372036854775807) AND (?4 IS NULL OR w.started_at_ms < ?4) + ORDER BY w.started_at_ms, w.agent, w.call_key"; let mut statement = self .connection .prepare_cached(SQL) @@ -1650,7 +1705,7 @@ pub(crate) fn io_error(message: &str, error: io::Error) -> CoreError { /// A SQLite failure. SQLite's own message can quote a statement or a value, /// so only its result code is kept. -fn sql_error(message: &str, error: rusqlite::Error) -> CoreError { +pub(crate) fn sql_error(message: &str, error: rusqlite::Error) -> CoreError { let details = match &error { rusqlite::Error::SqliteFailure(failure, _) | rusqlite::Error::SqlInputError { error: failure, .. } => { diff --git a/rust/crates/agent-sessions/src/tests/store.rs b/rust/crates/agent-sessions/src/tests/store.rs index 200e1e02..0c12af9d 100644 --- a/rust/crates/agent-sessions/src/tests/store.rs +++ b/rust/crates/agent-sessions/src/tests/store.rs @@ -1086,3 +1086,245 @@ fn session_counts_ignore_the_page_and_group_by_directory() { "groupsTruncated": false }) ); } + +#[test] +fn daily_overview_tracks_replaced_and_forgotten_copies() { + use crate::pricing::PriceTable; + use crate::stats::{CallSelector, GroupBy, OverviewQuery, Summarizer}; + const DAY: i64 = 86_400_000; + let mut f = Fixture::new("daily-copies"); + let a = f.file("a"); + let b = f.file("b"); + let c = f.file("c"); + append( + &a, + &(session_line("s", "/work", 0) + &call_line("copy", 1, "m", 12, 100)), + ); + append( + &b, + &(session_line("s", "/work", 0) + + &call_line("copy", DAY + 5, "m", 24, 300) + + &call_line("unique", DAY + 10, "m", 12, 100)), + ); + append( + &c, + &(session_line("s", "/work", 0) + &call_line("stable", 2 * DAY + 1, "m", 12, 100)), + ); + f.sync(&[a.clone(), b.clone(), c.clone()]); + let calendar = OverviewQuery { + today_ms: 5 * DAY, + initial_offset: 0, + offsets: vec![], + }; + let filter = CallFilter { + agents: vec![AGENT.into()], + ..CallFilter::default() + }; + let check = |store: &SessionStore, prices: Option<&PriceTable>, selector: CallSelector| { + let overview = store + .usage_overview( + &filter, + &selector, + prices, + GroupBy::Day { + utc_offset_seconds: 0, + }, + GroupBy::Model, + &calendar, + ) + .expect("overview"); + let mut total = Summarizer::new(GroupBy::All, prices).detailed(); + let mut series = Summarizer::new( + GroupBy::Day { + utc_offset_seconds: 0, + }, + prices, + ) + .split_by(GroupBy::Model) + .detailed(); + store + .for_each_call(&filter, |entry| { + if selector.keeps(&entry) { + total.add(&entry); + series.add(&entry); + } + Ok(()) + }) + .expect("scan"); + assert_eq!(overview.summaries, total.finish()); + assert_eq!(overview.series, series.finish()); + }; + check(&f.store, None, CallSelector::default()); + f.store = SessionStore::open(&f.dir.path().join("cache")).expect("reopen"); + check(&f.store, None, CallSelector::default()); + let days = |s: &SessionStore| { + s.connection + .prepare("SELECT start_ms FROM usage_days ORDER BY start_ms") + .unwrap() + .query_map([], |r| r.get::<_, i64>(0)) + .unwrap() + .collect::, _>>() + .unwrap() + }; + assert_eq!(days(&f.store), [0, DAY, 2 * DAY]); + f.sync(&[b.clone(), c.clone()]); + assert_eq!(days(&f.store), [2 * DAY]); + check(&f.store, None, CallSelector::default()); + append(&b, &call_line("unique", 3 * DAY + 10, "m", 7, 400)); + f.sync(&[b, c]); + assert_eq!(days(&f.store), [2 * DAY]); + for rate in [1, 2] { + let table = PriceTable::from_models_dev( + &serde_json::to_vec( + &json!({"vendor":{"models":{"m":{"cost":{"input":rate,"output":rate}}}}}), + ) + .unwrap(), + ) + .unwrap(); + check(&f.store, Some(&table), CallSelector::default()); + } + check(&f.store, None, CallSelector::default().with_search("work")); + f.store.remove_agent(AGENT).unwrap(); + assert!(days(&f.store).is_empty()); + check(&f.store, None, CallSelector::default()); +} + +#[test] +fn warm_overview_answers_from_saved_days_and_busy_writer_keeps_precise_results() { + use crate::stats::{CallSelector, GroupBy, OverviewQuery, Summarizer}; + const DAY: i64 = 86_400_000; + let mut f = Fixture::new("warm-speeds"); + let file = f.file("history"); + let mut input = session_line("session", "/workspace", 0); + for i in 0..256 { + input += &format!( + "{}\n", + json!({"type":"call","key":format!("c{i}"),"at":i%2*DAY+1, + "model": if i%3==0 {"a"} else {"b"}, "provider":"p", "input":100,"cacheRead":5, + "output":120+i, "durationMs":1700+i%23, "firstTokenMs":100+i%11}) + ); + } + append(&file, &input); + f.sync(&[file]); + let filter = CallFilter { + agents: vec![AGENT.into()], + ..CallFilter::default() + }; + let calendar = OverviewQuery { + today_ms: 3 * DAY, + initial_offset: 0, + offsets: vec![], + }; + let expected = |filter: &CallFilter| { + let mut sums = Summarizer::new(GroupBy::All, None).detailed(); + f.store + .for_each_call(filter, |entry| { + sums.add(&entry); + Ok(()) + }) + .unwrap(); + sums.finish() + }; + let read = |filter: &CallFilter| { + f.store + .usage_overview( + filter, + &CallSelector::default(), + None, + GroupBy::Day { + utc_offset_seconds: 0, + }, + GroupBy::Model, + &calendar, + ) + .unwrap() + .summaries + }; + let total = expected(&filter); + let writer = SessionStore::open(&f.dir.path().join("cache")).unwrap(); + writer.connection.execute_batch("BEGIN IMMEDIATE").unwrap(); + assert_eq!(read(&filter), total); + writer.connection.execute_batch("ROLLBACK").unwrap(); + assert_eq!(read(&filter), total); + let partial = CallFilter { + since_ms: Some(2), + until_ms: Some(DAY + 2), + ..filter.clone() + }; + assert_eq!(read(&partial), expected(&partial)); + + let priced = |rates: &[u8]| { + let table = crate::pricing::PriceTable::from_models_dev(rates).unwrap(); + f.store + .usage_overview( + &filter, + &CallSelector::default(), + Some(&table), + GroupBy::Day { + utc_offset_seconds: 0, + }, + GroupBy::Model, + &calendar, + ) + .unwrap() + .summaries + }; + let price_before = priced(br#"{"p":{"models":{"a":{"cost":{"input":1,"output":2}}}}}"#); + // Shadow the detail table on the reader only. Changing a price for a model + // absent from this day must still allow the warm read to complete. + f.store + .connection + .execute_batch("CREATE TEMP VIEW calls AS SELECT 1 AS blocked") + .unwrap(); + assert_eq!(priced(br#"{"p":{"models":{"a":{"cost":{"input":1,"output":2}},"unused":{"cost":{"input":3,"output":4}}}}}"#), price_before); +} + +#[test] +fn overview_reuses_only_days_with_identical_calendar_bounds() { + use crate::stats::{CallSelector, GroupBy, GroupKey, OverviewQuery}; + const DAY: i64 = 86_400_000; + let mut f = Fixture::new("changed-zone"); + let file = f.file("calls"); + let time = DAY - 5 * 3_600_000 - 40 * 60_000; + append( + &file, + &(session_line("s", "/work", 0) + &call_line("boundary", time, "m", 100, 20)), + ); + f.sync(&[file]); + let filter = CallFilter { + agents: vec![AGENT.into()], + ..CallFilter::default() + }; + for (offset, expected) in [ + (0, "1970-01-01"), + (20_700, "1970-01-02"), + (19_800, "1970-01-01"), + ] { + let query = OverviewQuery { + today_ms: 4 * DAY - i64::from(offset) * 1000, + initial_offset: offset, + offsets: vec![], + }; + let answer = f + .store + .usage_overview( + &filter, + &CallSelector::default(), + None, + GroupBy::Day { + utc_offset_seconds: offset, + }, + GroupBy::Agent, + &query, + ) + .unwrap(); + assert_eq!(answer.series.len(), 1); + assert_eq!( + answer.series[0].key, + GroupKey::Day { + date: expected.into() + } + ); + assert_eq!(answer.summaries[0].calls, 1); + } +} diff --git a/rust/fixtures/ai/agent-usage-overview-v1.json b/rust/fixtures/ai/agent-usage-overview-v1.json new file mode 100644 index 00000000..219a9f42 --- /dev/null +++ b/rust/fixtures/ai/agent-usage-overview-v1.json @@ -0,0 +1,22 @@ +{ + "callStartMs": 1793593800000, + "query": { + "groupBy": "day", + "splitBy": "model", + "detail": true, + "sinceMs": 1793332800000, + "untilMs": 1793682000000, + "utcOffsetSeconds": -18000, + "overview": { + "todayMs": 1796101200000, + "initialOffset": -14400, + "offsets": [ + { + "atMs": 1793512800000, + "seconds": -18000 + } + ] + } + }, + "date": "2026-11-01" +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 6c36cd6b..c52728c4 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4226,6 +4226,21 @@ Lithe list, search and sum them without the CLI running: `firstToken {calls, averageMs}`, the mean wait for the first token over its successful calls that report one. Each is absent when no call of the group qualifies. Without `detail` neither is present. + - The desktop may request an overview in one read. With `groupBy: "day"` + or `"hour"`, `splitBy` and `detail: true`, pass + `overview: {todayMs, initialOffset, offsets?: [{atMs, seconds}]}`. + `todayMs` is today's local midnight in Unix milliseconds. Offsets are + seconds east of UTC (strictly between −86400 and 86400). Changes have + strictly increasing UTC instants, at most 4096. Supply the offset in effect + before the first change and every change covering the requested days. + The answer has `summaries` (the overall group), `groups` (by `splitBy`), + `series` (time buckets split by that same dimension), and `rateLimits`. + All three arrays respect the same readable agents, filters and database + snapshot. Empty arrays denote no matches. Hour alignment and exact + median rules are unchanged. This mode omits the separate speed ranking. + Invalid overview grouping or calendar values refuse with + `agentSessions.invalidGroup`. Earlier Core versions reject `overview`. + This host command is separate from the plugin SDK method `agents/usage`. - All of this was added within `agents` 0. An older Core refuses `splitBy`, the filters and `detail` as unknown fields and the new group names as `agentSessions.invalidGroup`. diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 939baf08..b1289abb 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -61,7 +61,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-38 | 受管网络 | 部分完成 | `network/request`:可取消、有界 HTTP(S) | 下载文件、身份验证会话 | [工作流](../guides/plugin-workflows.md) | | API-40 | 工作区 authority | 部分完成 | [工作区上下文](../contract/v1/README.md#workspace-contexts-and-capability-discovery)带 `local` 或 `remote`,远程的另带远端主机的 `platform`(`os`、`arch`);`workspace/getHostPaths` 单独给出根目录在远端主机上的路径;文件和编辑器方法对远程上下文明确返回 `plugin.host.authorityUnsupported`;远程专用的失败码 `remoteDisconnected`、`platformUnavailable` | 远程执行(进程、语言服务器、调试器在远端主机上运行)、贡献的运行位置 `placement` | [插件后端](domains/backend.md)、[远程工作区](../guides/plugin-backend-remote-workspaces.md) | | API-41 | 激活事件与启动预算 | 部分完成 | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation)、`onCommand`、后台两路并发启动、`initialize` 超时、有界通知队列 | 按工作区内容匹配激活、全局冷启动预算 | [插件后端](domains/backend.md) | -| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),Core 替换文件前先备份,`agentProviders.restore` 由用户恢复原样 | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | +| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计。宿主可用 `agentSessions.stats` 一次读取用量总计、分组和时间序列;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),Core 替换文件前先备份,`agentProviders.restore` 由用户恢复原样 | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | ### 计划中的 API @@ -284,7 +284,7 @@ Status meanings: | API-38 | Managed network | Partial | `network/request`: bounded HTTP(S) with cancellation | File downloads and authentication sessions | [Workflows](../guides/plugin-workflows.md) | | API-40 | Workspace authority | Partial | [Workspace contexts](../contract/v1/README.md#workspace-contexts-and-capability-discovery) carry `local` or `remote`, and a remote one also the remote host's `platform` (`os`, `arch`); `workspace/getHostPaths` gives the roots' paths on the remote host on its own; file and editor methods refuse a remote context with `plugin.host.authorityUnsupported`; the remote failure codes `remoteDisconnected` and `platformUnavailable` | Remote execution (processes, language servers, and debuggers running on the remote host), the `placement` of contributions | [Plugin backend](domains/backend.md), [Remote workspaces](../guides/plugin-backend-remote-workspaces.md) | | API-41 | Activation events and startup budget | Partial | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation), `onCommand`, two concurrent background starts, `initialize` timeout, bounded notification queues | Activation by workspace content, a global cold-start budget | [Plugin backend](domains/backend.md) | -| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before replacing it, and `agentProviders.restore` puts it back on the user's request | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | +| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them. The host can read totals, groups and a time series in one `agentSessions.stats` overview; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before replacing it, and `agentProviders.restore` puts it back on the user's request | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | ### Planned APIs diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index c2f2f5b0..c863c930 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,6 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [桌面需求 #2594](https://github.com/1lck/Lithe-IDEA/issues/2594)(待提交) | — | API-45 | `agents` 0 内的补充 | 宿主 `agentSessions.stats` 增加可选 `overview`,在同一快照中返回总计、分组、按日或小时的序列。插件的 `agents/usage` 和四语 SDK 接口沿用原状。 | | [#249](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/249)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 在 #248 的 `configuration.providers` 上补充密钥写入、Lithe 保存的供应商列表和备份恢复。`providers` 新增可选 `listKeptBy`(`cli` / `lithe`,默认 `cli`)。密钥只写不读:`agentProviders.apply` 的 `addProvider`/`updateProvider` 可带 `key`(1–1024 字节,无控制字符和换行,否则 `agentProviders.invalidKey`),`updateProvider` 可带 `clearKey`(不能与 `key` 同时给);Core 只在内存里把它交给插件的 `edit`,不写日志、不进错误信息,快照的供应商只回答 `keySet`。`listKeptBy` 为 `lithe` 时(CLI 配置只能放一个自定义端点),Core 在资源库目录的 `saved-providers.json` 保存用户的供应商列表(不含密钥),插件用已有的 `lithe/host/credentials/*` 存密钥;修改带 `active` 与 `setProvider` 的 `provider`,供应商可带 `model`;快照的供应商增加 `saved`、`origin`、`model`,每个 Agent 增加 `listKeptBy`;Core 先存列表再调插件,失败时恢复列表。`apply` 替换文件前先备份到资源库目录的 `backups/`(自上次恢复以来第一次修改前的原样,加最近 20 份历史;可能含密钥,只在本机、仅所有者可读,不发给插件、不经接口回答),快照增加 `backup {savedAtMs, modifiedSince}`。新增宿主命令 `agentProviders.restore {agent, discardLaterChanges?}`(只接受用户发起)。新增错误码 `agentProviders.invalidKey`、`endpointExists`、`activeProvider`、`backupFailed`、`noBackup`、`changedSinceApply`、`restoreFailed`(见契约 [Models and providers](../contract/v1/README.md#models-and-providers)),日志事件 `agent.providers.restore_applied`、`restore_failed`。旧 Core 把 `listKeptBy`、`key`、`clearKey` 当未知字段拒绝,不认识 `agentProviders.restore`。没有新增插件可调用的宿主方法、通知或能力版本。 | | [#248](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/248)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | Agent 配置新增可选 `configuration.providers {read, edit?, operations?}`:插件函数 `read` 回答模型与模型供应商快照(格式 `litheAgentProviders`),`edit` 在暂存副本上应用一项修改(格式 `litheAgentProvidersEdit`),Core 应用后重新读取确认。`operations` 从 `addProvider`、`updateProvider`、`removeProvider`、`setProviderEnabled`、`setModel`、`setProvider`、`setProfile` 中声明,未声明的操作以 `agentProviders.unsupportedOperation` 拒绝。Core 执行隐私规则:环境变量和密钥只回答名称,地址去掉 userinfo、查询和片段,名称、数量和长度设上限;插件不得读取凭据文件和钥匙串;设置里的端点环境变量(BASE_URL 一类)作为供应商的 `baseUrl` 回答,其他环境变量只给名称。新增宿主命令 `agentProviders.read`、`agentProviders.apply`,错误码 `agentProviders.*`(见契约 [Models and providers](../contract/v1/README.md#models-and-providers)),日志事件 `agent.providers.read_finished`、`read_failed`、`change_applied`、`change_failed`。宿主命令 `agentLibrary.read` 新增可选 `query`、`agent`、`presence`、`sort`,回答在有筛选时增加 `matches`,新错误码 `agentLibrary.invalidFilter`;不带参数时行为不变。声明 `providers` 时配置 `read` 可省略,权限沿用 `agents.configuration`。旧 Core 把 `providers` 当未知字段拒绝清单,把新筛选参数当未知字段拒绝。同时修正 Agent 日志里耗时字段名,使 `duration_ms` 不再被丢弃。样例见 `fixtures/agents/agents.plugin.json` 和 `fixtures/manifest/invalid-manifests.json`。没有新增插件可调用的宿主方法、通知或能力版本。 | | [#246](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/246)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | `toolCall` 事件新增可选 `command`:`execute` 调用实际运行的命令行(1 字节到 1 MiB),此时 `title` 写这条命令要做什么(例如 CLI 给的描述),宿主把标题作为步骤标题、命令放进命令卡片,没有 `command` 时只用标题。`didStart` 新增 `toolCommands: true`,后端只在看到它时才发送 `command`;旧 Core 的 `toolCall` 严格解码,收到 `command` 会拒绝整批报告。会话来源 `read` 函数新增可选请求参数 `toolCommands`,`agentSessions.page` 随 `toolCalls` 一起发送,只有这时 `tool` 消息才可带 `command`,否则以 `agentSessions.invalidRead` 拒绝。四语 SDK 的 `AgentSessionStart` 新增 `toolCommands`(Rust `tool_commands`、Go `ToolCommands`、Java `toolCommands()`、Node `toolCommands`);记录读取仍是普通 JSON 函数,无类型变化。没有新增宿主方法、错误码或能力版本。样例见 `fixtures/agents/native-session.json` 与 `fixtures/agents/record-read.json`。 | From e4f4bf0f96d5ca533f14fd67ce26b511bc40f623 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Wed, 2 Dec 2026 15:56:37 +0800 Subject: [PATCH 2/4] docs(agents): link the overview contract to its pull request --- shared/plugins/reference/protocol-changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index c863c930..8f3f47b7 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| [桌面需求 #2594](https://github.com/1lck/Lithe-IDEA/issues/2594)(待提交) | — | API-45 | `agents` 0 内的补充 | 宿主 `agentSessions.stats` 增加可选 `overview`,在同一快照中返回总计、分组、按日或小时的序列。插件的 `agents/usage` 和四语 SDK 接口沿用原状。 | +| [#251](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/251)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 内的补充 | 宿主 `agentSessions.stats` 增加可选 `overview`,在同一快照中返回总计、分组、按日或小时的序列。插件的 `agents/usage` 和四语 SDK 接口沿用原状。 | | [#249](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/249)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 在 #248 的 `configuration.providers` 上补充密钥写入、Lithe 保存的供应商列表和备份恢复。`providers` 新增可选 `listKeptBy`(`cli` / `lithe`,默认 `cli`)。密钥只写不读:`agentProviders.apply` 的 `addProvider`/`updateProvider` 可带 `key`(1–1024 字节,无控制字符和换行,否则 `agentProviders.invalidKey`),`updateProvider` 可带 `clearKey`(不能与 `key` 同时给);Core 只在内存里把它交给插件的 `edit`,不写日志、不进错误信息,快照的供应商只回答 `keySet`。`listKeptBy` 为 `lithe` 时(CLI 配置只能放一个自定义端点),Core 在资源库目录的 `saved-providers.json` 保存用户的供应商列表(不含密钥),插件用已有的 `lithe/host/credentials/*` 存密钥;修改带 `active` 与 `setProvider` 的 `provider`,供应商可带 `model`;快照的供应商增加 `saved`、`origin`、`model`,每个 Agent 增加 `listKeptBy`;Core 先存列表再调插件,失败时恢复列表。`apply` 替换文件前先备份到资源库目录的 `backups/`(自上次恢复以来第一次修改前的原样,加最近 20 份历史;可能含密钥,只在本机、仅所有者可读,不发给插件、不经接口回答),快照增加 `backup {savedAtMs, modifiedSince}`。新增宿主命令 `agentProviders.restore {agent, discardLaterChanges?}`(只接受用户发起)。新增错误码 `agentProviders.invalidKey`、`endpointExists`、`activeProvider`、`backupFailed`、`noBackup`、`changedSinceApply`、`restoreFailed`(见契约 [Models and providers](../contract/v1/README.md#models-and-providers)),日志事件 `agent.providers.restore_applied`、`restore_failed`。旧 Core 把 `listKeptBy`、`key`、`clearKey` 当未知字段拒绝,不认识 `agentProviders.restore`。没有新增插件可调用的宿主方法、通知或能力版本。 | | [#248](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/248)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | Agent 配置新增可选 `configuration.providers {read, edit?, operations?}`:插件函数 `read` 回答模型与模型供应商快照(格式 `litheAgentProviders`),`edit` 在暂存副本上应用一项修改(格式 `litheAgentProvidersEdit`),Core 应用后重新读取确认。`operations` 从 `addProvider`、`updateProvider`、`removeProvider`、`setProviderEnabled`、`setModel`、`setProvider`、`setProfile` 中声明,未声明的操作以 `agentProviders.unsupportedOperation` 拒绝。Core 执行隐私规则:环境变量和密钥只回答名称,地址去掉 userinfo、查询和片段,名称、数量和长度设上限;插件不得读取凭据文件和钥匙串;设置里的端点环境变量(BASE_URL 一类)作为供应商的 `baseUrl` 回答,其他环境变量只给名称。新增宿主命令 `agentProviders.read`、`agentProviders.apply`,错误码 `agentProviders.*`(见契约 [Models and providers](../contract/v1/README.md#models-and-providers)),日志事件 `agent.providers.read_finished`、`read_failed`、`change_applied`、`change_failed`。宿主命令 `agentLibrary.read` 新增可选 `query`、`agent`、`presence`、`sort`,回答在有筛选时增加 `matches`,新错误码 `agentLibrary.invalidFilter`;不带参数时行为不变。声明 `providers` 时配置 `read` 可省略,权限沿用 `agents.configuration`。旧 Core 把 `providers` 当未知字段拒绝清单,把新筛选参数当未知字段拒绝。同时修正 Agent 日志里耗时字段名,使 `duration_ms` 不再被丢弃。样例见 `fixtures/agents/agents.plugin.json` 和 `fixtures/manifest/invalid-manifests.json`。没有新增插件可调用的宿主方法、通知或能力版本。 | | [#246](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/246)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | `toolCall` 事件新增可选 `command`:`execute` 调用实际运行的命令行(1 字节到 1 MiB),此时 `title` 写这条命令要做什么(例如 CLI 给的描述),宿主把标题作为步骤标题、命令放进命令卡片,没有 `command` 时只用标题。`didStart` 新增 `toolCommands: true`,后端只在看到它时才发送 `command`;旧 Core 的 `toolCall` 严格解码,收到 `command` 会拒绝整批报告。会话来源 `read` 函数新增可选请求参数 `toolCommands`,`agentSessions.page` 随 `toolCalls` 一起发送,只有这时 `tool` 消息才可带 `command`,否则以 `agentSessions.invalidRead` 拒绝。四语 SDK 的 `AgentSessionStart` 新增 `toolCommands`(Rust `tool_commands`、Go `ToolCommands`、Java `toolCommands()`、Node `toolCommands`);记录读取仍是普通 JSON 函数,无类型变化。没有新增宿主方法、错误码或能力版本。样例见 `fixtures/agents/native-session.json` 与 `fixtures/agents/record-read.json`。 | From 0c390b3cd38b2936f8326ecf9fb98fa3d899a030 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Thu, 3 Dec 2026 10:58:49 +0800 Subject: [PATCH 3/4] Recover exact usage overviews when daily cache data is unavailable --- rust/crates/agent-runtime/src/records.rs | 44 ++- rust/crates/agent-runtime/src/tests.rs | 32 ++ rust/crates/agent-sessions/src/stats.rs | 4 +- .../agent-sessions/src/stats/overview.rs | 317 +++++++++++++----- rust/crates/agent-sessions/src/tests/store.rs | 85 ++++- .../diagnostics/src/catalog_generated.rs | 12 + rust/logging/events/agent.json | 15 + shared/plugins/contract/v1/README.md | 16 +- .../plugins/reference/protocol-changelog.md | 2 +- 9 files changed, 420 insertions(+), 107 deletions(-) diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index 9d6af7e5..4ff0cf55 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -1025,16 +1025,34 @@ impl Records { )?; let readable = allowed_agents(runtime, request.agents); if let Some(calendar) = request.overview { - let split = split_by - .filter(|_| { - request.detail - && calendar.valid() - && matches!(group_by, GroupBy::Day { .. } | GroupBy::Hour { .. }) - }) - .ok_or_else(|| { - refusal(ErrorCode::InvalidRequest, "agentSessions.invalidGroup", - "An overview needs a day or hour series, a split, detail and a valid calendar.") - })?; + let split = split_by.ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidSplit", + "An overview requires splitBy.", + ) + })?; + if !matches!(group_by, GroupBy::Day { .. } | GroupBy::Hour { .. }) { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidOverviewGroup", + "An overview requires day or hour grouping.", + )); + } + if !request.detail { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidOverviewDetail", + "An overview requires detail.", + )); + } + if !calendar.valid() { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidCalendar", + "Supply valid offsets and chronologically ordered changes for the overview.", + )); + } let result = if let Some(agents) = readable { let reader = self.lock_reader(); let store = reader.as_ref().ok_or_else(not_configured)?; @@ -1055,6 +1073,12 @@ impl Records { } else { Overview::default() }; + if let Some(reason) = result.cache_warning { + log( + "agent.records.usage_cache_failed", + [("reason", json!(reason))], + ); + } return Ok( json!({"summaries": result.summaries, "groups": result.groups, "series": result.series, "rateLimits": self.rate_limit_entries(runtime)}), diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 48963906..5334a77b 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -3356,6 +3356,38 @@ fn overview_matches_the_shared_calendar_and_legacy_totals() { assert_eq!(result["series"][0]["speed"], total["summaries"][0]["speed"]); assert_eq!(result["rateLimits"], total["rateLimits"]); } + for (field, value, expected) in [ + ("splitBy", Value::Null, "agentSessions.invalidSplit"), + ( + "detail", + json!(false), + "agentSessions.invalidOverviewDetail", + ), + ( + "groupBy", + json!("all"), + "agentSessions.invalidOverviewGroup", + ), + ( + "overview", + json!({"todayMs":0,"initialOffset":-86400}), + "agentSessions.invalidCalendar", + ), + ( + "overview", + json!({"todayMs":0,"initialOffset":0,"offsets":vec![json!({"atMs":0,"seconds":0});4097]}), + "agentSessions.invalidCalendar", + ), + ( + "overview", + json!({"todayMs":0,"initialOffset":0,"offsets":[{"atMs":1,"seconds":1},{"atMs":1,"seconds":2}]}), + "agentSessions.invalidCalendar", + ), + ] { + let mut invalid = query.clone(); + invalid[field] = value; + assert_eq!(harness.refused("agentSessions.stats", invalid), expected); + } let mut denied = query.clone(); denied["agents"] = json!([]); let result = harness.run("agentSessions.stats", denied); diff --git a/rust/crates/agent-sessions/src/stats.rs b/rust/crates/agent-sessions/src/stats.rs index 53c71bdf..b573022b 100644 --- a/rust/crates/agent-sessions/src/stats.rs +++ b/rust/crates/agent-sessions/src/stats.rs @@ -195,7 +195,8 @@ pub struct FirstTokenSummary { pub average_ms: f64, } -/// Statistics of one group of calls. +/// Statistics of one group of calls. Its serialized form is also used by the daily cache; +/// incompatible field changes require bumping [`crate::SCHEMA_VERSION`]. #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Summary { @@ -245,6 +246,7 @@ pub struct Summarizer<'a> { groups: BTreeMap<(GroupKey, Option), Accumulator>, } +/// Persisted daily counts. Bump [`crate::SCHEMA_VERSION`] for incompatible field changes. #[derive(Debug, Clone, Serialize, Deserialize)] struct Accumulator { summary: Summary, diff --git a/rust/crates/agent-sessions/src/stats/overview.rs b/rust/crates/agent-sessions/src/stats/overview.rs index d1e66de9..44526c9f 100644 --- a/rust/crates/agent-sessions/src/stats/overview.rs +++ b/rust/crates/agent-sessions/src/stats/overview.rs @@ -34,7 +34,7 @@ pub struct OverviewQuery { impl OverviewQuery { /// Checks bounds before using the supplied calendar in date arithmetic. pub fn valid(&self) -> bool { - let valid_offset = |v: i32| (-86400..86400).contains(&v); + let valid_offset = |v: i32| (-86399..=86399).contains(&v); self.offsets.len() <= 4096 && valid_offset(self.initial_offset) && self.offsets.iter().all(|o| valid_offset(o.seconds)) @@ -94,6 +94,9 @@ pub struct Overview { pub groups: Vec, /// Sparse hour or local day buckets, split by that dimension. pub series: Vec, + /// Cache fallback reason for the runtime log; never included in the command response. + #[serde(skip)] + pub cache_warning: Option, } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] @@ -143,6 +146,8 @@ impl CellKey { } } +const SPEEDS_PER_BLOCK: usize = 32; + /// Bounds let the median read just blocks that can contain a middle value. #[derive(Clone, Serialize, Deserialize)] struct Block { @@ -165,8 +170,27 @@ enum Samples { Fresh(Rc<[u8]>), } +// Only invalid cached bytes trigger an exact retry. SQLite read and cancellation errors propagate. +enum ReadFailure { + Query(CoreError), + Damaged(i64), +} + +impl From for ReadFailure { + fn from(error: CoreError) -> Self { + Self::Query(error) + } +} + impl Samples { - fn read(&self, store: &SessionStore, block: &Block) -> Result, CoreError> { + fn invalid(&self) -> ReadFailure { + match self { + Self::Stored(id) => ReadFailure::Damaged(*id), + Self::Fresh(_) => ReadFailure::Query(cache_error()), + } + } + + fn read(&self, store: &SessionStore, block: &Block) -> Result, ReadFailure> { let size = block.count * 8; match self { Self::Stored(id) => { @@ -223,12 +247,14 @@ impl Projection { blocks.extend(cell.blocks.iter().map(|b| (b.clone(), samples.clone()))); } - fn finish(self, store: &SessionStore) -> Result, CoreError> { + fn finish(self, store: &SessionStore) -> Result, ReadFailure> { self.groups .into_values() .map(|Group { mut counts, blocks }| { if !blocks.is_empty() { - let n: usize = blocks.iter().map(|(b, _)| b.count).sum(); + let n = blocks.iter().try_fold(0usize, |n, (block, source)| { + n.checked_add(block.count).ok_or_else(|| source.invalid()) + })?; counts.summary.speed = Some(SpeedSummary { calls: n as u64, median_tokens_per_second: block_median(store, &blocks, n)?, @@ -245,7 +271,16 @@ fn block_median( store: &SessionStore, blocks: &[(Block, Samples)], n: usize, -) -> Result { +) -> Result { + let invalid = || { + blocks + .iter() + .find_map(|(_, source)| match source { + Samples::Stored(id) => Some(ReadFailure::Damaged(*id)), + Samples::Fresh(_) => None, + }) + .unwrap_or_else(|| ReadFailure::Query(cache_error())) + }; let bound = |upper: bool, rank: usize| { let mut ends: Vec<_> = blocks .iter() @@ -255,14 +290,15 @@ fn block_median( let mut remaining = rank; for (value, count) in ends { if remaining < count { - return value; + return Ok(value); } remaining -= count; } - unreachable!("bounds cover every sample") + Err(invalid()) }; - let low = bound(false, (n - 1) / 2); - let high = bound(true, n / 2); + let last = n.checked_sub(1).ok_or_else(invalid)?; + let low = bound(false, last / 2)?; + let high = bound(true, n / 2)?; if low == high { return Ok(low); } @@ -274,11 +310,19 @@ fn block_median( below += block.count; } else if block.low <= high { let bytes = source.read(store, block)?; - if bytes.len() != block.count * 8 { - return Err(cache_error()); + // Metadata for a stored block was checked against the blob length before use. + // Verify the values we actually read before trusting their ranks. + let values = bytes.as_chunks::<8>().0; + if values.first().map(|v| f64::from_le_bytes(*v)) != Some(block.low) + || values.last().map(|v| f64::from_le_bytes(*v)) != Some(block.high) + { + return Err(source.invalid()); } - for value in bytes.as_chunks::<8>().0 { + for value in values { let speed = f64::from_le_bytes(*value); + if !(block.low..=block.high).contains(&speed) { + return Err(source.invalid()); + } if speed < low { below += 1; } else if speed <= high { @@ -288,7 +332,12 @@ fn block_median( } } middle.sort_unstable_by(f64::total_cmp); - Ok((middle[(n - 1) / 2 - below] + middle[n / 2 - below]) / 2.0) + let at = |rank: usize| { + rank.checked_sub(below) + .and_then(|i| middle.get(i)) + .ok_or_else(invalid) + }; + Ok((at(last / 2)? + at(n / 2)?) / 2.0) } fn db_error(e: rusqlite::Error) -> CoreError { @@ -307,7 +356,7 @@ fn pack(groups: BTreeMap) -> (Vec, Vec) { let mut speeds = std::mem::take(&mut counts.speeds); speeds.sort_unstable_by(f64::total_cmp); let mut blocks = Vec::new(); - for part in speeds.chunks(32) { + for part in speeds.chunks(SPEEDS_PER_BLOCK) { blocks.push(Block { low: part[0], high: part[part.len() - 1], @@ -350,34 +399,44 @@ impl Period<'_> { serde_json::to_vec(&used).map_err(|_| cache_error()) } - fn prices_match(&self, saved: &[u8]) -> Result { + fn prices_match(&self, saved: &[u8]) -> bool { let Some(table) = self.prices else { - return Ok(saved == b"null"); + return saved == b"null"; }; type ModelPrice = (String, Option, Option); - let used: Option> = - serde_json::from_slice(saved).map_err(|_| cache_error())?; - Ok(used.is_some_and(|rows| { - rows.iter().all(|(model, provider, price)| { - table.lookup(provider.as_deref(), model) == price.as_ref() - }) - })) + let Ok(Some(rows)) = serde_json::from_slice::>>(saved) else { + return false; + }; + + rows.iter().all(|(model, provider, price)| { + table.lookup(provider.as_deref(), model) == price.as_ref() + }) } - fn visit_days( + fn visit_days>( &self, store: &SessionStore, - mut visit: impl FnMut(&str, i64, i64, String, bool) -> Result<(), CoreError>, - ) -> Result<(), CoreError> { + mut visit: impl FnMut(&str, i64, i64, String, bool) -> Result<(), E>, + ) -> Result<(), E> { let mut next = store.connection.prepare_cached( "SELECT started_at_ms FROM selected_calls WHERE agent = ?1 AND started_at_ms >= ?2 AND started_at_ms <= ?3 ORDER BY started_at_ms LIMIT 1" ).map_err(db_error)?; - for agent in self - .filter - .agents - .iter() - .collect::>() - { + let all_agents; + let agents = if self.filter.agents.is_empty() { + let mut query = store + .connection + .prepare_cached("SELECT DISTINCT agent FROM selected_calls") + .map_err(db_error)?; + all_agents = query + .query_map([], |row| row.get::<_, String>(0)) + .map_err(db_error)? + .collect::>>() + .map_err(db_error)?; + &all_agents + } else { + &self.filter.agents + }; + for agent in agents.iter().collect::>() { let mut from = self.filter.since_ms.unwrap_or(i64::MIN); let last = match self.filter.until_ms { Some(ms) => match ms.checked_sub(1) { @@ -410,13 +469,15 @@ impl Period<'_> { Ok(()) } - fn warm(&self, store: &SessionStore) -> Result<(), CoreError> { - self.visit_days(store, |agent, start, end, _, complete| { - if complete { - self.warm_day(store, agent, start, end)?; + fn warm(&self, store: &SessionStore) -> Result, CoreError> { + let mut warning = None; + self.visit_days::(store, |agent, start, end, _, complete| { + if complete && warning.is_none() { + warning = self.warm_day(store, agent, start, end, false)?; } Ok(()) - }) + })?; + Ok(warning) } fn warm_day( @@ -425,20 +486,19 @@ impl Period<'_> { agent: &str, start: i64, end: i64, - ) -> Result<(), CoreError> { + repair: bool, + ) -> Result, CoreError> { let tx = store.connection.unchecked_transaction().map_err(db_error)?; let saved: Option> = tx .query_row( - "SELECT prices FROM usage_days WHERE agent=?1 AND start_ms=?2 AND end_ms=?3", + "SELECT CAST(prices AS BLOB) FROM usage_days WHERE agent=?1 AND start_ms=?2 AND end_ms=?3", params![agent, start, end], |row| row.get(0), ) .optional() .map_err(db_error)?; - if let Some(saved) = saved { - if self.prices_match(&saved)? { - return Ok(()); - } + if !repair && saved.is_some_and(|saved| self.prices_match(&saved)) { + return Ok(None); } let filter = CallFilter { agents: vec![agent.to_owned()], @@ -457,31 +517,39 @@ impl Period<'_> { // A sync can remove the last copy between discovering a day and opening // its snapshot. In particular, never recreate a forgotten agent's cache row. if cells.is_empty() { - return Ok(()); + return Ok(None); } let (cells, bytes) = pack(cells); let data = serde_json::to_vec(&cells).map_err(|_| cache_error())?; // Build under a read snapshot. If a sync has taken the writer or changed // that snapshot, skip publishing. The final read still has its exact path. - let publish = tx.execute( - "DELETE FROM usage_days WHERE agent=?1 AND start_ms < ?3 AND end_ms > ?2", - params![agent, start, end], - ); - if publish - .as_ref() - .is_err_and(|e| e.sqlite_error_code() == Some(rusqlite::ErrorCode::DatabaseBusy)) - { - return Ok(()); + let prices = self.day_prices(&cells)?; + let publish = || -> rusqlite::Result<()> { + tx.execute( + "DELETE FROM usage_days WHERE agent=?1 AND start_ms < ?3 AND end_ms > ?2", + params![agent, start, end], + )?; + tx.execute( + "INSERT INTO usage_days(agent,start_ms,end_ms,prices,counts,samples) + VALUES(?1,?2,?3,?4,?5,?6)", + params![agent, start, end, prices, data, bytes], + )?; + tx.commit() + }; + if let Err(error) = publish() { + cancellation::check()?; + if error.sqlite_error_code() == Some(rusqlite::ErrorCode::OperationInterrupted) { + return Err(db_error(error)); + } + // Aggregate publication diagnostics at the request boundary without logging SQL or paths. + return Ok(Some( + error + .sqlite_error_code() + .map_or_else(|| "writeFailed".into(), |code| format!("{code:?}")), + )); } - publish.map_err(db_error)?; - tx.execute( - "INSERT INTO usage_days(agent,start_ms,end_ms,prices,counts,samples) - VALUES(?1,?2,?3,?4,?5,?6)", - params![agent, start, end, self.day_prices(&cells)?, data, bytes], - ) - .map_err(db_error)?; - tx.commit().map_err(db_error) + Ok(None) } } @@ -517,10 +585,97 @@ impl SessionStore { let reusable = matches!(series, GroupBy::Day { .. }) && selector.words.is_empty() && filter.session_id.is_none(); - if reusable { - period.warm(self)?; - } + let mut warning = if reusable { period.warm(self)? } else { None }; let snapshot = self.connection.unchecked_transaction().map_err(db_error)?; + let mut repair: Option<(String, i64, i64)> = None; + let mut answer = match period.read(self, selector, series, split, reusable) { + Ok(answer) => answer, + Err(ReadFailure::Query(error)) => return Err(error), + Err(ReadFailure::Damaged(id)) => { + repair = Some( + snapshot + .query_row( + "SELECT agent,start_ms,end_ms FROM usage_days WHERE id=?1", + [id], + |row| row.try_into(), + ) + .map_err(db_error)?, + ); + // Reuse the same snapshot so indexing cannot change an answer halfway through. + match period.read(self, selector, series, split, false) { + Ok(answer) => answer, + Err(ReadFailure::Query(error)) => return Err(error), + Err(ReadFailure::Damaged(_)) => return Err(cache_error()), + } + } + }; + snapshot.commit().map_err(db_error)?; + if let Some((agent, start, end)) = repair { + warning = period + .warm_day(self, &agent, start, end, true)? + .or_else(|| Some("invalidData".into())); + } + answer.cache_warning = warning; + Ok(answer) + } +} + +impl Period<'_> { + fn cached_day( + &self, + store: &SessionStore, + agent: &str, + start: i64, + end: i64, + ) -> Result, Samples)>, ReadFailure> { + let cached: Option<(i64, Vec, Vec, usize)> = store + .connection + .query_row( + "SELECT id, CAST(counts AS BLOB), CAST(prices AS BLOB), length(samples) + FROM usage_days WHERE agent=?1 AND start_ms=?2 AND end_ms=?3", + params![agent, start, end], + |row| row.try_into(), + ) + .optional() + .map_err(db_error)?; + let Some((id, bytes, rates, length)) = cached else { + return Ok(None); + }; + if !self.prices_match(&rates) { + return Ok(None); + } + let cells: Vec = + serde_json::from_slice(&bytes).map_err(|_| ReadFailure::Damaged(id))?; + // Blocks are packed consecutively across cells, with at most one chunk of speeds each. + // Check their layout without reading the blob; warm queries fetch only median candidates. + let mut offset = 0usize; + for block in cells.iter().flat_map(|cell| &cell.blocks) { + if !(1..=SPEEDS_PER_BLOCK).contains(&block.count) + || block.low > block.high + || block.offset != offset + { + return Err(ReadFailure::Damaged(id)); + } + offset = offset + .checked_add(block.count * 8) + .ok_or(ReadFailure::Damaged(id))?; + } + if cells.is_empty() || offset != length { + return Err(ReadFailure::Damaged(id)); + } + Ok(Some((cells, Samples::Stored(id)))) + } + + fn read( + &self, + store: &SessionStore, + selector: &CallSelector, + series: GroupBy, + split: GroupBy, + reusable: bool, + ) -> Result { + let filter = self.filter; + let prices = self.prices; let (mut totals, mut groups, mut chart) = ( Projection::default(), Projection::default(), @@ -532,22 +687,14 @@ impl SessionStore { groups.add(group.clone(), None, cell, samples); chart.add(time.clone(), Some(group), cell, samples); }; - period.visit_days(self, |agent, start, end, date, complete| { + self.visit_days::(store, |agent, start, end, date, complete| { let day = GroupKey::Day { date }; if reusable && complete { - let cached = snapshot.query_row( - "SELECT id, counts, prices FROM usage_days WHERE agent=?1 AND start_ms=?2 AND end_ms=?3", - params![agent, start, end], - |row| Ok((row.get::<_, i64>(0)?, row.get::<_, Vec>(1)?, row.get::<_,Vec>(2)?)), - ).optional().map_err(db_error)?; - if let Some((id, bytes, rates)) = cached { - if period.prices_match(&rates)? { - let cells: Vec = serde_json::from_slice(&bytes).map_err(|_| cache_error())?; + if let Some((cells, source)) = self.cached_day(store, agent, start, end)? { for cell in cells.iter().filter(|cell| cell.key.keeps(selector)) { - consume(cell, &day, &Samples::Stored(id)); + consume(cell, &day, &source); } return Ok(()); - } } } @@ -558,13 +705,16 @@ impl SessionStore { part.until_ms = Some(end.min(filter.until_ms.unwrap_or(i64::MAX))); } let mut buckets = BTreeMap::>::new(); - self.for_each_call(&part, |entry| { + store.for_each_call(&part, |entry| { if selector.keeps(&entry) { let time = match series { GroupBy::Hour { .. } => group_key(series, &entry), _ => day.clone(), }; - buckets.entry(time).or_default().entry(CellKey::of(&entry)) + buckets + .entry(time) + .or_default() + .entry(CellKey::of(&entry)) .or_insert_with(|| Accumulator::new(GroupKey::All, None, prices)) .add(&entry.call, prices, true); } @@ -579,12 +729,11 @@ impl SessionStore { } Ok(()) })?; - let answer = Overview { - summaries: totals.finish(self)?, - groups: groups.finish(self)?, - series: chart.finish(self)?, - }; - snapshot.commit().map_err(db_error)?; - Ok(answer) + Ok(Overview { + summaries: totals.finish(store)?, + groups: groups.finish(store)?, + series: chart.finish(store)?, + cache_warning: None, + }) } } diff --git a/rust/crates/agent-sessions/src/tests/store.rs b/rust/crates/agent-sessions/src/tests/store.rs index 0c12af9d..31e3caba 100644 --- a/rust/crates/agent-sessions/src/tests/store.rs +++ b/rust/crates/agent-sessions/src/tests/store.rs @@ -1151,8 +1151,18 @@ fn daily_overview_tracks_replaced_and_forgotten_copies() { Ok(()) }) .expect("scan"); - assert_eq!(overview.summaries, total.finish()); - assert_eq!(overview.series, series.finish()); + let compare = |mut actual: Vec, + expected: Vec| { + for (row, reference) in actual.iter_mut().zip(&expected) { + if let (Some(cost), Some(want)) = (&mut row.cost, reference.cost) { + assert!((cost.usd - want.usd).abs() <= 1e-12 * want.usd.abs().max(1.0)); + cost.usd = want.usd; + } + } + assert_eq!(actual, expected); + }; + compare(overview.summaries, total.finish()); + compare(overview.series, series.finish()); }; check(&f.store, None, CallSelector::default()); f.store = SessionStore::open(&f.dir.path().join("cache")).expect("reopen"); @@ -1253,6 +1263,53 @@ fn warm_overview_answers_from_saved_days_and_busy_writer_keeps_precise_results() }; assert_eq!(read(&partial), expected(&partial)); + let saved_day = || { + f.store + .connection + .query_row( + "SELECT hex(counts) || ':' || hex(samples) FROM usage_days WHERE start_ms=0", + [], + |row| row.get::<_, String>(0), + ) + .unwrap() + }; + let valid_day = saved_day(); + for damage in [ + "counts=x'ff'", + "counts=CAST(json_set(CAST(counts AS TEXT),'$[0].blocks[0].count',0) AS BLOB)", + "counts=CAST(json_set(CAST(counts AS TEXT),'$[0].blocks[0].low',1e12) AS BLOB)", + "samples=zeroblob(0)", + "samples=zeroblob(length(samples))", + ] { + f.store + .connection + .execute( + &format!("UPDATE usage_days SET {damage} WHERE start_ms=0"), + [], + ) + .unwrap(); + assert_eq!(read(&filter), total, "{damage}"); + assert_eq!(saved_day(), valid_day, "repair after {damage}"); + } + f.store + .connection + .execute_batch("UPDATE usage_days SET prices=x'ff'; PRAGMA query_only=ON;") + .unwrap(); + assert_eq!(read(&filter), total); + f.store + .connection + .execute_batch( + "PRAGMA query_only=OFF; DELETE FROM usage_days; + CREATE TEMP TRIGGER refuse_publication BEFORE INSERT ON usage_days + BEGIN SELECT RAISE(ABORT,'fixture'); END;", + ) + .unwrap(); + assert_eq!(read(&filter), total); + f.store + .connection + .execute_batch("DROP TRIGGER refuse_publication") + .unwrap(); + let priced = |rates: &[u8]| { let table = crate::pricing::PriceTable::from_models_dev(rates).unwrap(); f.store @@ -1270,6 +1327,14 @@ fn warm_overview_answers_from_saved_days_and_busy_writer_keeps_precise_results() .summaries }; let price_before = priced(br#"{"p":{"models":{"a":{"cost":{"input":1,"output":2}}}}}"#); + f.store + .connection + .execute_batch("UPDATE usage_days SET prices=x'ff'") + .unwrap(); + assert_eq!( + priced(br#"{"p":{"models":{"a":{"cost":{"input":1,"output":2}}}}}"#), + price_before + ); // Shadow the detail table on the reader only. Changing a price for a model // absent from this day must still allow the warm read to complete. f.store @@ -1291,10 +1356,14 @@ fn overview_reuses_only_days_with_identical_calendar_bounds() { &(session_line("s", "/work", 0) + &call_line("boundary", time, "m", 100, 20)), ); f.sync(&[file]); - let filter = CallFilter { - agents: vec![AGENT.into()], - ..CallFilter::default() - }; + // The store-level empty filter includes every agent, just like for_each_call. + let second = f.file("other"); + append( + &second, + &(session_line("second", "/work", 0) + &call_line("other", time, "m", 1, 2)), + ); + sync_as(&mut f.store, OTHER_AGENT, &[second]); + let filter = CallFilter::default(); for (offset, expected) in [ (0, "1970-01-01"), (20_700, "1970-01-02"), @@ -1318,13 +1387,13 @@ fn overview_reuses_only_days_with_identical_calendar_bounds() { &query, ) .unwrap(); - assert_eq!(answer.series.len(), 1); + assert_eq!(answer.series.len(), 2); assert_eq!( answer.series[0].key, GroupKey::Day { date: expected.into() } ); - assert_eq!(answer.summaries[0].calls, 1); + assert_eq!(answer.summaries[0].calls, 2); } } diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 8837d28b..a651fd81 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -269,6 +269,18 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "agent.records.usage_cache_failed", + channel: "agent", + level: LogLevel::Warn, + message: "The usage overview fell back to exact records", + fields: &[ + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Invalid cached data or SQLite result category when publishing daily usage", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "agent.report.rejected", channel: "agent", diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index 58776c48..69f5929f 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -181,6 +181,21 @@ "rate": 60, "owner": "lithe-core" }, + { + "id": "agent.records.usage_cache_failed", + "channel": "agent", + "level": "warn", + "message": "The usage overview fell back to exact records", + "fields": { + "reason": { + "type": "token", + "required": true, + "description": "Invalid cached data or SQLite result category when publishing daily usage" + } + }, + "rate": 60, + "owner": "lithe-core" + }, { "id": "agent.records.removed", "channel": "agent", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 755fab7d..38ecf104 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4240,8 +4240,16 @@ Lithe list, search and sum them without the CLI running: All three arrays respect the same readable agents, filters and database snapshot. Empty arrays denote no matches. Hour alignment and exact median rules are unchanged. This mode omits the separate speed ranking. - Invalid overview grouping or calendar values refuse with - `agentSessions.invalidGroup`. Earlier Core versions reject `overview`. + Day buckets follow the overview calendar, including offset transitions. + For hour buckets, `utcOffsetSeconds` supplies the alignment unless an explicit + `hourAnchorMs` is given. Equivalent cost totals may differ in their last + floating-point digits when daily subtotals are added together. + A missing or unknown split refuses with `agentSessions.invalidSplit`. + An otherwise valid grouping other than day or hour refuses with + `agentSessions.invalidOverviewGroup`, and missing or false detail with + `agentSessions.invalidOverviewDetail`. Invalid calendar offsets, ordering or + too many changes refuse with `agentSessions.invalidCalendar`. + Earlier Core versions reject `overview`. This host command is separate from the plugin SDK method `agents/usage`. - All of this was added within `agents` 0. An older Core refuses `splitBy`, the filters and `detail` as unknown fields and the new group names as @@ -4382,7 +4390,9 @@ in `rate-limits.json` in the cache directory. under the agent's roots), `agentSessions.discoveryFailed`, `agentSessions.backendUnavailable`, `agentSessions.scanFailed`, `agentSessions.invalidScan`, `agentSessions.readFailed`, -`agentSessions.invalidRead` and `agentSessions.invalidGroup`. +`agentSessions.invalidRead`, `agentSessions.invalidGroup`, `agentSessions.invalidSplit`, +`agentSessions.invalidOverviewGroup`, `agentSessions.invalidOverviewDetail` and +`agentSessions.invalidCalendar`. ### Agent configuration diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index d856494f..19b30923 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| [#251](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/251)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 内的补充 | 宿主 `agentSessions.stats` 增加可选 `overview`,在同一快照中返回总计、分组、按日或小时的序列。插件的 `agents/usage` 和四语 SDK 接口沿用原状。 | +| [#251](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/251)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 内的补充 | 宿主 `agentSessions.stats` 增加可选 `overview`,在同一快照中返回总计、分组、按日或小时的序列。按日分桶使用概览日历。缺少分组维度沿用 `agentSessions.invalidSplit`;概览的分组、明细开关和日历错误分别返回 `agentSessions.invalidOverviewGroup`、`agentSessions.invalidOverviewDetail`、`agentSessions.invalidCalendar`。插件的 `agents/usage` 和四语 SDK 接口沿用原状。 | | [#249](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/249)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 在 #248 的 `configuration.providers` 上补充密钥写入、Lithe 保存的供应商列表和备份恢复。`providers` 新增可选 `listKeptBy`(`cli` / `lithe`,默认 `cli`)。密钥只写不读:`agentProviders.apply` 的 `addProvider`/`updateProvider` 可带 `key`(1–1024 字节,无控制字符和换行,否则 `agentProviders.invalidKey`),`updateProvider` 可带 `clearKey`(不能与 `key` 同时给);Core 只在内存里把它交给插件的 `edit`,不写日志、不进错误信息,快照的供应商只回答 `keySet`。`listKeptBy` 为 `lithe` 时(CLI 配置只能放一个自定义端点),Core 在资源库目录的 `saved-providers.json` 保存用户的供应商列表(不含密钥),插件用已有的 `lithe/host/credentials/*` 存密钥;修改带 `active` 与 `setProvider` 的 `provider`,供应商可带 `model`;快照的供应商增加 `saved`、`origin`、`model`,每个 Agent 增加 `listKeptBy`;Core 先存列表再调插件,失败时恢复列表。`apply` 替换文件前先备份到资源库目录的 `backups/`(自上次恢复以来第一次修改前的原样,加最近 20 份历史;可能含密钥,只在本机、仅所有者可读,不发给插件、不经接口回答),快照增加 `backup {savedAtMs, modifiedSince}`。新增宿主命令 `agentProviders.restore {agent, discardLaterChanges?}`(只接受用户发起)。新增错误码 `agentProviders.invalidKey`、`endpointExists`、`activeProvider`、`backupFailed`、`noBackup`、`changedSinceApply`、`restoreFailed`(见契约 [Models and providers](../contract/v1/README.md#models-and-providers)),日志事件 `agent.providers.restore_applied`、`restore_failed`。旧 Core 把 `listKeptBy`、`key`、`clearKey` 当未知字段拒绝,不认识 `agentProviders.restore`。没有新增插件可调用的宿主方法、通知或能力版本。 | | [#248](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/248)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | Agent 配置新增可选 `configuration.providers {read, edit?, operations?}`:插件函数 `read` 回答模型与模型供应商快照(格式 `litheAgentProviders`),`edit` 在暂存副本上应用一项修改(格式 `litheAgentProvidersEdit`),Core 应用后重新读取确认。`operations` 从 `addProvider`、`updateProvider`、`removeProvider`、`setProviderEnabled`、`setModel`、`setProvider`、`setProfile` 中声明,未声明的操作以 `agentProviders.unsupportedOperation` 拒绝。Core 执行隐私规则:环境变量和密钥只回答名称,地址去掉 userinfo、查询和片段,名称、数量和长度设上限;插件不得读取凭据文件和钥匙串;设置里的端点环境变量(BASE_URL 一类)作为供应商的 `baseUrl` 回答,其他环境变量只给名称。新增宿主命令 `agentProviders.read`、`agentProviders.apply`,错误码 `agentProviders.*`(见契约 [Models and providers](../contract/v1/README.md#models-and-providers)),日志事件 `agent.providers.read_finished`、`read_failed`、`change_applied`、`change_failed`。宿主命令 `agentLibrary.read` 新增可选 `query`、`agent`、`presence`、`sort`,回答在有筛选时增加 `matches`,新错误码 `agentLibrary.invalidFilter`;不带参数时行为不变。声明 `providers` 时配置 `read` 可省略,权限沿用 `agents.configuration`。旧 Core 把 `providers` 当未知字段拒绝清单,把新筛选参数当未知字段拒绝。同时修正 Agent 日志里耗时字段名,使 `duration_ms` 不再被丢弃。样例见 `fixtures/agents/agents.plugin.json` 和 `fixtures/manifest/invalid-manifests.json`。没有新增插件可调用的宿主方法、通知或能力版本。 | | [#247](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/247)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 宿主命令说明 | 补充 `agents.prompt` 重试的发送模式、原始提示词校验和拒绝原因。 | From 5a88ef8115e3ea409235b6db248b4428489ed762 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Thu, 3 Dec 2026 15:14:15 +0800 Subject: [PATCH 4/4] Reserve the session writer before reading records for deletion --- rust/crates/agent-sessions/src/store.rs | 82 ++++++++++++++++++++++--- 1 file changed, 74 insertions(+), 8 deletions(-) diff --git a/rust/crates/agent-sessions/src/store.rs b/rust/crates/agent-sessions/src/store.rs index 3e39c6b7..5b299894 100644 --- a/rust/crates/agent-sessions/src/store.rs +++ b/rust/crates/agent-sessions/src/store.rs @@ -583,17 +583,22 @@ impl SessionStore { report.files_listed = listed.len() as u64; let known = self.known_files(agent)?; - let transaction = self.transaction()?; - for (id, path) in &known { - if listed - .binary_search_by(|(text, _)| (*text).cmp(path.as_str())) - .is_err() - { + let mut missing = known + .iter() + .filter(|(_, path)| { + listed + .binary_search_by(|(text, _)| (*text).cmp(path.as_str())) + .is_err() + }) + .peekable(); + if missing.peek().is_some() { + let transaction = self.transaction()?; + for (id, _) in missing { forget_file(&transaction, *id)?; report.files_removed += 1; } + commit(transaction)?; } - commit(transaction)?; for (text, path) in listed { cancellation::check()?; @@ -611,6 +616,9 @@ impl SessionStore { pub fn remove_agent(&mut self, agent: &str) -> Result { check_caller_id("agent", agent)?; let known = self.known_files(agent)?; + if known.is_empty() { + return Ok(0); + } let transaction = self.transaction()?; for (id, _) in &known { forget_file(&transaction, *id)?; @@ -1161,8 +1169,10 @@ impl SessionStore { } fn transaction(&mut self) -> Result, CoreError> { + // Reserve the writer before reading span IDs. A concurrent overview can still + // read its snapshot, but cannot publish a usage day underneath a record deletion. self.connection - .transaction() + .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate) .map_err(|error| sql_error("Could not write the agent session cache", error)) } } @@ -1718,3 +1728,59 @@ pub(crate) fn sql_error(message: &str, error: rusqlite::Error) -> CoreError { }; CoreError::new(ErrorCode::Unknown, message).with_details(details) } + +#[cfg(test)] +mod transaction_tests { + use super::*; + use crate::stats::{CallSelector, GroupBy, OverviewQuery}; + use crate::tests::{append, call_line, session_line, LinesParser, TempDir}; + + #[test] + fn forgetting_records_takes_priority_over_publishing_a_usage_day() { + let dir = TempDir::new("forget-while-publishing"); + let mut writer = SessionStore::open(dir.path()).unwrap(); + for agent in ["keep", "forget"] { + let path = dir.path().join(agent); + append( + &path, + &(session_line("s", "/work", 0) + &call_line("c", 1, "m", 2, 3)), + ); + writer + .sync_agent(agent, &[path], &mut LinesParser::default()) + .unwrap(); + } + let reader = SessionStore::open(dir.path()).unwrap(); + reader.connection.busy_timeout(Duration::ZERO).unwrap(); + let tx = writer.transaction().unwrap(); + let id = tx + .query_row("SELECT id FROM files WHERE agent='forget'", [], |row| { + row.get(0) + }) + .unwrap(); + // Publish after the deletion has read its snapshot, before its first write. + let answer = reader + .usage_overview( + &CallFilter { + agents: vec!["keep".into()], + ..Default::default() + }, + &CallSelector::default(), + None, + GroupBy::Day { + utc_offset_seconds: 0, + }, + GroupBy::Agent, + &OverviewQuery { + today_ms: 86_400_000, + initial_offset: 0, + offsets: vec![], + }, + ) + .unwrap(); + assert_eq!(answer.summaries[0].calls, 1); + forget_file(&tx, id).expect("the overview must yield to record deletion"); + commit(tx).unwrap(); + assert!(writer.known_files("forget").unwrap().is_empty()); + assert!(answer.cache_warning.is_some()); + } +}