mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 01:10:23 +08:00
Fix/usage transfer filter (#307)
* fix(usage): 恢复 usage 列表中的 fallback 路由信号 * fix(admin): 支持 usage 记录展示和筛选 fallback 转移 * fix(usage): 在用户 usage 记录中暴露 fallback 标记 * fix(usage): 共享 usage 页面支持 fallback 筛选 * fix(usage): 对齐 fallback 筛选相关前端类型 * fix(usage): propagate has_fallback through active polling --------- Co-authored-by: fawney19 <elky0401@gmail.com>
This commit is contained in:
@@ -5,10 +5,11 @@ use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::query_param_value;
|
||||
use crate::GatewayError;
|
||||
use aether_admin::observability::usage::{
|
||||
admin_usage_bad_request_response, admin_usage_data_unavailable_response, admin_usage_parse_ids,
|
||||
admin_usage_parse_limit, admin_usage_parse_offset, build_admin_usage_active_requests_response,
|
||||
build_admin_usage_records_response, build_admin_usage_summary_stats_response_from_summary,
|
||||
ADMIN_USAGE_DATA_UNAVAILABLE_DETAIL,
|
||||
admin_usage_bad_request_response, admin_usage_data_unavailable_response,
|
||||
admin_usage_has_fallback, admin_usage_matches_search, admin_usage_matches_username,
|
||||
admin_usage_parse_ids, admin_usage_parse_limit, admin_usage_parse_offset,
|
||||
build_admin_usage_active_requests_response, build_admin_usage_records_response,
|
||||
build_admin_usage_summary_stats_response_from_summary, ADMIN_USAGE_DATA_UNAVAILABLE_DETAIL,
|
||||
};
|
||||
use aether_data_contracts::repository::usage::{
|
||||
StoredRequestUsageAudit, UsageAuditKeywordSearchQuery, UsageAuditListQuery,
|
||||
@@ -54,6 +55,7 @@ fn apply_admin_usage_status_filter(query: &mut UsageAuditListQuery, status: Opti
|
||||
"pending" | "streaming" | "completed" | "cancelled" => {
|
||||
query.statuses = Some(vec![status.to_string()]);
|
||||
}
|
||||
"has_fallback" => {}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -331,6 +333,9 @@ pub(super) async fn maybe_build_local_admin_usage_summary_response(
|
||||
Ok(value) => value,
|
||||
Err(detail) => return Ok(Some(admin_usage_bad_request_response(detail))),
|
||||
};
|
||||
let has_fallback_only = query_param_value(query, "status")
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.trim().eq_ignore_ascii_case("has_fallback"));
|
||||
let search = query_param_value(query, "search");
|
||||
let username_filter = query_param_value(query, "username");
|
||||
let limit = match admin_usage_parse_limit(query) {
|
||||
@@ -367,7 +372,44 @@ pub(super) async fn maybe_build_local_admin_usage_summary_response(
|
||||
let active_username_filter = username_filter
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty());
|
||||
let (usage, total) = if active_search.is_some() || active_username_filter.is_some() {
|
||||
let (usage, total) = if has_fallback_only {
|
||||
let mut usage = state.list_usage_audits(&base_query).await?;
|
||||
let user_ids: Vec<String> = usage
|
||||
.iter()
|
||||
.filter_map(|item| item.user_id.clone())
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
let users_by_id: BTreeMap<
|
||||
String,
|
||||
aether_data::repository::users::StoredUserSummary,
|
||||
> = state.resolve_auth_user_summaries_by_ids(&user_ids).await?;
|
||||
let api_key_names = admin_usage_api_key_names(state, &usage).await?;
|
||||
|
||||
usage.retain(|item| {
|
||||
admin_usage_matches_search(
|
||||
item,
|
||||
active_search,
|
||||
&users_by_id,
|
||||
&api_key_names,
|
||||
state.has_auth_user_data_reader(),
|
||||
state.has_auth_api_key_data_reader(),
|
||||
) && admin_usage_matches_username(
|
||||
item,
|
||||
active_username_filter,
|
||||
&users_by_id,
|
||||
state.has_auth_user_data_reader(),
|
||||
) && admin_usage_has_fallback(item)
|
||||
});
|
||||
sort_usage_newest_first(&mut usage);
|
||||
let total = usage.len();
|
||||
let records = usage
|
||||
.into_iter()
|
||||
.skip(offset)
|
||||
.take(limit)
|
||||
.collect::<Vec<_>>();
|
||||
(records, total)
|
||||
} else if active_search.is_some() || active_username_filter.is_some() {
|
||||
let keywords = active_search
|
||||
.map(parse_admin_usage_search_keywords)
|
||||
.unwrap_or_default();
|
||||
|
||||
@@ -217,6 +217,7 @@ fn build_users_me_usage_record_payload(
|
||||
"first_byte_time_ms": item.first_byte_time_ms,
|
||||
"is_stream": item.is_stream,
|
||||
"status": item.status,
|
||||
"has_fallback": item.has_fallback(),
|
||||
"created_at": unix_secs_to_rfc3339(item.created_at_unix_ms),
|
||||
"cache_creation_input_tokens": item.cache_creation_input_tokens,
|
||||
"cache_creation_ephemeral_5m_input_tokens": item.cache_creation_ephemeral_5m_input_tokens,
|
||||
@@ -265,6 +266,7 @@ fn build_users_me_usage_active_payload(item: &StoredRequestUsageAudit) -> serde_
|
||||
"endpoint_api_format": item.endpoint_api_format,
|
||||
"has_format_conversion": item.has_format_conversion,
|
||||
"target_model": item.target_model,
|
||||
"has_fallback": item.has_fallback(),
|
||||
});
|
||||
if item.api_format.is_none() {
|
||||
payload
|
||||
|
||||
@@ -745,21 +745,25 @@ async fn gateway_handles_admin_usage_active_locally_with_trusted_admin_principal
|
||||
start_usage_upstream("/api/admin/usage/active").await;
|
||||
|
||||
let usage_repository = Arc::new(InMemoryUsageReadRepository::seed(vec![
|
||||
sample_usage_row(
|
||||
"usage-pending",
|
||||
"req-pending",
|
||||
Some("user-1"),
|
||||
Some("key-1"),
|
||||
Some("primary"),
|
||||
"OpenAI",
|
||||
"gpt-5",
|
||||
"pending",
|
||||
10,
|
||||
0,
|
||||
0.0,
|
||||
0.0,
|
||||
DAY_2_UNIX_SECS,
|
||||
),
|
||||
{
|
||||
let mut row = sample_usage_row(
|
||||
"usage-pending",
|
||||
"req-pending",
|
||||
Some("user-1"),
|
||||
Some("key-1"),
|
||||
Some("primary"),
|
||||
"OpenAI",
|
||||
"gpt-5",
|
||||
"pending",
|
||||
10,
|
||||
0,
|
||||
0.0,
|
||||
0.0,
|
||||
DAY_2_UNIX_SECS,
|
||||
);
|
||||
row.candidate_index = Some(1);
|
||||
row
|
||||
},
|
||||
sample_usage_row(
|
||||
"usage-done",
|
||||
"req-done",
|
||||
@@ -819,6 +823,7 @@ async fn gateway_handles_admin_usage_active_locally_with_trusted_admin_principal
|
||||
assert_eq!(payload["requests"][0]["effective_input_tokens"], 5);
|
||||
assert_eq!(payload["requests"][0]["provider"], "OpenAI");
|
||||
assert_eq!(payload["requests"][0]["api_key_name"], "fresh-primary");
|
||||
assert_eq!(payload["requests"][0]["has_fallback"], true);
|
||||
assert_eq!(
|
||||
payload["requests"][0]["provider_key_name"],
|
||||
"upstream-primary"
|
||||
@@ -1107,6 +1112,77 @@ async fn gateway_handles_admin_usage_records_with_provider_key_name_fallback_fro
|
||||
upstream_handle.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_filters_admin_usage_records_by_has_fallback_status() {
|
||||
let (_upstream_url, upstream_hits, upstream_handle) =
|
||||
start_usage_upstream("/api/admin/usage/records").await;
|
||||
|
||||
let mut fallback_usage = sample_usage_row(
|
||||
"usage-has-fallback",
|
||||
"req-has-fallback",
|
||||
Some("user-1"),
|
||||
Some("key-1"),
|
||||
Some("primary"),
|
||||
"OpenAI",
|
||||
"gpt-5",
|
||||
"completed",
|
||||
12,
|
||||
8,
|
||||
0.02,
|
||||
0.02,
|
||||
DAY_1_UNIX_SECS,
|
||||
);
|
||||
fallback_usage.candidate_index = Some(1);
|
||||
|
||||
let usage_repository = Arc::new(InMemoryUsageReadRepository::seed(vec![
|
||||
fallback_usage,
|
||||
sample_usage_row(
|
||||
"usage-no-fallback",
|
||||
"req-no-fallback",
|
||||
Some("user-1"),
|
||||
Some("key-1"),
|
||||
Some("primary"),
|
||||
"OpenAI",
|
||||
"gpt-5",
|
||||
"completed",
|
||||
12,
|
||||
8,
|
||||
0.02,
|
||||
0.02,
|
||||
DAY_1_UNIX_SECS,
|
||||
),
|
||||
]));
|
||||
let user_repository = Arc::new(InMemoryUserReadRepository::seed(vec![sample_user_summary(
|
||||
"user-1", "alice",
|
||||
)]));
|
||||
let gateway = build_router_with_state(
|
||||
AppState::new()
|
||||
.expect("gateway should build")
|
||||
.with_data_state_for_tests(
|
||||
GatewayDataState::with_usage_reader_for_tests(usage_repository)
|
||||
.with_user_reader(user_repository),
|
||||
),
|
||||
);
|
||||
let (gateway_url, gateway_handle) = start_server(gateway).await;
|
||||
|
||||
let response = admin_request(reqwest::Client::new().get(format!(
|
||||
"{gateway_url}/api/admin/usage/records?start_date=2024-03-21&end_date=2024-03-22&tz_offset_minutes=0&status=has_fallback&limit=10&offset=0"
|
||||
)))
|
||||
.send()
|
||||
.await
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let payload: serde_json::Value = response.json().await.expect("json body should parse");
|
||||
assert_eq!(payload["total"], 1);
|
||||
assert_eq!(payload["records"][0]["id"], "usage-has-fallback");
|
||||
assert_eq!(payload["records"][0]["has_fallback"], true);
|
||||
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
|
||||
|
||||
gateway_handle.abort();
|
||||
upstream_handle.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_handles_admin_usage_records_with_snapshot_first_user_and_api_key_names() {
|
||||
let (_upstream_url, upstream_hits, upstream_handle) =
|
||||
|
||||
@@ -4795,6 +4795,7 @@ async fn gateway_handles_users_me_usage_locally_without_proxying_upstream() {
|
||||
"streaming",
|
||||
now - chrono::Duration::minutes(5),
|
||||
);
|
||||
streaming_usage.candidate_index = Some(2);
|
||||
streaming_usage.request_metadata = Some(json!({
|
||||
"rate_multiplier": 0.5,
|
||||
"input_price_per_1m": 3.0,
|
||||
@@ -4886,6 +4887,7 @@ async fn gateway_handles_users_me_usage_locally_without_proxying_upstream() {
|
||||
assert_eq!(payload["records"][0]["output_price_per_1m"], 9.0);
|
||||
assert_eq!(payload["records"][0]["cache_creation_price_per_1m"], 3.75);
|
||||
assert_eq!(payload["records"][0]["cache_read_price_per_1m"], 0.3);
|
||||
assert_eq!(payload["records"][0]["has_fallback"], true);
|
||||
assert_eq!(payload["records"][0]["api_key"]["name"], "renamed-key");
|
||||
assert_eq!(payload["records"][0]["api_key"]["display"], "renamed-key");
|
||||
assert_eq!(
|
||||
|
||||
@@ -238,6 +238,10 @@ pub fn admin_usage_is_failed(item: &StoredRequestUsageAudit) -> bool {
|
||||
.is_some_and(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
pub fn admin_usage_has_fallback(item: &StoredRequestUsageAudit) -> bool {
|
||||
item.has_fallback()
|
||||
}
|
||||
|
||||
pub fn admin_usage_matches_status(item: &StoredRequestUsageAudit, status: Option<&str>) -> bool {
|
||||
let Some(status) = status.map(str::trim).filter(|value| !value.is_empty()) else {
|
||||
return true;
|
||||
@@ -251,6 +255,7 @@ pub fn admin_usage_matches_status(item: &StoredRequestUsageAudit, status: Option
|
||||
"pending" | "streaming" | "completed" | "cancelled" => item.status == status,
|
||||
"failed" => admin_usage_is_failed(item),
|
||||
"active" => matches!(item.status.as_str(), "pending" | "streaming"),
|
||||
"has_fallback" => admin_usage_has_fallback(item),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
@@ -594,7 +599,7 @@ pub fn admin_usage_record_json(
|
||||
"status_code": item.status_code,
|
||||
"error_message": item.error_message,
|
||||
"status": item.status,
|
||||
"has_fallback": false,
|
||||
"has_fallback": admin_usage_has_fallback(item),
|
||||
"has_retry": false,
|
||||
"has_rectified": false,
|
||||
"is_free_tier": is_free_tier,
|
||||
@@ -1532,6 +1537,7 @@ pub fn build_admin_usage_active_requests_response(
|
||||
"provider": item.provider_name,
|
||||
"api_key_name": api_key_name,
|
||||
"provider_key_name": provider_key_name,
|
||||
"has_fallback": admin_usage_has_fallback(item),
|
||||
});
|
||||
if let Some(api_format) = item.api_format.as_ref() {
|
||||
value["api_format"] = json!(api_format);
|
||||
@@ -1766,9 +1772,9 @@ mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::{
|
||||
admin_usage_has_body_value, admin_usage_is_failed, admin_usage_matches_search,
|
||||
admin_usage_matches_status, admin_usage_matches_username, admin_usage_record_json,
|
||||
build_admin_usage_detail_payload,
|
||||
admin_usage_has_body_value, admin_usage_has_fallback, admin_usage_is_failed,
|
||||
admin_usage_matches_search, admin_usage_matches_status, admin_usage_matches_username,
|
||||
admin_usage_record_json, build_admin_usage_detail_payload,
|
||||
};
|
||||
use aether_data_contracts::repository::usage::{StoredRequestUsageAudit, UsageBodyField};
|
||||
|
||||
@@ -1840,6 +1846,25 @@ mod tests {
|
||||
assert!(admin_usage_matches_status(&item, Some("failed")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admin_usage_fallback_flag_uses_routing_candidate_index() {
|
||||
let mut item = sample_usage("completed", Some(200), None);
|
||||
item.candidate_index = Some(2);
|
||||
|
||||
assert!(admin_usage_has_fallback(&item));
|
||||
assert!(admin_usage_matches_status(&item, Some("has_fallback")));
|
||||
|
||||
let payload = admin_usage_record_json(
|
||||
&item,
|
||||
&BTreeMap::new(),
|
||||
&BTreeMap::new(),
|
||||
false,
|
||||
false,
|
||||
Some("primary"),
|
||||
);
|
||||
assert_eq!(payload["has_fallback"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn body_availability_considers_typed_reference_fields() {
|
||||
let item = StoredRequestUsageAudit {
|
||||
|
||||
@@ -361,6 +361,11 @@ impl StoredRequestUsageAudit {
|
||||
.or_else(|| self.request_metadata_u64("candidate_index"))
|
||||
}
|
||||
|
||||
pub fn has_fallback(&self) -> bool {
|
||||
self.routing_candidate_index()
|
||||
.is_some_and(|index| index > 0)
|
||||
}
|
||||
|
||||
pub fn routing_key_name(&self) -> Option<&str> {
|
||||
self.key_name
|
||||
.as_deref()
|
||||
|
||||
@@ -597,14 +597,42 @@ SELECT
|
||||
NULL::varchar AS http_provider_request_body_ref,
|
||||
NULL::varchar AS http_response_body_ref,
|
||||
NULL::varchar AS http_client_response_body_ref,
|
||||
NULL::varchar AS routing_candidate_id,
|
||||
NULL::integer AS routing_candidate_index,
|
||||
NULL::varchar AS routing_key_name,
|
||||
NULL::varchar AS routing_planner_kind,
|
||||
NULL::varchar AS routing_route_family,
|
||||
NULL::varchar AS routing_route_kind,
|
||||
NULL::varchar AS routing_execution_path,
|
||||
NULL::varchar AS routing_local_execution_runtime_miss_reason,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.candidate_id,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'candidate_id'), '')
|
||||
) AS routing_candidate_id,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.candidate_index,
|
||||
CASE
|
||||
WHEN ("usage".request_metadata->>'candidate_index') ~ '^[0-9]+$'
|
||||
THEN ("usage".request_metadata->>'candidate_index')::integer
|
||||
ELSE NULL
|
||||
END
|
||||
) AS routing_candidate_index,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.key_name,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'key_name'), '')
|
||||
) AS routing_key_name,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.planner_kind,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'planner_kind'), '')
|
||||
) AS routing_planner_kind,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.route_family,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'route_family'), '')
|
||||
) AS routing_route_family,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.route_kind,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'route_kind'), '')
|
||||
) AS routing_route_kind,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.execution_path,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'execution_path'), '')
|
||||
) AS routing_execution_path,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.local_execution_runtime_miss_reason,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'local_execution_runtime_miss_reason'), '')
|
||||
) AS routing_local_execution_runtime_miss_reason,
|
||||
usage_settlement_snapshots.billing_snapshot_schema_version AS settlement_billing_snapshot_schema_version,
|
||||
usage_settlement_snapshots.billing_snapshot_status AS settlement_billing_snapshot_status,
|
||||
CAST(usage_settlement_snapshots.rate_multiplier AS DOUBLE PRECISION) AS settlement_rate_multiplier,
|
||||
@@ -630,6 +658,8 @@ SELECT
|
||||
) AS BIGINT
|
||||
) AS finalized_at_unix_secs
|
||||
FROM "usage"
|
||||
LEFT JOIN usage_routing_snapshots
|
||||
ON usage_routing_snapshots.request_id = "usage".request_id
|
||||
LEFT JOIN usage_settlement_snapshots
|
||||
ON usage_settlement_snapshots.request_id = "usage".request_id
|
||||
"#;
|
||||
@@ -783,14 +813,42 @@ SELECT
|
||||
NULL::varchar AS http_provider_request_body_ref,
|
||||
NULL::varchar AS http_response_body_ref,
|
||||
NULL::varchar AS http_client_response_body_ref,
|
||||
NULL::varchar AS routing_candidate_id,
|
||||
NULL::integer AS routing_candidate_index,
|
||||
NULL::varchar AS routing_key_name,
|
||||
NULL::varchar AS routing_planner_kind,
|
||||
NULL::varchar AS routing_route_family,
|
||||
NULL::varchar AS routing_route_kind,
|
||||
NULL::varchar AS routing_execution_path,
|
||||
NULL::varchar AS routing_local_execution_runtime_miss_reason,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.candidate_id,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'candidate_id'), '')
|
||||
) AS routing_candidate_id,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.candidate_index,
|
||||
CASE
|
||||
WHEN ("usage".request_metadata->>'candidate_index') ~ '^[0-9]+$'
|
||||
THEN ("usage".request_metadata->>'candidate_index')::integer
|
||||
ELSE NULL
|
||||
END
|
||||
) AS routing_candidate_index,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.key_name,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'key_name'), '')
|
||||
) AS routing_key_name,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.planner_kind,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'planner_kind'), '')
|
||||
) AS routing_planner_kind,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.route_family,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'route_family'), '')
|
||||
) AS routing_route_family,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.route_kind,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'route_kind'), '')
|
||||
) AS routing_route_kind,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.execution_path,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'execution_path'), '')
|
||||
) AS routing_execution_path,
|
||||
COALESCE(
|
||||
usage_routing_snapshots.local_execution_runtime_miss_reason,
|
||||
NULLIF(BTRIM("usage".request_metadata->>'local_execution_runtime_miss_reason'), '')
|
||||
) AS routing_local_execution_runtime_miss_reason,
|
||||
usage_settlement_snapshots.billing_snapshot_schema_version AS settlement_billing_snapshot_schema_version,
|
||||
usage_settlement_snapshots.billing_snapshot_status AS settlement_billing_snapshot_status,
|
||||
CAST(usage_settlement_snapshots.rate_multiplier AS DOUBLE PRECISION) AS settlement_rate_multiplier,
|
||||
@@ -816,6 +874,8 @@ SELECT
|
||||
) AS BIGINT
|
||||
) AS finalized_at_unix_secs
|
||||
FROM "usage"
|
||||
LEFT JOIN usage_routing_snapshots
|
||||
ON usage_routing_snapshots.request_id = "usage".request_id
|
||||
LEFT JOIN usage_settlement_snapshots
|
||||
ON usage_settlement_snapshots.request_id = "usage".request_id
|
||||
"#;
|
||||
@@ -5701,10 +5761,10 @@ mod tests {
|
||||
assert!(super::LIST_USAGE_AUDITS_PREFIX.contains("NULL::json AS provider_request_body"));
|
||||
assert!(super::LIST_USAGE_AUDITS_PREFIX.contains("NULL::bytea AS request_body_compressed"));
|
||||
assert!(super::LIST_USAGE_AUDITS_PREFIX.contains("NULL::varchar AS http_request_body_ref"));
|
||||
assert!(super::LIST_USAGE_AUDITS_PREFIX.contains("NULL::varchar AS routing_candidate_id"));
|
||||
assert!(
|
||||
super::LIST_USAGE_AUDITS_PREFIX.contains("NULL::integer AS routing_candidate_index")
|
||||
);
|
||||
assert!(super::LIST_USAGE_AUDITS_PREFIX.contains("usage_routing_snapshots.candidate_id"));
|
||||
assert!(super::LIST_USAGE_AUDITS_PREFIX.contains("usage_routing_snapshots.candidate_index"));
|
||||
assert!(super::LIST_USAGE_AUDITS_PREFIX.contains("request_metadata->>'candidate_index'"));
|
||||
assert!(super::LIST_USAGE_AUDITS_PREFIX.contains("LEFT JOIN usage_routing_snapshots"));
|
||||
assert!(super::LIST_USAGE_AUDITS_PREFIX.contains("LEFT JOIN usage_settlement_snapshots"));
|
||||
assert!(
|
||||
super::LIST_USAGE_AUDITS_PREFIX.contains("settlement_billing_snapshot_schema_version")
|
||||
@@ -5718,9 +5778,15 @@ mod tests {
|
||||
assert!(super::LIST_RECENT_USAGE_AUDITS_PREFIX
|
||||
.contains("NULL::varchar AS http_client_response_body_ref"));
|
||||
assert!(super::LIST_RECENT_USAGE_AUDITS_PREFIX
|
||||
.contains("NULL::integer AS routing_candidate_index"));
|
||||
.contains("usage_routing_snapshots.candidate_index"));
|
||||
assert!(
|
||||
super::LIST_RECENT_USAGE_AUDITS_PREFIX.contains("request_metadata->>'candidate_index'")
|
||||
);
|
||||
assert!(
|
||||
super::LIST_RECENT_USAGE_AUDITS_PREFIX.contains("LEFT JOIN usage_routing_snapshots")
|
||||
);
|
||||
assert!(super::LIST_RECENT_USAGE_AUDITS_PREFIX
|
||||
.contains("NULL::varchar AS routing_execution_path"));
|
||||
.contains("usage_routing_snapshots.execution_path"));
|
||||
assert!(
|
||||
super::LIST_RECENT_USAGE_AUDITS_PREFIX.contains("LEFT JOIN usage_settlement_snapshots")
|
||||
);
|
||||
|
||||
@@ -69,6 +69,7 @@ export interface UsageRecordDetail {
|
||||
cache_creation_price_per_1m?: number
|
||||
cache_read_price_per_1m?: number
|
||||
price_per_request?: number // 按次计费价格
|
||||
has_fallback?: boolean
|
||||
api_key?: {
|
||||
id: string
|
||||
name: string
|
||||
@@ -293,6 +294,7 @@ export const meApi = {
|
||||
api_format?: string | null
|
||||
endpoint_api_format?: string | null
|
||||
has_format_conversion?: boolean | null
|
||||
has_fallback?: boolean | null
|
||||
}>
|
||||
}> {
|
||||
const params = ids ? { ids } : {}
|
||||
|
||||
@@ -307,6 +307,7 @@ export const usageApi = {
|
||||
api_format?: string | null
|
||||
endpoint_api_format?: string | null
|
||||
has_format_conversion?: boolean | null
|
||||
has_fallback?: boolean | null
|
||||
target_model?: string | null
|
||||
}>
|
||||
}> {
|
||||
|
||||
@@ -401,6 +401,7 @@ export function useUsageData(options: UseUsageDataOptions) {
|
||||
api_format: existing.api_format || record.api_format,
|
||||
endpoint_api_format: existing.endpoint_api_format || record.endpoint_api_format,
|
||||
has_format_conversion: existing.has_format_conversion ?? record.has_format_conversion,
|
||||
has_fallback: existing.has_fallback === true || record.has_fallback === true,
|
||||
api_key_name: existing.api_key_name || record.api_key_name,
|
||||
provider_key_name: existing.provider_key_name || record.provider_key_name,
|
||||
rate_multiplier: existing.rate_multiplier ?? record.rate_multiplier,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ref, computed, type Ref } from 'vue'
|
||||
import type { UsageRecord, FilterStatusValue } from '../types'
|
||||
import { isUsageRecordFailed } from '../utils/status'
|
||||
import { hasUsageFallback, isUsageRecordFailed } from '../utils/status'
|
||||
|
||||
export interface UseUsageFiltersOptions {
|
||||
/** 所有记录的响应式引用 */
|
||||
@@ -79,6 +79,8 @@ export function useUsageFilters(options: UseUsageFiltersOptions) {
|
||||
records = records.filter(record => isUsageRecordFailed(record))
|
||||
} else if (filterStatus.value === 'cancelled') {
|
||||
records = records.filter(record => record.status === 'cancelled')
|
||||
} else if (filterStatus.value === 'has_fallback') {
|
||||
records = records.filter(record => hasUsageFallback(record))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -127,7 +127,14 @@ export interface DateRangeParams {
|
||||
export type PeriodValue = 'today' | 'yesterday' | 'last7days' | 'last30days' | 'last90days'
|
||||
|
||||
// 筛选状态(简化为常用维度)
|
||||
export type FilterStatusValue = '__all__' | 'stream' | 'standard' | 'active' | 'failed' | 'cancelled'
|
||||
export type FilterStatusValue =
|
||||
'__all__' |
|
||||
'stream' |
|
||||
'standard' |
|
||||
'active' |
|
||||
'failed' |
|
||||
'cancelled' |
|
||||
'has_fallback'
|
||||
|
||||
// 默认统计状态
|
||||
export function createDefaultStats(): UsageStatsState {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
hasUsageFallback,
|
||||
isUsageRecordFailed,
|
||||
isUsageRecordSuccessful,
|
||||
mapRequestStatusToTimelineStatus,
|
||||
@@ -91,6 +92,12 @@ describe('usage status helpers', () => {
|
||||
})).toBe('failed')
|
||||
})
|
||||
|
||||
it('uses explicit has_fallback flag for transfer filtering', () => {
|
||||
expect(hasUsageFallback(buildUsageRecord({ has_fallback: true }))).toBe(true)
|
||||
expect(hasUsageFallback(buildUsageRecord({ has_fallback: false }))).toBe(false)
|
||||
expect(hasUsageFallback(buildUsageRecord({ has_fallback: undefined }))).toBe(false)
|
||||
})
|
||||
|
||||
it('uses status code only as a last fallback for timeline status', () => {
|
||||
expect(resolveTimelineFinalStatus({
|
||||
statusCode: 200,
|
||||
|
||||
@@ -11,6 +11,12 @@ function hasLegacyFailureSignal(
|
||||
(typeof record.error_message === 'string' && record.error_message.trim().length > 0)
|
||||
}
|
||||
|
||||
export function hasUsageFallback(
|
||||
record: Pick<UsageRecord, 'has_fallback'>
|
||||
): boolean {
|
||||
return record.has_fallback === true
|
||||
}
|
||||
|
||||
function hasTerminalSuccessStatusCode(
|
||||
record: Pick<UsageRecord, 'status_code'>
|
||||
): boolean {
|
||||
|
||||
@@ -144,7 +144,7 @@ import {
|
||||
getDateRangeFromPeriod
|
||||
} from '@/features/usage/composables'
|
||||
import { reconcileActiveRequestDiscovery } from '@/features/usage/utils/activeRequestDiscovery'
|
||||
import { isUsageRecordFailed } from '@/features/usage/utils/status'
|
||||
import { hasUsageFallback, isUsageRecordFailed } from '@/features/usage/utils/status'
|
||||
import type { DateRangeParams, FilterStatusValue } from '@/features/usage/types'
|
||||
import type { UserOption } from '@/features/usage/components/UsageRecordsTable.vue'
|
||||
import { log } from '@/utils/logger'
|
||||
@@ -309,6 +309,8 @@ const filteredRecords = computed(() => {
|
||||
records = records.filter(record => isUsageRecordFailed(record))
|
||||
} else if (filterStatus.value === 'cancelled') {
|
||||
records = records.filter(record => record.status === 'cancelled')
|
||||
} else if (filterStatus.value === 'has_fallback') {
|
||||
records = records.filter(record => hasUsageFallback(record))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -399,6 +401,9 @@ async function pollActiveRequests() {
|
||||
if (update.api_format != null) record.api_format = update.api_format
|
||||
if (update.endpoint_api_format != null) record.endpoint_api_format = update.endpoint_api_format
|
||||
if (update.has_format_conversion != null) record.has_format_conversion = update.has_format_conversion
|
||||
if (typeof update.has_fallback === 'boolean') {
|
||||
record.has_fallback = record.has_fallback === true || update.has_fallback
|
||||
}
|
||||
// 模型映射:streaming 时已可确定
|
||||
if ('target_model' in update && (typeof update.target_model === 'string' || update.target_model === null)) {
|
||||
record.target_model = update.target_model
|
||||
|
||||
Reference in New Issue
Block a user