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
147 changes: 135 additions & 12 deletions rust/crates/agent-runtime/src/records.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ use crate::catalog::{record_key, split_record_key, CatalogAgent};
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, GroupBy, SpeedRanker, Summarizer};
use lithe_agent_sessions::stats::{
call_speed, model_name, CallSelector, GroupBy, SpeedRanker, Summarizer,
};
use lithe_agent_sessions::{
discover, ByteRange, CallEntry, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionFilter,
SessionOrder, SessionParser, SessionSource, SessionStore, MAX_FILTER_DIRECTORIES,
Expand Down Expand Up @@ -887,9 +889,21 @@ impl Records {
until_ms: Option<i64>,
group_by: String,
#[serde(default)]
split_by: Option<String>,
#[serde(default)]
utc_offset_seconds: i32,
#[serde(default)]
hour_anchor_ms: Option<i64>,
#[serde(default)]
models: Vec<String>,
#[serde(default)]
providers: Vec<String>,
#[serde(default)]
failed: Option<bool>,
#[serde(default)]
search: Option<String>,
#[serde(default)]
detail: bool,
}
let request: StatsRequest = crate::decode(payload)?;
let group_by = parse_group_by(
Expand All @@ -902,9 +916,28 @@ impl Records {
refusal(
ErrorCode::InvalidRequest,
"agentSessions.invalidGroup",
"Group by hour, day, agent, model, session or cwd. Only hour accepts hourAnchorMs.",
"Group by hour, day, agent, model, provider, modelProvider, session, cwd or all. Only hour accepts hourAnchorMs.",
)
})?;
let split_by = request
.split_by
.as_deref()
.map(|name| {
parse_split_by(name).ok_or_else(|| {
refusal(
ErrorCode::InvalidRequest,
"agentSessions.invalidSplit",
"Split by agent, model, provider or modelProvider.",
)
})
})
.transpose()?;
let selector = call_selector(
request.models,
request.providers,
request.failed,
request.search.as_deref(),
)?;
let (summaries, speeds) = match allowed_agents(runtime, request.agents) {
None => (json!([]), json!([])),
Some(agents) => {
Expand All @@ -916,7 +949,14 @@ impl Records {
};
let reader = self.lock_reader();
let store = reader.as_ref().ok_or_else(not_configured)?;
self.summarize(store, &filter, group_by)?
self.summarize(
store,
&filter,
group_by,
split_by,
&selector,
request.detail,
)?
}
};
Ok(json!({
Expand Down Expand Up @@ -945,8 +985,14 @@ impl Records {
#[serde(default)]
model: Option<String>,
#[serde(default)]
models: Vec<String>,
#[serde(default)]
providers: Vec<String>,
#[serde(default)]
failed: Option<bool>,
#[serde(default)]
search: Option<String>,
#[serde(default)]
offset: usize,
limit: usize,
}
Expand All @@ -959,6 +1005,13 @@ impl Records {
"Ask for 1 to 500 calls at an offset of at most 50000.",
));
}
// `model` is the one-model form of `models`; both must hold.
let selector = call_selector(
request.models,
request.providers,
request.failed,
request.search.as_deref(),
)?;
let Some(agents) = allowed_agents(runtime, request.agents) else {
return Ok(json!({ "calls": [], "total": 0 }));
};
Expand All @@ -982,12 +1035,7 @@ impl Records {
.model
.as_deref()
.is_some_and(|model| model_name(call) != Some(model))
{
return Ok(());
}
if request
.failed
.is_some_and(|failed| call.error_category.is_some() != failed)
|| !selector.keeps(&entry)
{
return Ok(());
}
Expand All @@ -1009,18 +1057,32 @@ impl Records {
Ok(json!({ "calls": calls, "total": total }))
}

/// The summaries of the calls `filter` selects, grouped by `group_by`,
/// and the models ranked by median output speed over the same calls.
/// The summaries of the calls `filter` and `selector` keep, grouped by
/// `group_by` and split by `split_by`, with each group's median speed and
/// first-token average when `detailed`, and the models ranked by median
/// output speed over the same calls.
fn summarize(
&self,
store: &SessionStore,
filter: &CallFilter,
group_by: GroupBy,
split_by: Option<GroupBy>,
selector: &CallSelector,
detailed: bool,
) -> Result<(Value, Value), CoreError> {
let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner);
let mut summarizer = Summarizer::new(group_by, prices.as_ref());
if let Some(split_by) = split_by {
summarizer = summarizer.split_by(split_by);
}
if detailed {
summarizer = summarizer.detailed();
}
let mut speeds = SpeedRanker::default();
store.for_each_call(filter, |entry| {
if !selector.keeps(&entry) {
return Ok(());
}
summarizer.add(&entry);
speeds.add(&entry.call);
Ok(())
Expand Down Expand Up @@ -1105,7 +1167,15 @@ impl Records {
since_ms: Some(since_ms),
until_ms: Some(until_ms),
};
self.summarize(store, &filter, group_by).map_err(|_| {
self.summarize(
store,
&filter,
group_by,
None,
&CallSelector::default(),
false,
)
.map_err(|_| {
AgentHostFailure::new(codes::HOST_FAILED, "Could not sum the session records.")
})?
};
Expand Down Expand Up @@ -1338,10 +1408,63 @@ fn parse_group_by(
"model" => Some(GroupBy::Model),
"session" if host => Some(GroupBy::Session),
"cwd" if host => Some(GroupBy::Cwd),
"provider" if host => Some(GroupBy::Provider),
"modelProvider" if host => Some(GroupBy::ModelProvider),
"all" if host => Some(GroupBy::All),
_ => None,
}
}

/// What a statistics request can split each group by.
fn parse_split_by(name: &str) -> Option<GroupBy> {
match name {
"agent" => Some(GroupBy::Agent),
"model" => Some(GroupBy::Model),
"provider" => Some(GroupBy::Provider),
"modelProvider" => Some(GroupBy::ModelProvider),
_ => None,
}
}

/// Most models or providers a request may filter by, and the longest name or
/// search text.
const MAX_FILTER_NAMES: usize = 64;
const MAX_FILTER_TEXT_BYTES: usize = 256;

/// The selector of a statistics or calls request, or a refusal when a filter
/// is too long.
fn call_selector(
models: Vec<String>,
providers: Vec<String>,
failed: Option<bool>,
search: Option<&str>,
) -> Result<CallSelector, CoreError> {
let too_long = |names: &[String]| {
names.len() > MAX_FILTER_NAMES
|| names.iter().any(|name| name.len() > MAX_FILTER_TEXT_BYTES)
};
if too_long(&models)
|| too_long(&providers)
|| search.is_some_and(|text| text.len() > MAX_FILTER_TEXT_BYTES)
{
return Err(refusal(
ErrorCode::InvalidRequest,
"agentSessions.invalidFilter",
"Filter by at most 64 models and 64 providers, each name and the search text at most 256 bytes.",
));
}
let selector = CallSelector {
models,
providers,
failed,
words: Vec::new(),
};
Ok(match search {
Some(text) => selector.with_search(text),
None => selector,
})
}

/// A session source with its root resolved.
struct RootedSource {
root: PathBuf,
Expand Down
115 changes: 115 additions & 0 deletions rust/crates/agent-runtime/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1765,6 +1765,121 @@ fn hourly_stats_match_the_shared_desktop_fixture() {
);
}

#[test]
fn stats_split_filter_and_detail_the_calls() {
let harness = Harness::new("stats-split", ALL_GRANTS);
write_session_file(&harness, crate::now_ms());
harness.run(
"agentSessions.sync",
json!({ "pluginID": PLUGIN, "agentID": AGENT }),
);

// A day split by model carries the split key and, on request, the group's
// median speed and first-token average.
let detailed = harness.run(
"agentSessions.stats",
json!({ "groupBy": "day", "splitBy": "model", "detail": true }),
);
let summary = &detailed["summaries"][0];
assert_eq!(summary["calls"], 1, "{detailed}");
assert_eq!(
summary["split"],
json!({ "kind": "model", "model": "sample-model" }),
"{detailed}"
);
assert_eq!(
summary["speed"],
json!({ "calls": 1, "medianTokensPerSecond": 150.0, "lowerBound": false }),
"{detailed}"
);
assert_eq!(
summary["firstToken"],
json!({ "calls": 1, "averageMs": 500.0 }),
"{detailed}"
);
let plain = harness.run("agentSessions.stats", json!({ "groupBy": "day" }));
assert!(plain["summaries"][0].get("split").is_none(), "{plain}");
assert!(plain["summaries"][0].get("speed").is_none(), "{plain}");
assert!(plain["summaries"][0].get("firstToken").is_none(), "{plain}");

for (group, key) in [
("all", json!({ "kind": "all" })),
("provider", json!({ "kind": "provider" })),
(
"modelProvider",
json!({ "kind": "modelProvider", "model": "sample-model" }),
),
] {
let stats = harness.run("agentSessions.stats", json!({ "groupBy": group }));
assert_eq!(stats["summaries"][0]["key"], key, "{stats}");
}

// Filters narrow what is summed and what the request table lists.
for (filter, kept) in [
(json!({ "models": ["sample-model"] }), 1),
(json!({ "models": ["other-model"] }), 0),
(json!({ "providers": [""] }), 1),
(json!({ "providers": ["p1"] }), 0),
(json!({ "failed": false }), 1),
(json!({ "failed": true }), 0),
(json!({ "search": "SAMPLE" }), 1),
(json!({ "search": "sample nothing" }), 0),
(json!({ "search": "/work/project" }), 1),
] {
let mut stats_query = filter.clone();
stats_query["groupBy"] = json!("all");
let stats = harness.run("agentSessions.stats", stats_query);
let counted = stats["summaries"][0]["calls"].as_u64().unwrap_or(0);
assert_eq!(counted, kept, "stats {filter} {stats}");
let mut calls_query = filter.clone();
calls_query["limit"] = json!(10);
let calls = harness.run("agentSessions.calls", calls_query);
assert_eq!(calls["total"], kept, "calls {filter} {calls}");
}
let narrowed = harness.run(
"agentSessions.stats",
json!({ "groupBy": "model", "models": ["other-model"], "detail": true }),
);
assert_eq!(narrowed["summaries"], json!([]), "{narrowed}");
assert_eq!(narrowed["speeds"], json!([]), "{narrowed}");

for (query, code) in [
(
json!({ "groupBy": "day", "splitBy": "day" }),
"agentSessions.invalidSplit",
),
(
json!({ "groupBy": "day", "search": "x".repeat(257) }),
"agentSessions.invalidFilter",
),
(
json!({ "groupBy": "day", "models": vec!["m"; 65] }),
"agentSessions.invalidFilter",
),
] {
assert_eq!(harness.refused("agentSessions.stats", query.clone()), code);
}
assert_eq!(
harness.refused(
"agentSessions.calls",
json!({ "limit": 1, "providers": vec!["p"; 65] })
),
"agentSessions.invalidFilter"
);

// Plugins keep the grouping and the answer they had.
for group in ["provider", "modelProvider", "all"] {
let refusal = harness
.answer(AGENTS_USAGE, json!({ "groupBy": group }))
.expect_err("plugins cannot group by this");
assert_eq!(refusal.code, codes::HOST_INVALID_PARAMS);
}
let usage = harness
.answer(AGENTS_USAGE, json!({ "groupBy": "model" }))
.expect("usage");
assert!(usage["summaries"][0].get("speed").is_none(), "{usage}");
}

#[test]
fn rate_limits_survive_a_restart() {
let dir;
Expand Down
Loading
Loading