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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,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` |
Expand Down
67 changes: 65 additions & 2 deletions rust/crates/agent-runtime/src/records.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -987,6 +987,8 @@ impl Records {
search: Option<String>,
#[serde(default)]
detail: bool,
#[serde(default)]
overview: Option<OverviewQuery>,
}
let request: StatsRequest = crate::decode(payload)?;
let group_by = parse_group_by(
Expand Down Expand Up @@ -1021,7 +1023,68 @@ 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 {
Comment thread
WhiteZeek marked this conversation as resolved.
Resolved
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)?;
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()
};
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)}),
);
}
let (summaries, speeds) = match readable {
None => (json!([]), json!([])),
Some(agents) => {
let filter = CallFilter {
Expand Down
72 changes: 72 additions & 0 deletions rust/crates/agent-runtime/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3323,3 +3323,75 @@ 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"]);
}
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);
for key in ["summaries", "groups", "series"] {
assert_eq!(result[key], json!([]));
}
}
8 changes: 6 additions & 2 deletions rust/crates/agent-sessions/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
129 changes: 129 additions & 0 deletions rust/crates/agent-sessions/benches/daily_overview.rs
Original file line number Diff line number Diff line change
@@ -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<T>(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);
}
}
7 changes: 4 additions & 3 deletions rust/crates/agent-sessions/src/pricing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down
Loading
Loading