mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-29 16:00:51 +00:00
perf(store): reduce redundant persistence and write amplification
Reuse unchanged catalog TOAST values during refresh. Remove unused analytics source versions and duplicate artifact version storage, retire the covered charge-event index, and index artifact configuration cleanup. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -107,15 +107,15 @@ impl PgRequestAnalyticsRepository {
|
||||
order by pending.oldest_pending_at, pending.request_id limit ($1::bigint - (select count(*) from live))
|
||||
) select request_id, change_version from live union all select request_id, change_version from oldest")
|
||||
.bind(i64::from(batch_size)).fetch_all(&mut *transaction).await.map_err(|error| postgres_unavailable("load analytics request queue", error))?;
|
||||
let mut jobs = Vec::with_capacity(rows.len());
|
||||
let mut ids = Vec::<String>::with_capacity(rows.len());
|
||||
let mut versions = Vec::<i64>::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
jobs.push(ProjectionJob { id: get(&row,"request_id")?, version: get(&row,"change_version")? });
|
||||
ids.push(get(&row,"request_id")?);
|
||||
versions.push(get(&row,"change_version")?);
|
||||
}
|
||||
self.project_batch(&mut transaction, &jobs).await?;
|
||||
result.projected_requests = jobs.len() as u64;
|
||||
self.project_batch(&mut transaction, &ids).await?;
|
||||
result.projected_requests = ids.len() as u64;
|
||||
result.backfilled_requests = self.backfill(&mut transaction, batch_size).await?;
|
||||
let ids = jobs.iter().map(|job|job.id.clone()).collect::<Vec<_>>();
|
||||
let versions = jobs.iter().map(|job|job.version).collect::<Vec<_>>();
|
||||
if result.projected_requests + result.backfilled_requests > 0 {
|
||||
publish_generation(&mut transaction, true).await?;
|
||||
}
|
||||
@@ -153,38 +153,35 @@ impl PgRequestAnalyticsRepository {
|
||||
async fn project_batch(
|
||||
&self,
|
||||
tx: &mut sqlx::Transaction<'_, Postgres>,
|
||||
jobs: &[ProjectionJob],
|
||||
ids: &[String],
|
||||
) -> StoreResult<()> {
|
||||
if jobs.is_empty() {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let ids = jobs.iter().map(|job| job.id.clone()).collect::<Vec<_>>();
|
||||
let versions = jobs.iter().map(|job| job.version).collect::<Vec<_>>();
|
||||
let previous = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"{} where mr.id=any($1::text[])",
|
||||
fact_select()
|
||||
)))
|
||||
.bind(&ids)
|
||||
.bind(ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read previous analytics contributions", error))?;
|
||||
sqlx::query("delete from request_analytics_facts where id=any($1::text[])")
|
||||
.bind(&ids)
|
||||
.bind(ids)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("replace analytics facts", error))?;
|
||||
sqlx::query(PROJECT_REQUEST)
|
||||
.bind(&ids)
|
||||
.bind(versions)
|
||||
.bind(ids)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("project analytics facts", error))?;
|
||||
self.project_billing_batch(tx, &ids).await?;
|
||||
self.project_billing_batch(tx, ids).await?;
|
||||
let current = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"{} where mr.id=any($1::text[])",
|
||||
fact_select()
|
||||
)))
|
||||
.bind(&ids)
|
||||
.bind(ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read current analytics contributions", error))?;
|
||||
@@ -204,7 +201,7 @@ impl PgRequestAnalyticsRepository {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut query = QueryBuilder::<Postgres>::new(
|
||||
"select id,started_at,nextval('request_analytics_change_version') as version,exists(select 1 from request_analytics_facts f where f.id=model_requests.id) as projected from model_requests",
|
||||
"select id,started_at,exists(select 1 from request_analytics_facts f where f.id=model_requests.id) as projected from model_requests",
|
||||
);
|
||||
// 首批与后续批次使用两种明确的计划,避免可空游标的 OR 使通用计划退化为全索引过滤
|
||||
if let Some(start) = get::<Option<DateTime<Utc>>>(&state, "backfill_cursor_started_at")? {
|
||||
@@ -225,17 +222,14 @@ impl PgRequestAnalyticsRepository {
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read analytics backfill batch", error))?;
|
||||
let mut jobs = Vec::with_capacity(rows.len());
|
||||
let mut ids = Vec::<String>::with_capacity(rows.len());
|
||||
for row in &rows {
|
||||
if get::<bool>(row, "projected")? {
|
||||
continue;
|
||||
}
|
||||
jobs.push(ProjectionJob {
|
||||
id: get(row, "id")?,
|
||||
version: get(row, "version")?,
|
||||
});
|
||||
ids.push(get(row, "id")?);
|
||||
}
|
||||
self.project_batch(tx, &jobs).await?;
|
||||
self.project_batch(tx, &ids).await?;
|
||||
if let Some(last) = rows.last() {
|
||||
sqlx::query("update request_analytics_build_state set backfill_cursor_started_at = $1, backfill_cursor_id = $2, coverage_start = $1 + interval '1 microsecond' where singleton")
|
||||
.bind(get::<DateTime<Utc>>(last,"started_at")?).bind(get::<String>(last,"id")?).execute(&mut **tx).await.map_err(|error| postgres_unavailable("save analytics backfill cursor", error))?;
|
||||
@@ -377,11 +371,6 @@ pub(super) fn collections(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
struct ProjectionJob {
|
||||
id: String,
|
||||
version: i64,
|
||||
}
|
||||
|
||||
async fn publish_generation(
|
||||
tx: &mut sqlx::Transaction<'_, Postgres>,
|
||||
facts_changed: bool,
|
||||
@@ -391,4 +380,4 @@ async fn publish_generation(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const PROJECT_REQUEST: &str = "insert into request_analytics_facts (id, started_at, completed_at, client_api_key_ref, provider_account_ref, routing_group_refs, operation, provider_kind, requested_model_id, upstream_model_id, outcome, client_status_code, upstream_status_code, client_transport, upstream_transport, attempt_count, client_response_id, upstream_response_id, upstream_request_id, recovered_at, downstream_committed_at, request_kind, image_generation_requested, image_generation_succeeded, error_kind, input_tokens, output_tokens, cached_input_tokens, cache_write_input_tokens, reasoning_output_tokens, image_input_tokens, image_output_tokens, total_tokens, cost_source, cost_currency, cost_amount, first_token_ms, latency_ms, admission_decision_ms, account_selection_wait_ms, upstream_response_ms, capacity_used_slots, capacity_total_slots, source_version, ops_failure_count, ops_rate_limited_count, ops_auth_failure_count, ops_provider_5xx_count) select mr.id, mr.started_at, mr.completed_at, mr.client_api_key_ref, mr.provider_account_ref, array(select distinct group_ref from unnest(mr.routing_group_refs) group_ref order by group_ref), mr.operation, mr.provider_kind, mr.requested_model_id, mr.upstream_model_id, mr.outcome, mr.client_status_code, mr.upstream_status_code, mr.client_transport, mr.upstream_transport, mr.attempt_count, mr.client_response_id, mr.upstream_response_id, mr.upstream_request_id, mr.recovered_at, mr.downstream_committed_at, mr.request_kind, mr.image_generation_requested, mr.image_generation_succeeded, mr.error_kind, mr.input_tokens, mr.output_tokens, mr.cached_input_tokens, mr.cache_write_input_tokens, mr.reasoning_output_tokens, mr.image_input_tokens, mr.image_output_tokens, mr.total_tokens, mr.cost_source, mr.cost_currency, mr.cost_amount, mr.first_token_ms, mr.latency_ms, mr.admission_decision_ms, mr.account_selection_wait_ms, mr.upstream_response_ms, mr.capacity_used_slots, mr.capacity_total_slots, job.version, ops.failure_count, ops.rate_limited_count, ops.auth_failure_count, ops.provider_5xx_count from unnest($1::text[],$2::bigint[]) job(id,version) join model_request_observations mr on mr.id=job.id cross join lateral (select count(*)::bigint as failure_count, count(*) filter(where failure_kind in ('rate_limited','quota_exhausted') or status_code=429)::bigint as rate_limited_count, count(*) filter(where failure_kind in ('authentication','authorization','invalid_credential') or status_code in (401,403))::bigint as auth_failure_count, count(*) filter(where status_code between 500 and 599)::bigint as provider_5xx_count from ops_events where model_request_id=mr.id) ops returning id, started_at";
|
||||
const PROJECT_REQUEST: &str = "insert into request_analytics_facts (id, started_at, completed_at, client_api_key_ref, provider_account_ref, routing_group_refs, operation, provider_kind, requested_model_id, upstream_model_id, outcome, client_status_code, upstream_status_code, client_transport, upstream_transport, attempt_count, client_response_id, upstream_response_id, upstream_request_id, recovered_at, downstream_committed_at, request_kind, image_generation_requested, image_generation_succeeded, error_kind, input_tokens, output_tokens, cached_input_tokens, cache_write_input_tokens, reasoning_output_tokens, image_input_tokens, image_output_tokens, total_tokens, cost_source, cost_currency, cost_amount, first_token_ms, latency_ms, admission_decision_ms, account_selection_wait_ms, upstream_response_ms, capacity_used_slots, capacity_total_slots, ops_failure_count, ops_rate_limited_count, ops_auth_failure_count, ops_provider_5xx_count) select mr.id, mr.started_at, mr.completed_at, mr.client_api_key_ref, mr.provider_account_ref, array(select distinct group_ref from unnest(mr.routing_group_refs) group_ref order by group_ref), mr.operation, mr.provider_kind, mr.requested_model_id, mr.upstream_model_id, mr.outcome, mr.client_status_code, mr.upstream_status_code, mr.client_transport, mr.upstream_transport, mr.attempt_count, mr.client_response_id, mr.upstream_response_id, mr.upstream_request_id, mr.recovered_at, mr.downstream_committed_at, mr.request_kind, mr.image_generation_requested, mr.image_generation_succeeded, mr.error_kind, mr.input_tokens, mr.output_tokens, mr.cached_input_tokens, mr.cache_write_input_tokens, mr.reasoning_output_tokens, mr.image_input_tokens, mr.image_output_tokens, mr.total_tokens, mr.cost_source, mr.cost_currency, mr.cost_amount, mr.first_token_ms, mr.latency_ms, mr.admission_decision_ms, mr.account_selection_wait_ms, mr.upstream_response_ms, mr.capacity_used_slots, mr.capacity_total_slots, ops.failure_count, ops.rate_limited_count, ops.auth_failure_count, ops.provider_5xx_count from unnest($1::text[]) job(id) join model_request_observations mr on mr.id=job.id cross join lateral (select count(*)::bigint as failure_count, count(*) filter(where failure_kind in ('rate_limited','quota_exhausted') or status_code=429)::bigint as rate_limited_count, count(*) filter(where failure_kind in ('authentication','authorization','invalid_credential') or status_code in (401,403))::bigint as auth_failure_count, count(*) filter(where status_code between 500 and 599)::bigint as provider_5xx_count from ops_events where model_request_id=mr.id) ops returning id, started_at";
|
||||
|
||||
@@ -264,8 +264,8 @@ impl PluginStore for PgPluginStore {
|
||||
.map_err(|error| admin_store_error("plugin", error))?;
|
||||
let mut platforms = metadata.platforms.clone();
|
||||
platforms.sort();
|
||||
let row = sqlx::query("insert into plugin_artifacts (sha256, plugin_id, version, metadata_json, source_json, outbound_proxy_id, archive) values ($1,$2,$3,$4,$5,$6,$7) returning metadata_json, source_json, installed_at, accepted_at")
|
||||
.bind(&metadata.sha256).bind(&metadata.plugin_id).bind(&metadata.version)
|
||||
let row = sqlx::query("insert into plugin_artifacts (sha256, plugin_id, metadata_json, source_json, outbound_proxy_id, archive) values ($1,$2,$3,$4,$5,$6) returning metadata_json, source_json, installed_at, accepted_at")
|
||||
.bind(&metadata.sha256).bind(&metadata.plugin_id)
|
||||
.bind(sqlx::types::Json(&metadata)).bind(sqlx::types::Json(&source))
|
||||
.bind(outbound_proxy.map(|proxy| proxy.id)).bind(artifact.archive.as_ref())
|
||||
.fetch_one(&mut *transaction).await.map_err(|error| {
|
||||
|
||||
@@ -64,11 +64,14 @@ impl PgProviderAccountRepository {
|
||||
observation: &AccountCatalogObservation,
|
||||
document: &[u8],
|
||||
) -> Result<bool, CoreStoreError> {
|
||||
// 相同正文复用旧 TOAST 值,定期复查只更新账号观测,减少正文重写及 WAL
|
||||
let result = sqlx::query("insert into provider_account_model_catalogs (account_id, credential_revision, plan_type, observed_at, document, etag)
|
||||
select a.id, a.credential_revision, a.plan_type, $4, $5, $6 from provider_accounts a
|
||||
where a.id=$1 and a.credential_revision=$2 and a.plan_type is not distinct from $3 for share
|
||||
on conflict (account_id) do update set credential_revision=excluded.credential_revision, plan_type=excluded.plan_type,
|
||||
etag=excluded.etag, observed_at=excluded.observed_at, document=excluded.document
|
||||
etag=excluded.etag, observed_at=excluded.observed_at, document=case
|
||||
when provider_account_model_catalogs.document_hash=excluded.document_hash
|
||||
then provider_account_model_catalogs.document else excluded.document end
|
||||
where provider_account_model_catalogs.credential_revision < excluded.credential_revision or
|
||||
(provider_account_model_catalogs.credential_revision=excluded.credential_revision and provider_account_model_catalogs.observed_at <= excluded.observed_at)")
|
||||
.bind(observation.account_id.as_str()).bind(i64::try_from(observation.revision.get()).map_err(|_|CoreStoreError::new(CoreStoreErrorKind::InvalidData))?)
|
||||
|
||||
@@ -449,7 +449,7 @@ async fn extrema_rebuild_reads_only_its_bucket_when_history_is_large() {
|
||||
}
|
||||
drain_analytics(&pool).await;
|
||||
// 只扩充其他时间桶的事实,规划器拿到真实行数后不能再为一个分组扫描全部历史
|
||||
sqlx::query("insert into request_analytics_facts select ('history_'||n)::text as id,(f.started_at-make_interval(hours=>n/1000+2))::timestamptz,f.completed_at-make_interval(hours=>n/1000+2),f.client_api_key_ref,f.provider_account_ref,f.routing_group_refs,f.operation,f.provider_kind,f.requested_model_id,f.upstream_model_id,f.outcome,f.client_status_code,f.upstream_status_code,f.client_transport,f.upstream_transport,f.attempt_count,null,null,null,f.recovered_at,f.downstream_committed_at,f.request_kind,f.image_generation_requested,f.image_generation_succeeded,f.error_kind,f.input_tokens,f.output_tokens,f.cached_input_tokens,f.cache_write_input_tokens,f.reasoning_output_tokens,f.image_input_tokens,f.image_output_tokens,f.total_tokens,f.cost_source,f.cost_currency,f.cost_amount,f.first_token_ms,f.latency_ms,f.admission_decision_ms,f.account_selection_wait_ms,f.upstream_response_ms,f.capacity_used_slots,f.capacity_total_slots,f.standard_cost_amount,f.no_cache_cost_amount,f.source_version,f.schema_version,f.ops_failure_count,f.ops_rate_limited_count,f.ops_auth_failure_count,f.ops_provider_5xx_count from request_analytics_facts f cross join generate_series(1,300000) n where f.id='rebuild_range_2'")
|
||||
sqlx::query("insert into request_analytics_facts select ('history_'||n)::text as id,(f.started_at-make_interval(hours=>n/1000+2))::timestamptz,f.completed_at-make_interval(hours=>n/1000+2),f.client_api_key_ref,f.provider_account_ref,f.routing_group_refs,f.operation,f.provider_kind,f.requested_model_id,f.upstream_model_id,f.outcome,f.client_status_code,f.upstream_status_code,f.client_transport,f.upstream_transport,f.attempt_count,null,null,null,f.recovered_at,f.downstream_committed_at,f.request_kind,f.image_generation_requested,f.image_generation_succeeded,f.error_kind,f.input_tokens,f.output_tokens,f.cached_input_tokens,f.cache_write_input_tokens,f.reasoning_output_tokens,f.image_input_tokens,f.image_output_tokens,f.total_tokens,f.cost_source,f.cost_currency,f.cost_amount,f.first_token_ms,f.latency_ms,f.admission_decision_ms,f.account_selection_wait_ms,f.upstream_response_ms,f.capacity_used_slots,f.capacity_total_slots,f.standard_cost_amount,f.no_cache_cost_amount,f.schema_version,f.ops_failure_count,f.ops_rate_limited_count,f.ops_auth_failure_count,f.ops_provider_5xx_count from request_analytics_facts f cross join generate_series(1,300000) n where f.id='rebuild_range_2'")
|
||||
.execute(&pool).await.unwrap();
|
||||
sqlx::query("analyze request_analytics_facts")
|
||||
.execute(&pool)
|
||||
|
||||
@@ -34,7 +34,7 @@ async fn business_backup_restores_core_state_and_usage_without_request_history()
|
||||
insert into client_api_key_budget_windows values('restore_key',now(),now()+interval '1 day',now(),now()+interval '7 days',2.5,9.5);
|
||||
insert into client_api_key_charge_events(request_id,client_api_key_id,amount_usd,completed_at) values('native_a','restore_key',2.5,now());
|
||||
insert into plugin_update_sources(plugin_id,source_json) values('backup.test','{}');
|
||||
insert into plugin_artifacts(sha256,plugin_id,version,metadata_json,source_json,archive,accepted_at) values(repeat('a',64),'backup.test','1.0.0','{}','{}',decode('010203','hex'),now());
|
||||
insert into plugin_artifacts(sha256,plugin_id,metadata_json,source_json,archive,accepted_at) values(repeat('a',64),'backup.test','{\"version\":\"1.0.0\"}','{}',decode('010203','hex'),now());
|
||||
update runtime_settings set usage_retention_days=3;
|
||||
update model_requests set cost_source='provider_reported',cost_amount=0.5,cost_currency='USD';
|
||||
insert into request_analytics_1h(bucket_start,collection,dimensions,outcome,schema_version,histogram_version,counts,costs,distributions)
|
||||
|
||||
@@ -261,6 +261,55 @@ async fn bulk_catalog_restore_keeps_ten_thousand_owners_and_fences_late_writes()
|
||||
.map(|a| a.id().as_str())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(ids, std::collections::BTreeSet::from(["acct_1", "acct_5"]));
|
||||
// 相同正文的复查仍更新账号观测,正文变化后单独恢复,迟到写入不能撤回新目录
|
||||
let refreshed = AccountCatalogObservation {
|
||||
account_id: ProviderAccountId::new("acct_5").unwrap(),
|
||||
observed_at: SystemTime::now(),
|
||||
etag: Some("v2".into()),
|
||||
..observation.clone()
|
||||
};
|
||||
assert!(
|
||||
repo.save_account_catalog(&refreshed, &document)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let restored = repo.load_account_catalogs(&provider).await.unwrap();
|
||||
assert_eq!(restored.len(), 1);
|
||||
let owner = restored[0]
|
||||
.accounts
|
||||
.iter()
|
||||
.find(|owner| owner.account_id == refreshed.account_id)
|
||||
.unwrap();
|
||||
assert_eq!(owner.etag, refreshed.etag);
|
||||
assert_eq!(
|
||||
chrono::DateTime::<Utc>::from(owner.observed_at).timestamp_micros(),
|
||||
chrono::DateTime::<Utc>::from(refreshed.observed_at).timestamp_micros()
|
||||
);
|
||||
assert_eq!(&restored[0].document[..], &document);
|
||||
let changed = AccountCatalogObservation {
|
||||
observed_at: SystemTime::now(),
|
||||
etag: Some("v3".into()),
|
||||
..refreshed.clone()
|
||||
};
|
||||
assert!(
|
||||
repo.save_account_catalog(&changed, b"changed")
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
!repo
|
||||
.save_account_catalog(&refreshed, &document)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let restored = repo.load_account_catalogs(&provider).await.unwrap();
|
||||
assert_eq!(restored.len(), 2);
|
||||
let changed_group = restored
|
||||
.iter()
|
||||
.find(|group| &group.document[..] == b"changed")
|
||||
.unwrap();
|
||||
assert_eq!(changed_group.accounts.len(), 1);
|
||||
assert_eq!(changed_group.accounts[0].account_id, changed.account_id);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
|
||||
@@ -49,3 +49,4 @@ e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_a
|
||||
44a24ba1bab7630881b4eeac66806231d3a7040dd72a99b0475e1a0f20cfc540 0049_client_key_validity_and_proxy_test_targets.sql
|
||||
c62495a0aff26b149381370fe1eea656091ab8d9d7d55aee27be4f56d5885fd3 0050_prompt_rewrite_rules.sql
|
||||
c4cc50c137deabae7895b97a8a8681c618f2b856276455d591475a02956ee373 0051_account_platform_icons.sql
|
||||
5911268734a4dddf099e747bdc684ef184b5861dd6fec0482c8da5f0eb35104c 0052_storage_write_efficiency.sql
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
-- 投影以源快照重算,精确版本确认由持久队列承担
|
||||
alter table request_analytics_facts drop column source_version;
|
||||
|
||||
-- 制品读取统一使用元数据版本,平台表继续约束同版本同平台的包身份
|
||||
alter table plugin_artifacts
|
||||
add constraint plugin_artifacts_metadata_version_ck check (
|
||||
metadata_json ? 'version'
|
||||
and jsonb_typeof(metadata_json->'version') = 'string'
|
||||
and length(metadata_json->>'version') between 1 and 128
|
||||
),
|
||||
drop column version;
|
||||
|
||||
-- 费用事件按请求去重、按 Key 和完成时间重算,复合索引覆盖现行读取
|
||||
drop index client_api_key_charge_events_client_api_key_id;
|
||||
|
||||
-- 删除制品时按摘要级联清理所有实例的历史配置
|
||||
create index plugin_version_configurations_artifact_sha256_idx
|
||||
on plugin_version_configurations (artifact_sha256);
|
||||
Reference in New Issue
Block a user