use crate::db::{self};
use anyhow::Result;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum CallSource {
Agent,
CommandLine,
}
impl CallSource {
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::Agent => "agent",
Self::CommandLine => "cli",
}
}
}
const MAX_STATS_ARG_LENGTH: usize = 500;
pub(crate) fn recorded_arguments(args: &serde_json::Value) -> String {
let serialized = serde_json::to_string(args).expect("Value is always serializable");
crate::util::truncate_bytes(&serialized, MAX_STATS_ARG_LENGTH).to_string()
}
impl crate::logs::LogStore {
pub(crate) async fn flush_batch(
&self,
agent_id: &str,
role: &str,
workspace: &str,
source: CallSource,
recorded_at: &str,
stats: &[crate::ToolCallRecord],
) -> Result<()> {
if stats.is_empty() {
return Ok(());
}
let tx = self.conn.begin_tx().await?;
for record in stats {
tx.execute(
"INSERT INTO tool_calls \
(agent_id, role, source, tool_name, arguments, duration_ms, success, error_message, workspace, recorded_at) \
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
db::params![
agent_id,
role,
source.as_str(),
record.tool_name.clone(),
record.arguments.clone(),
record.duration_ms,
i64::from(record.success),
record.error_message.clone(),
workspace.to_string(),
recorded_at,
],
)
.await?;
}
tx.commit().await?;
Ok(())
}
pub(crate) async fn record_llm_request(&self, rec: &LlmRequestRecord) -> Result<()> {
self.conn
.execute(
"INSERT INTO llm_requests \
(recorded_at, purpose, agent_id, role, workspace, ticket_id, model, routing, \
input_tokens, output_tokens, cached_input_tokens, cache_miss_tokens, \
cost, cost_details, upstream_provider, system_fingerprint, \
duration_ms, retry_attempts, finish_reason, failure_class, success) \
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, \
?17, ?18, ?19, ?20, ?21)",
db::params![
rec.recorded_at.clone(),
rec.purpose,
rec.agent_id.clone(),
rec.role.clone(),
rec.workspace.clone(),
rec.ticket_id.clone(),
rec.model.clone(),
rec.routing.clone(),
rec.input_tokens.map(i64::try_from).transpose()?,
rec.output_tokens.map(i64::try_from).transpose()?,
rec.cached_input_tokens.map(i64::try_from).transpose()?,
rec.cache_miss_tokens.map(i64::try_from).transpose()?,
rec.cost,
rec.cost_details.clone(),
rec.upstream_provider.clone(),
rec.system_fingerprint.clone(),
i64::try_from(rec.duration_ms)?,
i64::from(rec.retry_attempts),
rec.finish_reason.clone(),
rec.failure_class.clone(),
i64::from(rec.success),
],
)
.await?;
Ok(())
}
pub(crate) async fn record_llm_failure_row(&self, rec: &LlmFailureRow) -> Result<()> {
self.conn
.execute(
"INSERT INTO llm_failures \
(operation_id, recorded_at, purpose, agent_id, role, workspace, ticket_id, \
model, routing, attempt, attempt_duration_ms, failure_class, finish_reason, \
retry_after_ms, error_chain) \
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
db::params![
rec.operation_id.clone(),
rec.recorded_at.clone(),
rec.purpose,
rec.agent_id.clone(),
rec.role.clone(),
rec.workspace.clone(),
rec.ticket_id.clone(),
rec.model.clone(),
rec.routing.clone(),
i64::from(rec.attempt),
rec.attempt_duration_ms.map(i64::try_from).transpose()?,
rec.failure_class.clone(),
rec.finish_reason.clone(),
rec.retry_after_ms.map(i64::try_from).transpose()?,
rec.error_chain.clone(),
],
)
.await?;
Ok(())
}
}
#[derive(Debug, Clone)]
pub(crate) struct LlmRequestRecord {
pub purpose: &'static str,
pub agent_id: String,
pub role: String,
pub workspace: String,
pub ticket_id: Option<String>,
pub model: String,
pub routing: String,
pub input_tokens: Option<u64>,
pub output_tokens: Option<u64>,
pub cached_input_tokens: Option<u64>,
pub cache_miss_tokens: Option<u64>,
pub cost: Option<f64>,
pub cost_details: Option<String>,
pub upstream_provider: Option<String>,
pub system_fingerprint: Option<String>,
pub duration_ms: u64,
pub retry_attempts: u32,
pub finish_reason: Option<String>,
pub failure_class: Option<String>,
pub success: bool,
pub recorded_at: String,
}
#[derive(Debug, Clone)]
pub(crate) struct LlmFailureRow {
pub operation_id: String,
pub purpose: &'static str,
pub agent_id: String,
pub role: String,
pub workspace: String,
pub ticket_id: Option<String>,
pub model: String,
pub routing: String,
pub attempt: u32,
pub attempt_duration_ms: Option<u64>,
pub failure_class: String,
pub finish_reason: Option<String>,
pub retry_after_ms: Option<u64>,
pub error_chain: String,
pub recorded_at: String,
}
pub(crate) struct LlmCallMeta {
pub meta: crate::ChatRequestMeta,
pub model: String,
pub provider: Option<String>,
}
pub(crate) struct LlmOperationCtx {
pub operation_id: String,
pub call: LlmCallMeta,
}
impl LlmCallMeta {
#[must_use]
fn routing(&self) -> String {
self.provider
.clone()
.unwrap_or_else(|| "default".to_string())
}
pub(crate) fn from_request(request: &crate::ChatRequest) -> Option<Self> {
let meta = request.meta.as_ref()?;
Some(Self {
meta: meta.clone(),
model: request.model.clone(),
provider: request.provider.clone(),
})
}
}
impl LlmOperationCtx {
#[must_use]
pub(crate) fn from_request(request: &crate::ChatRequest) -> Option<Self> {
let call = LlmCallMeta::from_request(request)?;
Some(Self {
operation_id: crate::generate_id(),
call,
})
}
pub(crate) fn set_provider(&mut self, provider: Option<String>) {
self.call.provider = provider;
}
}
fn llm_request_record_meta(
call: &LlmCallMeta,
duration_ms: u64,
attempts: u32,
response: Option<&crate::ChatResponse>,
finish_reason: Option<&str>,
failure_class: Option<&'static str>,
) -> LlmRequestRecord {
let usage = response.and_then(|r| r.usage.as_ref());
LlmRequestRecord {
purpose: call.meta.purpose,
agent_id: call.meta.agent_id.clone(),
role: call.meta.role.clone(),
workspace: call.meta.workspace.clone(),
ticket_id: call.meta.ticket_id.clone(),
model: call.model.clone(),
routing: call.routing(),
input_tokens: usage.and_then(|u| u.input_tokens),
output_tokens: usage.and_then(|u| u.output_tokens),
cached_input_tokens: usage.and_then(|u| u.cached_input_tokens),
cache_miss_tokens: usage.and_then(|u| u.cache_miss_tokens),
cost: usage.and_then(|u| u.cost),
cost_details: usage
.and_then(|u| u.cost_details.as_ref())
.map(serde_json::Value::to_string),
upstream_provider: response.and_then(|r| r.upstream_provider.clone()),
system_fingerprint: response.and_then(|r| r.system_fingerprint.clone()),
duration_ms,
retry_attempts: attempts,
finish_reason: finish_reason.map(str::to_string),
failure_class: failure_class.map(str::to_string),
success: failure_class.is_none(),
recorded_at: crate::db::now(),
}
}
fn record_llm_operation(
request: &crate::ChatRequest,
duration_ms: u64,
attempts: u32,
response: Option<&crate::ChatResponse>,
finish_reason: Option<&str>,
failure_class: Option<&'static str>,
) {
let Some(call) = LlmCallMeta::from_request(request) else {
return;
};
record_llm_operation_meta(
&call,
duration_ms,
attempts,
response,
finish_reason,
failure_class,
);
}
pub(crate) fn record_llm_operation_meta(
call: &LlmCallMeta,
duration_ms: u64,
attempts: u32,
response: Option<&crate::ChatResponse>,
finish_reason: Option<&str>,
failure_class: Option<&'static str>,
) {
crate::telemetry::enqueue(crate::telemetry::TelemetryRecord::LlmRequest(
llm_request_record_meta(
call,
duration_ms,
attempts,
response,
finish_reason,
failure_class,
),
));
}
struct LlmAttemptOutcome {
attempt: u32,
attempt_duration_ms: Option<u64>,
failure_class: String,
finish_reason: Option<String>,
retry_after_ms: Option<u64>,
error_chain: String,
}
fn llm_failure_row(
operation_id: &str,
call: &LlmCallMeta,
outcome: LlmAttemptOutcome,
) -> LlmFailureRow {
LlmFailureRow {
operation_id: operation_id.to_string(),
purpose: call.meta.purpose,
agent_id: call.meta.agent_id.clone(),
role: call.meta.role.clone(),
workspace: call.meta.workspace.clone(),
ticket_id: call.meta.ticket_id.clone(),
model: call.model.clone(),
routing: call.routing(),
attempt: outcome.attempt,
attempt_duration_ms: outcome.attempt_duration_ms,
failure_class: outcome.failure_class,
finish_reason: outcome.finish_reason,
retry_after_ms: outcome.retry_after_ms,
error_chain: outcome.error_chain,
recorded_at: crate::db::now(),
}
}
pub(crate) fn record_llm_attempt_failure(
ctx: &LlmOperationCtx,
attempt: u32,
rec: &crate::retry::RetryFailureRecord,
attempt_started: Option<std::time::Instant>,
) {
let outcome = LlmAttemptOutcome {
attempt,
attempt_duration_ms: elapsed_ms(attempt_started),
failure_class: rec.class.label().to_string(),
finish_reason: rec.finish_reason.clone(),
retry_after_ms: rec.retry_after_ms,
error_chain: rec.error_chain.clone(),
};
crate::telemetry::enqueue(crate::telemetry::TelemetryRecord::LlmFailure(
llm_failure_row(&ctx.operation_id, &ctx.call, outcome),
));
}
fn elapsed_ms(started: Option<std::time::Instant>) -> Option<u64> {
started.and_then(|t| u64::try_from(t.elapsed().as_millis()).ok())
}
#[expect(clippy::cast_possible_truncation)]
pub(crate) fn record_llm_success(
request: &crate::ChatRequest,
started: std::time::Instant,
attempt: u32,
response: &crate::ChatResponse,
) {
record_llm_operation(
request,
started.elapsed().as_millis() as u64,
attempt,
Some(response),
response.finish_reason.as_deref(),
None,
);
}
#[expect(clippy::cast_possible_truncation)]
pub(crate) fn record_llm_failure(
request: &crate::ChatRequest,
started: std::time::Instant,
exhausted: &crate::retry::RetryExhausted,
) {
record_llm_operation(
request,
started.elapsed().as_millis() as u64,
exhausted.failures.len() as u32,
None,
exhausted
.failures
.last()
.and_then(|r| r.finish_reason.as_deref()),
Some(exhausted.final_class.label()),
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn recorded_arguments_keeps_the_arguments_and_caps_them() {
let args = serde_json::json!({"action": "search", "query": "rust"});
assert_eq!(
recorded_arguments(&args),
serde_json::to_string(&args).expect("Value is always serializable")
);
let args = serde_json::json!({
"action": "search",
"query": "x".repeat(MAX_STATS_ARG_LENGTH * 2),
});
let recorded = recorded_arguments(&args);
assert_eq!(recorded.len(), MAX_STATS_ARG_LENGTH);
assert!(recorded.starts_with(r#"{"action":"search","query":"xxx"#));
}
}