feat: complete Epic 1 production foundation
This commit is contained in:
1 parent
767428436d
commit
182bde8ac0
298 files changed
+35711
-5291
No files matched your search
@@ -1,5 +1,56 @@
|
||||
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)
|
||||
@@ -19,12 +70,36 @@ impl PostgresRegistry {
|
||||
pub async fn delete_invocation_logs_before(
|
||||
&self,
|
||||
cutoff: OffsetDateTime,
|
||||
) -> Result<u64, RegistryError> {
|
||||
let result = sqlx::query("delete from invocation_logs where created_at < $1::timestamptz")
|
||||
.bind(cutoff)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(result.rows_affected())
|
||||
) -> 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(
|
||||
@@ -63,15 +138,77 @@ impl PostgresRegistry {
|
||||
.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 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?;
|
||||
}
|
||||
sqlx::query(
|
||||
"insert into invocation_logs (
|
||||
id,
|
||||
workspace_id,
|
||||
agent_id,
|
||||
platform_api_key_id,
|
||||
operation_id,
|
||||
operation_version,
|
||||
source,
|
||||
level,
|
||||
status,
|
||||
@@ -82,17 +219,29 @@ impl PostgresRegistry {
|
||||
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::timestamptz
|
||||
$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")?)
|
||||
@@ -108,12 +257,157 @@ impl PostgresRegistry {
|
||||
}
|
||||
})?)
|
||||
.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(&self.pool)
|
||||
.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?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
transaction.commit().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -121,12 +415,15 @@ impl PostgresRegistry {
|
||||
&self,
|
||||
query: ListInvocationLogsQuery<'_>,
|
||||
) -> Result<Vec<InvocationLogRecord>, RegistryError> {
|
||||
let rows = sqlx::query(
|
||||
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,
|
||||
@@ -137,6 +434,10 @@ impl PostgresRegistry {
|
||||
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,
|
||||
@@ -149,42 +450,67 @@ impl PostgresRegistry {
|
||||
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.source = $3)
|
||||
and ($4::text is null or l.operation_id = $4)
|
||||
and ($5::text is null or l.agent_id = $5)
|
||||
and ($6::timestamptz is null or l.created_at >= $6::timestamptz)
|
||||
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 (
|
||||
$7::text is null
|
||||
or l.tool_name ilike '%' || $7 || '%'
|
||||
or l.message ilike '%' || $7 || '%'
|
||||
or o.name ilike '%' || $7 || '%'
|
||||
or o.display_name ilike '%' || $7 || '%'
|
||||
$10::timestamptz is null
|
||||
or (l.created_at, l.id) < ($10::timestamptz, $11::text)
|
||||
)
|
||||
order by l.created_at desc
|
||||
limit $8",
|
||||
)
|
||||
.bind(query.workspace_id.as_str())
|
||||
.bind(
|
||||
query
|
||||
.level
|
||||
.as_ref()
|
||||
.map(|value| serialize_enum_text(value, "level"))
|
||||
.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.created_after)
|
||||
.bind(query.search_text)
|
||||
.bind(i64::from(query.limit))
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
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()
|
||||
}
|
||||
@@ -199,7 +525,9 @@ impl PostgresRegistry {
|
||||
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,
|
||||
@@ -210,6 +538,10 @@ impl PostgresRegistry {
|
||||
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,
|
||||
@@ -245,10 +577,12 @@ impl PostgresRegistry {
|
||||
from invocation_logs
|
||||
where workspace_id = $1
|
||||
and created_at >= $2::timestamptz
|
||||
and ($3::text is null or source = $3)",
|
||||
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
|
||||
@@ -300,13 +634,15 @@ impl PostgresRegistry {
|
||||
from invocation_logs
|
||||
where workspace_id = $1
|
||||
and created_at >= $2::timestamptz
|
||||
and ($3::text is null or source = $3)
|
||||
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
|
||||
@@ -347,12 +683,14 @@ impl PostgresRegistry {
|
||||
join operations o on o.id = l.operation_id
|
||||
where l.workspace_id = $1
|
||||
and l.created_at >= $2::timestamptz
|
||||
and ($3::text is null or l.source = $3)
|
||||
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
|
||||
@@ -383,11 +721,13 @@ impl PostgresRegistry {
|
||||
where workspace_id = $1
|
||||
and operation_id = $2
|
||||
and created_at >= $3::timestamptz
|
||||
and ($4::text is null or source = $4)",
|
||||
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
|
||||
@@ -437,12 +777,14 @@ impl PostgresRegistry {
|
||||
join agents a on a.id = l.agent_id
|
||||
where l.workspace_id = $1
|
||||
and l.created_at >= $2::timestamptz
|
||||
and ($3::text is null or l.source = $3)
|
||||
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
|
||||
@@ -473,11 +815,13 @@ impl PostgresRegistry {
|
||||
where workspace_id = $1
|
||||
and agent_id = $2
|
||||
and created_at >= $3::timestamptz
|
||||
and ($4::text is null or source = $4)",
|
||||
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
|
||||
@@ -508,4 +852,78 @@ impl PostgresRegistry {
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
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()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user