Files
crank/crates/crank-registry/src/postgres/observability.rs
T
bsodfather e93de7015a
CI / Rust Checks (pull_request) Failing after 1s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
feat(import): complete OpenAPI onboarding and verify delivery
2026-10-09 17:50:38 +03:00

953 lines
37 KiB
Rust

use super::*;
const PRESERVED_USAGE_WINDOW_DAYS: u16 = 90;
fn usage_outcome_group_case_sql(prefix: &str) -> String {
debug_assert!(matches!(prefix, "" | "l."));
format!(
"case
when {prefix}status = 'ok' then 'success'
when {prefix}execution_error_code in (
'upstream_auth_error',
'upstream_not_found',
'upstream_rate_limited',
'upstream_server_error',
'upstream_status_error',
'upstream_timeout',
'upstream_transport_error',
'upstream_request_too_large',
'upstream_response_too_large'
) then 'upstream'
when execution_error_code in (
'authorization_denied',
'auth_profile_not_found',
'secret_not_found',
'secret_invalid',
'input_schema_invalid',
'input_mapping_invalid',
'outbound_target_rejected',
'adapter_configuration_invalid',
'confirmation_required',
'confirmation_invalid',
'idempotency_in_progress',
'idempotency_conflict',
'idempotency_outcome_unknown'
) then 'client'
when execution_error_code in (
'prepared_request_invalid',
'output_mapping_invalid',
'output_schema_invalid'
) then 'schema'
when execution_error_code in (
'execution_overloaded',
'safety_store_unavailable',
'protocol_unsupported',
'execution_mode_unsupported',
'persistence_unavailable',
'runtime_internal'
) then 'crank'
else 'crank'
end"
)
}
fn invocation_history_loss_category(error: &RegistryError) -> InvocationHistoryLossCategory {
match error {
RegistryError::Storage(error)
if error
.as_database_error()
.and_then(|database_error| database_error.code())
.is_some_and(|code| code.starts_with("22") || code.starts_with("23")) =>
{
InvocationHistoryLossCategory::InvalidRecord
}
RegistryError::Storage(_) => InvocationHistoryLossCategory::Unavailable,
_ => InvocationHistoryLossCategory::InvalidRecord,
}
}
impl PostgresRegistry {
pub async fn delete_invocation_logs_before(
&self,
cutoff: OffsetDateTime,
) -> Result<InvocationRetentionOutcome, RegistryError> {
let usage_floor = OffsetDateTime::now_utc()
- time::Duration::days(i64::from(PRESERVED_USAGE_WINDOW_DAYS));
let effective_cutoff = cutoff.min(usage_floor);
let result = sqlx::query(
"delete from invocation_logs l
where l.created_at < $1::timestamptz
and not exists (
select 1 from onboarding_selections s
where s.invocation_log_id = l.id or s.test_log_id = l.id
)",
)
.bind(effective_cutoff)
.execute(&self.pool)
.await?;
let deleted_records = result.rows_affected();
Ok(InvocationRetentionOutcome {
status: if deleted_records == 0 {
InvocationRetentionStatus::Noop
} else {
InvocationRetentionStatus::Completed
},
deleted_records,
policy: InvocationRetentionPolicy {
requested_cutoff: cutoff,
effective_cutoff,
usage_preservation_floor: usage_floor,
preserved_usage_window_days: PRESERVED_USAGE_WINDOW_DAYS,
},
})
}
pub async fn create_invocation_log(
&self,
request: CreateInvocationLogRequest<'_>,
) -> InvocationHistoryWriteOutcome {
match self.try_create_invocation_log(request).await {
Ok(()) => InvocationHistoryWriteOutcome::Recorded,
Err(error) => InvocationHistoryWriteOutcome::Lost(InvocationHistoryLoss {
category: invocation_history_loss_category(&error),
}),
}
}
async fn try_create_invocation_log(
&self,
request: CreateInvocationLogRequest<'_>,
) -> Result<(), RegistryError> {
let request_id =
request
.log
.request_id
.as_deref()
.ok_or(RegistryError::InvalidCorrelationIdentity {
field: "request_id",
})?;
crank_core::RequestId::parse(request_id).map_err(|_| {
RegistryError::InvalidCorrelationIdentity {
field: "request_id",
}
})?;
let trace_id = request
.log
.trace_id
.as_deref()
.ok_or(RegistryError::InvalidCorrelationIdentity { field: "trace_id" })?;
crank_core::TraceId::parse(trace_id)
.map_err(|_| RegistryError::InvalidCorrelationIdentity { field: "trace_id" })?;
let operation_version =
request
.log
.operation_version
.ok_or(RegistryError::InvalidExecutionRecord {
field: "operation_version",
})?;
let _stage = request
.log
.execution_stage
.ok_or(RegistryError::InvalidExecutionRecord {
field: "execution_stage",
})?;
let _retryability =
request
.log
.retryability
.ok_or(RegistryError::InvalidExecutionRecord {
field: "retryability",
})?;
let _certainty =
request
.log
.outcome_certainty
.ok_or(RegistryError::InvalidExecutionRecord {
field: "outcome_certainty",
})?;
match request.log.status {
crank_core::InvocationStatus::Ok if request.log.execution_error_code.is_some() => {
return Err(RegistryError::InvalidExecutionRecord {
field: "execution_error_code",
});
}
crank_core::InvocationStatus::Error if request.log.execution_error_code.is_none() => {
return Err(RegistryError::InvalidExecutionRecord {
field: "execution_error_code",
});
}
_ => {}
}
let request_preview = crank_core::sanitize_invocation_preview(&request.log.request_preview);
let response_preview =
crank_core::sanitize_invocation_preview(&request.log.response_preview);
let operation_version =
i32::try_from(operation_version).map_err(|_| RegistryError::InvalidNumericValue {
field: "operation_version",
value: i64::MAX,
})?;
let mut should_anchor_onboarding = request.log.source
== crank_core::InvocationSource::AgentToolCall
&& request.log.status == crank_core::InvocationStatus::Ok
&& request.log.execution_stage == Some(crank_core::ExecutionStage::Runtime)
&& request.log.outcome_certainty == Some(crank_core::OutcomeCertainty::Certain)
&& request.log.execution_error_code.is_none()
&& request.log.agent_id.is_some()
&& request.log.platform_api_key_id.is_some();
let mut transaction = self.pool.begin().await?;
if should_anchor_onboarding {
sqlx::query("select id from workspaces where id = $1 for update")
.bind(request.log.workspace_id.as_str())
.fetch_one(&mut *transaction)
.await?;
// A durable import context governs terminal anchoring: a pending
// context suppresses the generic anchor entirely, and an explicit
// selection only anchors the exact selected Operation/version.
// Without an import context the existing generic anchoring stays.
if let Some((selected_operation_id, selected_operation_version)) =
super::onboarding_import::onboarding_import_selection_in_transaction(
&mut transaction,
&request.log.workspace_id,
)
.await?
{
should_anchor_onboarding = selected_operation_id.as_deref()
== Some(request.log.operation_id.as_str())
&& selected_operation_version == Some(operation_version);
}
}
sqlx::query(
"insert into invocation_logs (
id,
workspace_id,
agent_id,
platform_api_key_id,
operation_id,
operation_version,
source,
level,
status,
tool_name,
message,
request_id,
trace_id,
status_code,
duration_ms,
error_kind,
execution_stage,
execution_error_code,
retryability,
outcome_certainty,
request_preview_json,
response_preview_json,
created_at
) values (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23::timestamptz
)",
)
.bind(request.log.id.as_str())
.bind(request.log.workspace_id.as_str())
.bind(request.log.agent_id.as_ref().map(|value| value.as_str()))
.bind(
request
.log
.platform_api_key_id
.as_ref()
.map(|value| value.as_str()),
)
.bind(request.log.operation_id.as_str())
.bind(operation_version)
.bind(serialize_enum_text(&request.log.source, "source")?)
.bind(serialize_enum_text(&request.log.level, "level")?)
.bind(serialize_enum_text(&request.log.status, "status")?)
.bind(&request.log.tool_name)
.bind(&request.log.message)
.bind(&request.log.request_id)
.bind(&request.log.trace_id)
.bind(request.log.status_code.map(i32::from))
.bind(i64::try_from(request.log.duration_ms).map_err(|_| {
RegistryError::InvalidNumericValue {
field: "duration_ms",
value: i64::MAX,
}
})?)
.bind(&request.log.error_kind)
.bind(
request
.log
.execution_stage
.as_ref()
.map(|value| serialize_enum_text(value, "execution_stage"))
.transpose()?,
)
.bind(
request
.log
.execution_error_code
.as_ref()
.map(|value| serialize_enum_text(value, "execution_error_code"))
.transpose()?,
)
.bind(
request
.log
.retryability
.as_ref()
.map(|value| serialize_enum_text(value, "retryability"))
.transpose()?,
)
.bind(
request
.log
.outcome_certainty
.as_ref()
.map(|value| serialize_enum_text(value, "outcome_certainty"))
.transpose()?,
)
.bind(Json(request_preview))
.bind(Json(response_preview))
.bind(request.log.created_at)
.execute(&mut *transaction)
.await?;
if should_anchor_onboarding {
let agent_id =
request
.log
.agent_id
.as_ref()
.ok_or(RegistryError::InvalidExecutionRecord {
field: "onboarding.agent_id",
})?;
let key_id = request.log.platform_api_key_id.as_ref().ok_or(
RegistryError::InvalidExecutionRecord {
field: "onboarding.platform_api_key_id",
},
)?;
let anchored = sqlx::query(
"insert into onboarding_selections (
workspace_id, operation_id, operation_version, agent_id, catalog_revision,
platform_api_key_id, invocation_log_id, test_log_id, evidence_after, selected_at
)
select $1, $2, $3, a.id, pa.catalog_revision, k.id, $6,
(
select l.id from invocation_logs l
where l.workspace_id = $1 and l.operation_id = $2
and l.operation_version = $3 and l.source = 'admin_test_run'
and l.status = 'ok' and l.execution_stage = 'runtime'
and l.outcome_certainty = 'certain' and l.execution_error_code is null
and l.created_at >= coalesce(
(select s.evidence_after from onboarding_selections s
where s.workspace_id = $1),
'-infinity'::timestamptz
)
order by l.created_at desc, l.id desc limit 1
),
coalesce(
(select s.evidence_after from onboarding_selections s
where s.workspace_id = $1),
'-infinity'::timestamptz
),
$7
from agents a
join published_agents pa on pa.agent_id = a.id
join agent_operation_bindings b
on b.agent_id = pa.agent_id and b.agent_version = pa.version
and b.operation_id = $2 and b.operation_version = $3 and b.enabled
join published_operations po on po.operation_id = b.operation_id and po.version = b.operation_version
join operations o on o.id = po.operation_id and o.workspace_id = $1
and o.status = 'published' and o.current_draft_version = po.version
join platform_api_keys k on k.workspace_id = $1 and k.agent_id = a.id and k.id = $5
where a.workspace_id = $1 and a.id = $4 and a.status = 'published'
and k.key_kind = 'mcp_client' and k.status = 'active'
and (k.expires_at is null or k.expires_at > $7)
on conflict (workspace_id) do update
set operation_id = excluded.operation_id,
operation_version = excluded.operation_version,
agent_id = excluded.agent_id,
catalog_revision = excluded.catalog_revision,
platform_api_key_id = excluded.platform_api_key_id,
invocation_log_id = excluded.invocation_log_id,
test_log_id = excluded.test_log_id,
selected_at = excluded.selected_at
where onboarding_selections.operation_id is null
and excluded.selected_at >= onboarding_selections.evidence_after",
)
.bind(request.log.workspace_id.as_str())
.bind(request.log.operation_id.as_str())
.bind(operation_version)
.bind(agent_id.as_str())
.bind(key_id.as_str())
.bind(request.log.id.as_str())
.bind(request.log.created_at)
.execute(&mut *transaction)
.await?
.rows_affected()
> 0;
if anchored {
let projection = super::onboarding::get_onboarding_projection_in_transaction(
&mut transaction,
&request.log.workspace_id,
)
.await?;
let eligible =
super::product_event::get_product_event_by_idempotency_key_in_transaction(
&mut transaction,
&request.log.workspace_id,
"onboarding:eligible:v1",
)
.await?;
if let Some(eligible_since) = eligible
.filter(|_| projection.completed)
.and_then(|record| record.event.eligible_since)
{
let completed = crank_core::ProductEvent {
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
workspace_id: request.log.workspace_id.clone(),
kind: crank_core::ProductEventKind::OnboardingCompleted,
schema_version: crank_core::PRODUCT_EVENT_SCHEMA_VERSION,
milestone: None,
eligible: true,
eligible_since: Some(eligible_since),
idempotency_key: "onboarding:completed:v1".to_owned(),
occurred_at: request.log.created_at,
};
super::product_event::append_product_event_in_transaction(
&mut transaction,
&completed,
)
.await?;
}
}
// Record import funnel publication/activation at the authoritative
// call boundary (idempotent; no-op without a selected import).
super::onboarding_import::record_import_funnel_milestones_in_transaction(
&mut transaction,
&request.log.workspace_id,
request.log.created_at,
)
.await?;
}
transaction.commit().await?;
Ok(())
}
pub async fn list_invocation_logs(
&self,
query: ListInvocationLogsQuery<'_>,
) -> Result<Vec<InvocationLogRecord>, RegistryError> {
let outcome_group_case = usage_outcome_group_case_sql("l.");
let sql = format!(
"select
l.id,
l.workspace_id,
l.agent_id,
l.platform_api_key_id,
l.operation_id,
l.operation_version,
l.source,
l.level,
l.status,
l.tool_name,
l.message,
l.request_id,
l.trace_id,
l.status_code,
l.duration_ms,
l.error_kind,
l.execution_stage,
l.execution_error_code,
l.retryability,
l.outcome_certainty,
l.request_preview_json,
l.response_preview_json,
l.created_at as created_at,
o.name as operation_name,
o.display_name as operation_display_name,
a.slug as agent_slug,
a.display_name as agent_display_name
from invocation_logs l
join operations o on o.id = l.operation_id
left join agents a on a.id = l.agent_id
where l.workspace_id = $1
and ($2::text is null or l.level = $2)
and ($3::text is null or l.status = $3)
and ($4::text is null or l.source = $4)
and ($5::text is null or l.operation_id = $5)
and ($6::text is null or l.agent_id = $6)
and ($7::text is null or ({outcome_group_case}) = $7)
and ($8::timestamptz is null or l.created_at >= $8::timestamptz)
and ($9::timestamptz is null or l.created_at < $9::timestamptz)
and (
$10::timestamptz is null
or (l.created_at, l.id) < ($10::timestamptz, $11::text)
)
and (
$12::text is null
or l.tool_name ilike '%' || $12 || '%'
or l.message ilike '%' || $12 || '%'
or o.name ilike '%' || $12 || '%'
or o.display_name ilike '%' || $12 || '%'
)
order by l.created_at desc, l.id desc
limit $13"
);
let rows = sqlx::query(sqlx::AssertSqlSafe(sql))
.bind(query.workspace_id.as_str())
.bind(
query
.level
.as_ref()
.map(|value| serialize_enum_text(value, "level"))
.transpose()?,
)
.bind(
query
.status
.as_ref()
.map(|value| serialize_enum_text(value, "status"))
.transpose()?,
)
.bind(
query
.source
.as_ref()
.map(|value| serialize_enum_text(value, "source"))
.transpose()?,
)
.bind(query.operation_id.map(|value| value.as_str()))
.bind(query.agent_id.map(|value| value.as_str()))
.bind(
query
.outcome_group
.as_ref()
.map(|value| serialize_enum_text(value, "outcome_group"))
.transpose()?,
)
.bind(query.created_after)
.bind(query.created_before)
.bind(query.cursor_created_at)
.bind(query.cursor_id.map(|value| value.as_str()))
.bind(query.search_text)
.bind(i64::from(query.limit))
.fetch_all(&self.pool)
.await?;
rows.iter().map(map_invocation_log_record).collect()
}
pub async fn get_invocation_log(
&self,
workspace_id: &WorkspaceId,
log_id: &InvocationLogId,
) -> Result<Option<InvocationLogRecord>, RegistryError> {
let row = sqlx::query(
"select
l.id,
l.workspace_id,
l.agent_id,
l.platform_api_key_id,
l.operation_id,
l.operation_version,
l.source,
l.level,
l.status,
l.tool_name,
l.message,
l.request_id,
l.trace_id,
l.status_code,
l.duration_ms,
l.error_kind,
l.execution_stage,
l.execution_error_code,
l.retryability,
l.outcome_certainty,
l.request_preview_json,
l.response_preview_json,
l.created_at as created_at,
o.name as operation_name,
o.display_name as operation_display_name,
a.slug as agent_slug,
a.display_name as agent_display_name
from invocation_logs l
join operations o on o.id = l.operation_id
left join agents a on a.id = l.agent_id
where l.workspace_id = $1 and l.id = $2",
)
.bind(workspace_id.as_str())
.bind(log_id.as_str())
.fetch_optional(&self.pool)
.await?;
row.as_ref().map(map_invocation_log_record).transpose()
}
pub async fn summarize_usage(
&self,
query: UsageQuery<'_>,
) -> Result<UsageSummary, RegistryError> {
let row = sqlx::query(
"select
count(*)::bigint as calls_total,
count(*) filter (where status = 'ok')::bigint as calls_ok,
count(*) filter (where status = 'error')::bigint as calls_error,
coalesce(percentile_cont(0.5) within group (order by duration_ms), 0)::bigint as p50_ms,
coalesce(percentile_cont(0.95) within group (order by duration_ms), 0)::bigint as p95_ms,
coalesce(percentile_cont(0.99) within group (order by duration_ms), 0)::bigint as p99_ms
from invocation_logs
where workspace_id = $1
and created_at >= $2::timestamptz
and created_at < $3::timestamptz
and ($4::text is null or source = $4)",
)
.bind(query.workspace_id.as_str())
.bind(query.created_after)
.bind(query.created_before)
.bind(
query
.source
.as_ref()
.map(|value| serialize_enum_text(value, "source"))
.transpose()?,
)
.fetch_one(&self.pool)
.await?;
let calls_total = row.try_get::<i64, _>("calls_total")?;
let calls_ok = row.try_get::<i64, _>("calls_ok")?;
let calls_error = row.try_get::<i64, _>("calls_error")?;
let rollup = UsageRollup {
workspace_id: query.workspace_id.clone(),
agent_id: None,
operation_id: None,
period: query.period,
calls_total: to_u64(calls_total, "calls_total")?,
calls_ok: to_u64(calls_ok, "calls_ok")?,
calls_error: to_u64(calls_error, "calls_error")?,
p50_ms: to_u64(row.try_get::<i64, _>("p50_ms")?, "p50_ms")?,
p95_ms: to_u64(row.try_get::<i64, _>("p95_ms")?, "p95_ms")?,
p99_ms: to_u64(row.try_get::<i64, _>("p99_ms")?, "p99_ms")?,
};
let success_rate = if rollup.calls_total == 0 {
0.0
} else {
(rollup.calls_ok as f64 / rollup.calls_total as f64) * 100.0
};
Ok(UsageSummary {
rollup,
success_rate,
})
}
pub async fn list_usage_timeline(
&self,
query: UsageQuery<'_>,
) -> Result<Vec<UsageTimelinePoint>, RegistryError> {
let bucket = usage_bucket_sql(query.bucket);
let sql = format!(
"select
(date_trunc('{bucket}', created_at at time zone 'UTC') at time zone 'UTC') as bucket_start,
count(*) filter (where status = 'ok')::bigint as calls_ok,
count(*) filter (where status = 'error')::bigint as calls_error
from invocation_logs
where workspace_id = $1
and created_at >= $2::timestamptz
and created_at < $3::timestamptz
and ($4::text is null or source = $4)
group by 1
order by 1 asc"
);
let rows = sqlx::query(sqlx::AssertSqlSafe(sql))
.bind(query.workspace_id.as_str())
.bind(query.created_after)
.bind(query.created_before)
.bind(
query
.source
.as_ref()
.map(|value| serialize_enum_text(value, "source"))
.transpose()?,
)
.fetch_all(&self.pool)
.await?;
rows.iter()
.map(|row| {
Ok(UsageTimelinePoint {
bucket_start: row.try_get("bucket_start")?,
calls_ok: to_u64(row.try_get::<i64, _>("calls_ok")?, "calls_ok")?,
calls_error: to_u64(row.try_get::<i64, _>("calls_error")?, "calls_error")?,
})
})
.collect()
}
pub async fn list_usage_by_operation(
&self,
query: UsageQuery<'_>,
) -> Result<Vec<UsageOperationBreakdown>, RegistryError> {
let rows = sqlx::query(
"select
o.id as operation_id,
o.name as operation_name,
o.display_name as operation_display_name,
o.protocol,
count(*)::bigint as calls_total,
count(*) filter (where l.status = 'error')::bigint as calls_error,
coalesce(percentile_cont(0.5) within group (order by l.duration_ms), 0)::bigint as p50_ms,
coalesce(percentile_cont(0.95) within group (order by l.duration_ms), 0)::bigint as p95_ms,
coalesce(percentile_cont(0.99) within group (order by l.duration_ms), 0)::bigint as p99_ms
from invocation_logs l
join operations o on o.id = l.operation_id
where l.workspace_id = $1
and l.created_at >= $2::timestamptz
and l.created_at < $3::timestamptz
and ($4::text is null or l.source = $4)
group by o.id, o.name, o.display_name, o.protocol
order by calls_total desc, o.name asc",
)
.bind(query.workspace_id.as_str())
.bind(query.created_after)
.bind(query.created_before)
.bind(
query
.source
.as_ref()
.map(|value| serialize_enum_text(value, "source"))
.transpose()?,
)
.fetch_all(&self.pool)
.await?;
rows.iter().map(map_usage_operation_breakdown).collect()
}
pub async fn get_usage_for_operation(
&self,
query: UsageQuery<'_>,
operation_id: &OperationId,
) -> Result<Option<UsageRollupRecord>, RegistryError> {
let row = sqlx::query(
"select
count(*)::bigint as calls_total,
count(*) filter (where status = 'ok')::bigint as calls_ok,
count(*) filter (where status = 'error')::bigint as calls_error,
coalesce(percentile_cont(0.5) within group (order by duration_ms), 0)::bigint as p50_ms,
coalesce(percentile_cont(0.95) within group (order by duration_ms), 0)::bigint as p95_ms,
coalesce(percentile_cont(0.99) within group (order by duration_ms), 0)::bigint as p99_ms
from invocation_logs
where workspace_id = $1
and operation_id = $2
and created_at >= $3::timestamptz
and created_at < $4::timestamptz
and ($5::text is null or source = $5)",
)
.bind(query.workspace_id.as_str())
.bind(operation_id.as_str())
.bind(query.created_after)
.bind(query.created_before)
.bind(
query
.source
.as_ref()
.map(|value| serialize_enum_text(value, "source"))
.transpose()?,
)
.fetch_one(&self.pool)
.await?;
let calls_total = to_u64(row.try_get::<i64, _>("calls_total")?, "calls_total")?;
if calls_total == 0 {
return Ok(None);
}
Ok(Some(UsageRollupRecord {
rollup: UsageRollup {
workspace_id: query.workspace_id.clone(),
agent_id: None,
operation_id: Some(operation_id.clone()),
period: query.period,
calls_total,
calls_ok: to_u64(row.try_get::<i64, _>("calls_ok")?, "calls_ok")?,
calls_error: to_u64(row.try_get::<i64, _>("calls_error")?, "calls_error")?,
p50_ms: to_u64(row.try_get::<i64, _>("p50_ms")?, "p50_ms")?,
p95_ms: to_u64(row.try_get::<i64, _>("p95_ms")?, "p95_ms")?,
p99_ms: to_u64(row.try_get::<i64, _>("p99_ms")?, "p99_ms")?,
},
}))
}
pub async fn list_usage_by_agent(
&self,
query: UsageQuery<'_>,
) -> Result<Vec<UsageAgentBreakdown>, RegistryError> {
let rows = sqlx::query(
"select
a.id as agent_id,
a.slug as agent_slug,
a.display_name as agent_display_name,
count(*)::bigint as calls_total,
count(*) filter (where l.status = 'error')::bigint as calls_error,
coalesce(percentile_cont(0.5) within group (order by l.duration_ms), 0)::bigint as p50_ms,
coalesce(percentile_cont(0.95) within group (order by l.duration_ms), 0)::bigint as p95_ms,
coalesce(percentile_cont(0.99) within group (order by l.duration_ms), 0)::bigint as p99_ms
from invocation_logs l
join agents a on a.id = l.agent_id
where l.workspace_id = $1
and l.created_at >= $2::timestamptz
and l.created_at < $3::timestamptz
and ($4::text is null or l.source = $4)
group by a.id, a.slug, a.display_name
order by calls_total desc, a.slug asc",
)
.bind(query.workspace_id.as_str())
.bind(query.created_after)
.bind(query.created_before)
.bind(
query
.source
.as_ref()
.map(|value| serialize_enum_text(value, "source"))
.transpose()?,
)
.fetch_all(&self.pool)
.await?;
rows.iter().map(map_usage_agent_breakdown).collect()
}
pub async fn get_usage_for_agent(
&self,
query: UsageQuery<'_>,
agent_id: &AgentId,
) -> Result<Option<UsageRollupRecord>, RegistryError> {
let row = sqlx::query(
"select
count(*)::bigint as calls_total,
count(*) filter (where status = 'ok')::bigint as calls_ok,
count(*) filter (where status = 'error')::bigint as calls_error,
coalesce(percentile_cont(0.5) within group (order by duration_ms), 0)::bigint as p50_ms,
coalesce(percentile_cont(0.95) within group (order by duration_ms), 0)::bigint as p95_ms,
coalesce(percentile_cont(0.99) within group (order by duration_ms), 0)::bigint as p99_ms
from invocation_logs
where workspace_id = $1
and agent_id = $2
and created_at >= $3::timestamptz
and created_at < $4::timestamptz
and ($5::text is null or source = $5)",
)
.bind(query.workspace_id.as_str())
.bind(agent_id.as_str())
.bind(query.created_after)
.bind(query.created_before)
.bind(
query
.source
.as_ref()
.map(|value| serialize_enum_text(value, "source"))
.transpose()?,
)
.fetch_one(&self.pool)
.await?;
let calls_total = to_u64(row.try_get::<i64, _>("calls_total")?, "calls_total")?;
if calls_total == 0 {
return Ok(None);
}
Ok(Some(UsageRollupRecord {
rollup: UsageRollup {
workspace_id: query.workspace_id.clone(),
agent_id: Some(agent_id.clone()),
operation_id: None,
period: query.period,
calls_total,
calls_ok: to_u64(row.try_get::<i64, _>("calls_ok")?, "calls_ok")?,
calls_error: to_u64(row.try_get::<i64, _>("calls_error")?, "calls_error")?,
p50_ms: to_u64(row.try_get::<i64, _>("p50_ms")?, "p50_ms")?,
p95_ms: to_u64(row.try_get::<i64, _>("p95_ms")?, "p95_ms")?,
p99_ms: to_u64(row.try_get::<i64, _>("p99_ms")?, "p99_ms")?,
},
}))
}
pub async fn list_usage_outcomes(
&self,
query: UsageQuery<'_>,
) -> Result<Vec<UsageOutcomeBreakdown>, RegistryError> {
let outcome_group_case = usage_outcome_group_case_sql("");
let sql = format!(
"select
{outcome_group_case} as outcome_group,
execution_error_code,
count(*)::bigint as calls_total,
coalesce(percentile_cont(0.5) within group (order by duration_ms), 0)::bigint as p50_ms,
coalesce(percentile_cont(0.95) within group (order by duration_ms), 0)::bigint as p95_ms,
coalesce(percentile_cont(0.99) within group (order by duration_ms), 0)::bigint as p99_ms
from invocation_logs
where workspace_id = $1
and created_at >= $2::timestamptz
and created_at < $3::timestamptz
and ($4::text is null or source = $4)
group by 1, execution_error_code
order by outcome_group asc, execution_error_code asc nulls first"
);
let rows = sqlx::query(sqlx::AssertSqlSafe(sql))
.bind(query.workspace_id.as_str())
.bind(query.created_after)
.bind(query.created_before)
.bind(
query
.source
.as_ref()
.map(|value| serialize_enum_text(value, "source"))
.transpose()?,
)
.fetch_all(&self.pool)
.await?;
rows.iter()
.map(|row| {
Ok(UsageOutcomeBreakdown {
group: deserialize_enum_text(
&row.try_get::<String, _>("outcome_group")?,
"outcome_group",
)?,
execution_error_code: row
.try_get::<Option<String>, _>("execution_error_code")?
.map(|value| deserialize_enum_text(&value, "execution_error_code"))
.transpose()?,
calls_total: to_u64(row.try_get::<i64, _>("calls_total")?, "calls_total")?,
p50_ms: to_u64(row.try_get::<i64, _>("p50_ms")?, "p50_ms")?,
p95_ms: to_u64(row.try_get::<i64, _>("p95_ms")?, "p95_ms")?,
p99_ms: to_u64(row.try_get::<i64, _>("p99_ms")?, "p99_ms")?,
})
})
.collect()
}
}
#[cfg(test)]
mod tests {
use crank_core::ExecutionErrorCode;
use super::usage_outcome_group_case_sql;
#[test]
fn usage_outcome_group_sql_covers_every_execution_error_code() {
let sql = usage_outcome_group_case_sql("");
for code in ExecutionErrorCode::ALL {
assert!(
sql.contains(code.as_str()),
"missing execution outcome grouping for {}",
code.as_str()
);
}
}
}