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, secrets: &[String]) -> String {
let serialized = serde_json::to_string(args).expect("Value is always serializable");
let redacted = crate::util::redact_secrets(&serialized, secrets);
let scrubbed = crate::util::scrub_credentials(&redacted);
crate::util::truncate_bytes(&scrubbed, 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_order: Option<String>,
}
pub(crate) struct LlmOperationCtx {
pub operation_id: String,
pub call: LlmCallMeta,
}
impl LlmCallMeta {
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_order: request.provider_order.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,
})
}
}
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
.provider_order
.as_deref()
.unwrap_or("default")
.to_string(),
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
.provider_order
.clone()
.unwrap_or_else(|| "default".to_string()),
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_closes_both_leak_paths() {
let key = "sk-1234567890abcdef";
let args = serde_json::json!({"action": "setup_web_search", "key": key});
let recorded = recorded_arguments(&args, &[key.to_string()]);
assert!(
!recorded.contains(key),
"the caller's key must be gone: {recorded}"
);
let token = "123456:AAHsecret";
let args = serde_json::json!({"action": "setup_telegram_bot", "token": token});
let recorded = recorded_arguments(&args, &[token.to_string()]);
assert!(
!recorded.contains(&token[..4]),
"not even the prefix of a handed-over secret may survive: {recorded}"
);
}
#[tokio::test]
async fn flush_batch_round_trip() {
let (store, _tmp) = crate::open_test_store!(crate::logs::LogStore, "log");
let records = vec![
crate::ToolCallRecord {
tool_name: "read".to_string(),
arguments: r#"{"path":"src/main.rs"}"#.to_string(),
duration_ms: 42,
success: true,
error_message: None,
},
crate::ToolCallRecord {
tool_name: "create_ticket".to_string(),
arguments: r#"{"title":"Fix bug"}"#.to_string(),
duration_ms: 150,
success: true,
error_message: None,
},
crate::ToolCallRecord {
tool_name: "write".to_string(),
arguments: r#"{"path":"src/lib.rs"}"#.to_string(),
duration_ms: 0,
success: false,
error_message: Some("Error executing write: permission denied".to_string()),
},
];
store
.flush_batch(
"test-agent",
"Engineer",
"my-workspace",
CallSource::Agent,
&crate::db::now(),
&records,
)
.await
.expect("flush_batch");
let rows = store
.conn
.query(
"SELECT tool_name, success, error_message FROM tool_calls ORDER BY tool_name",
crate::db::params![],
)
.await
.expect("query tool_calls");
let rows: Vec<(String, i64, Option<String>)> = rows
.into_iter()
.map(|row| {
(
row.get::<String>(0).expect("tool_name"),
row.get::<i64>(1).expect("success"),
row.get::<Option<String>>(2).expect("error_message"),
)
})
.collect();
assert_eq!(
rows,
vec![
("create_ticket".to_string(), 1, None),
("read".to_string(), 1, None),
(
"write".to_string(),
0,
Some("Error executing write: permission denied".to_string())
),
],
"every record lands as its own row, the failed one carrying its error text"
);
}
}