use crank_core::product_event::PRODUCT_EVENT_SERVER_IDEMPOTENCY_PREFIX; use crank_core::{ AgentId, InvocationLogId, OnboardingProjection, OnboardingStep, OnboardingStepId, OperationId, PRODUCT_EVENT_SCHEMA_VERSION, PlatformApiKeyId, ProductEvent, ProductEventKind, }; use sqlx::Row; use super::*; /// Bounded whole-transaction retries for transient PostgreSQL serialization /// failures. A `REPEATABLE READ` transaction that reads a row later updated by /// a concurrent transaction aborts with SQLSTATE `40001`; retrying from the /// start re-reads a consistent snapshot instead of continuing a partial, /// aborted transaction. const MAX_ONBOARDING_SERIALIZATION_ATTEMPTS: usize = 4; /// Whether a registry error is a transient PostgreSQL serialization/deadlock /// failure that must abort and retry the whole transaction. pub(super) fn is_onboarding_serialization_failure(error: &RegistryError) -> bool { matches!( error, RegistryError::Storage(sqlx::Error::Database(database)) if matches!(database.code().as_deref(), Some("40001") | Some("40P01")) ) } /// Begins an onboarding transaction with a true, consistent snapshot. /// /// The onboarding projection aggregates many relations and is paired with a /// separately-read durable import context; the default `READ COMMITTED` would /// let each statement see a different snapshot and pair a revision with newer /// choices. `REPEATABLE READ` fixes one snapshot for the whole transaction. pub(super) async fn begin_onboarding_transaction<'a>( pool: &'a sqlx::PgPool, ) -> Result, RegistryError> { let mut transaction = pool.begin().await?; sqlx::query("set transaction isolation level repeatable read") .execute(&mut *transaction) .await?; Ok(transaction) } const ONBOARDING_PROJECTION_SQL: &str = r#" with selection_state as ( select operation_id, operation_version, agent_id, catalog_revision, platform_api_key_id, invocation_log_id, test_log_id, evidence_after, selected_at from onboarding_selections where workspace_id = $1 ), import_selection as ( select application_idempotency_key, plan_digest, selected_operation_id, selected_operation_version, registered_at, selected_at from onboarding_import_selections where workspace_id = $1 ), operation_candidates as ( select o.id, o.current_draft_version, o.latest_published_version, o.updated_at, coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version, o.current_draft_version) as target_version, (o.status <> 'archived') as operation_active, exists ( select 1 from invocation_logs l where l.workspace_id = $1 and l.operation_id = o.id and l.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version, o.current_draft_version) and (ss.test_log_id is null or l.id = ss.test_log_id) and l.created_at >= coalesce(ss.evidence_after, '-infinity'::timestamptz) 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 ) as tested, exists ( select 1 from published_operations po where po.operation_id = o.id and po.version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version) ) as published, exists ( select 1 from agent_operation_bindings b join published_agents pa on pa.agent_id = b.agent_id and pa.version = b.agent_version join agents a on a.id = pa.agent_id where b.operation_id = o.id and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version) and (ss.agent_id is null or a.id = ss.agent_id) and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision) and b.enabled and a.workspace_id = $1 and a.status = 'published' and o.status <> 'archived' ) as published_agent, exists ( select 1 from agent_operation_bindings b join published_agents pa on pa.agent_id = b.agent_id and pa.version = b.agent_version join agents a on a.id = pa.agent_id join platform_api_keys k on k.workspace_id = $1 and k.agent_id = a.id where b.operation_id = o.id and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version) and (ss.agent_id is null or a.id = ss.agent_id) and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision) and (ss.platform_api_key_id is null or k.id = ss.platform_api_key_id) and b.enabled and a.workspace_id = $1 and a.status = 'published' and o.status <> 'archived' and k.key_kind = 'mcp_client' and k.status = 'active' and (k.expires_at is null or k.expires_at > now()) ) as active_key, exists ( select 1 from agent_operation_bindings b join published_agents pa on pa.agent_id = b.agent_id and pa.version = b.agent_version join agents a on a.id = pa.agent_id join platform_api_keys k on k.workspace_id = $1 and k.agent_id = a.id join invocation_logs l on l.workspace_id = $1 and l.agent_id = a.id and l.platform_api_key_id = k.id and l.operation_id = o.id and l.operation_version = b.operation_version where b.operation_id = o.id and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version) and (ss.agent_id is null or a.id = ss.agent_id) and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision) and (ss.platform_api_key_id is null or k.id = ss.platform_api_key_id) and b.enabled and a.workspace_id = $1 and a.status = 'published' and o.status <> 'archived' and k.key_kind = 'mcp_client' and k.status = 'active' and (k.expires_at is null or k.expires_at > now()) and l.source = 'agent_tool_call' 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 >= k.created_at and l.created_at >= pa.published_at and l.created_at >= coalesce(ss.evidence_after, '-infinity'::timestamptz) and (ss.invocation_log_id is null or l.id = ss.invocation_log_id) ) as first_call_complete , exists ( select 1 from agent_operation_bindings b join published_agents pa on pa.agent_id = b.agent_id and pa.version = b.agent_version join agents a on a.id = pa.agent_id join platform_api_keys k on k.workspace_id = $1 and k.agent_id = a.id join invocation_logs l on l.workspace_id = $1 and l.agent_id = a.id and l.platform_api_key_id = k.id and l.operation_id = o.id and l.operation_version = b.operation_version where b.operation_id = o.id and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version) and (ss.agent_id is null or a.id = ss.agent_id) and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision) and (ss.platform_api_key_id is null or k.id = ss.platform_api_key_id) and b.enabled and a.workspace_id = $1 and k.key_kind = 'mcp_client' and l.source = 'agent_tool_call' 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 >= k.created_at and l.created_at >= pa.published_at and l.created_at >= coalesce(ss.evidence_after, '-infinity'::timestamptz) and (ss.invocation_log_id is null or l.id = ss.invocation_log_id) ) as historical_first_call from operations o left join selection_state ss on true left join import_selection imp on true where o.workspace_id = $1 and (ss.operation_id is null or o.id = ss.operation_id) and ( ss.operation_id is not null or (imp.selected_operation_id is not null and o.id = imp.selected_operation_id) or (imp.selected_operation_id is null and not exists (select 1 from import_selection)) ) ), selected_operation as ( select o.id, o.current_draft_version, o.latest_published_version, o.updated_at, o.target_version, o.operation_active from operation_candidates o order by o.historical_first_call desc, o.operation_active desc, o.first_call_complete desc, o.active_key desc, o.published_agent desc, o.published desc, o.tested desc, o.updated_at desc, o.id limit 1 ), operation_state as ( select so.*, (so.operation_active and exists ( select 1 from invocation_logs l where l.workspace_id = $1 and l.operation_id = so.id and l.operation_version = so.target_version and l.created_at >= coalesce((select evidence_after from selection_state), '-infinity'::timestamptz) and ((select test_log_id from selection_state) is null or l.id = (select test_log_id from selection_state)) 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 )) as tested, (so.operation_active and so.current_draft_version = so.target_version and po.operation_id is not null and po.version = so.target_version) as published, po.version as published_version from selected_operation so left join published_operations po on po.operation_id = so.id and po.version = so.target_version ), agent_candidates as ( select a.id, pa.catalog_revision, pa.published_at as agent_published_at, a.updated_at, b.operation_id, b.operation_version, os.operation_active, (os.published and a.status = 'published') as agent_active, exists ( select 1 from platform_api_keys k where k.workspace_id = $1 and k.agent_id = a.id and os.operation_active and a.status = 'published' and k.key_kind = 'mcp_client' and k.status = 'active' and (k.expires_at is null or k.expires_at > now()) ) as active_key, exists ( select 1 from platform_api_keys k join invocation_logs l on l.workspace_id = $1 and l.agent_id = a.id and l.platform_api_key_id = k.id and l.operation_id = b.operation_id and l.operation_version = b.operation_version where k.workspace_id = $1 and k.agent_id = a.id and os.operation_active and a.status = 'published' and k.key_kind = 'mcp_client' and k.status = 'active' and (k.expires_at is null or k.expires_at > now()) and l.source = 'agent_tool_call' 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 >= k.created_at and l.created_at >= pa.published_at ) as first_call_complete , exists ( select 1 from platform_api_keys k join invocation_logs l on l.workspace_id = $1 and l.agent_id = a.id and l.platform_api_key_id = k.id and l.operation_id = b.operation_id and l.operation_version = b.operation_version where k.workspace_id = $1 and k.agent_id = a.id and k.key_kind = 'mcp_client' and l.source = 'agent_tool_call' 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 >= k.created_at and l.created_at >= pa.published_at ) as historical_first_call from operation_state os join agent_operation_bindings b on b.operation_id = os.id and b.operation_version = os.published_version and b.enabled join published_agents pa on pa.agent_id = b.agent_id and pa.version = b.agent_version join agents a on a.id = pa.agent_id where a.workspace_id = $1 and ((select agent_id from selection_state) is null or a.id = (select agent_id from selection_state)) and ((select catalog_revision from selection_state) is null or pa.catalog_revision = (select catalog_revision from selection_state)) ), selected_agent as ( select id, catalog_revision, agent_published_at, updated_at, operation_id, operation_version, operation_active, agent_active from agent_candidates order by historical_first_call desc, agent_active desc, first_call_complete desc, active_key desc, updated_at desc, id limit 1 ), key_candidates as ( select k.id, k.agent_id, k.last_used_at, k.created_at, k.expires_at, k.status, (sa.agent_active and k.status = 'active' and (k.expires_at is null or k.expires_at > now())) as key_active, exists ( select 1 from invocation_logs l where l.workspace_id = $1 and l.agent_id = sa.id and l.platform_api_key_id = k.id and l.operation_id = sa.operation_id and l.operation_version = sa.operation_version and l.source = 'agent_tool_call' 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 >= k.created_at and l.created_at >= sa.agent_published_at ) as first_call_complete from selected_agent sa join platform_api_keys k on k.workspace_id = $1 and k.agent_id = sa.id where k.key_kind = 'mcp_client' and ((select platform_api_key_id from selection_state) is null or k.id = (select platform_api_key_id from selection_state)) ), selected_key as ( select id, agent_id, last_used_at, created_at, expires_at, status, key_active from key_candidates order by first_call_complete desc, key_active desc, (last_used_at is not null) desc, created_at desc, id limit 1 ), first_call as ( select l.id, l.tool_name, l.created_at, l.request_id, l.trace_id from selected_agent sa join selected_key sk on sk.agent_id = sa.id join invocation_logs l on l.workspace_id = $1 and l.agent_id = sa.id and l.platform_api_key_id = sk.id and l.operation_id = sa.operation_id and l.operation_version = sa.operation_version where l.source = 'agent_tool_call' and l.status = 'ok' and sk.key_active and l.execution_stage = 'runtime' and l.outcome_certainty = 'certain' and l.execution_error_code is null and l.created_at >= sk.created_at and l.created_at >= sa.agent_published_at and l.created_at >= coalesce((select evidence_after from selection_state), '-infinity'::timestamptz) and ((select invocation_log_id from selection_state) is null or l.id = (select invocation_log_id from selection_state)) order by l.created_at, l.id limit 1 ), event_state as ( select count(*)::bigint as event_count, max(occurred_at) as last_event_at, max(id) as last_event_id, coalesce(bool_or(event_name = 'onboarding_completed'), false) as was_completed, min((properties_json ->> 'eligible_since')::timestamptz) filter (where event_name = 'onboarding_eligible') as eligible_since from product_events where workspace_id = $1 ) select os.id as operation_id, os.operation_active, os.tested, os.published, os.published_version, sa.id as agent_id, sa.agent_active, sa.catalog_revision, sk.id as platform_api_key_id, (sk.key_active and sk.last_used_at is not null) as connected, sk.key_active, fc.id as first_call_log_id, fc.tool_name as first_call_tool_name, fc.created_at as first_call_at, fc.request_id as first_call_request_id, fc.trace_id as first_call_trace_id, es.eligible_since, es.was_completed, (hashtextextended(concat_ws('|', coalesce(os.id, ''), coalesce(os.updated_at::text, ''), coalesce(os.tested::text, ''), coalesce(os.published_version::text, ''), coalesce(sa.id, ''), coalesce(sa.catalog_revision::text, ''), coalesce(sa.updated_at::text, ''), coalesce(sk.id, ''), coalesce(sk.status, ''), coalesce(sk.last_used_at::text, ''), coalesce(sk.expires_at::text, ''), coalesce(sk.key_active::text, ''), coalesce(fc.id, ''), coalesce(es.event_count::text, ''), coalesce(es.last_event_at::text, ''), coalesce(es.last_event_id, ''), coalesce((select evidence_after::text from selection_state), ''), coalesce((select selected_at::text from selection_state), ''), coalesce((select application_idempotency_key from import_selection), ''), coalesce((select plan_digest from import_selection), ''), coalesce((select selected_operation_id from import_selection), ''), coalesce((select selected_operation_version::text from import_selection), ''), coalesce((select registered_at::text from import_selection), ''), coalesce((select selected_at::text from import_selection), ''), coalesce((select o.current_draft_version::text from operations o where o.workspace_id = $1 and o.id = (select selected_operation_id from import_selection)), ''), coalesce(( select string_agg( candidate.operation_id || ':' || coalesce(o.status, 'missing') || ':' || coalesce(o.current_draft_version::text, 'null'), ',' order by candidate.operation_id ) from ( select distinct outcome ->> 'operation_id' as operation_id from import_plan_applications a cross join lateral jsonb_array_elements(a.report -> 'outcomes') as outcome where a.workspace_id = $1 and a.idempotency_key = ( select application_idempotency_key from import_selection ) and a.plan_digest = (select plan_digest from import_selection) and outcome ->> 'outcome' in ('created', 'versioned', 'renamed') and outcome ->> 'operation_id' is not null ) candidate left join operations o on o.workspace_id = $1 and o.id = candidate.operation_id ), '') ), 0) & 9007199254740991) as revision from event_state es left join operation_state os on true left join selected_agent sa on true left join selected_key sk on true left join first_call fc on true "#; impl PostgresRegistry { /// Retries a whole onboarding transaction on transient serialization /// failures. Each attempt starts from scratch, so an aborted transaction is /// never continued partially. Exhausted retries surface as a truthful /// revision conflict so the client reloads and revalidates. pub(super) async fn with_onboarding_retry( &self, mut operation: F, ) -> Result where F: FnMut() -> Fut, Fut: std::future::Future>, { let mut attempt = 0; loop { match operation().await { Err(error) if is_onboarding_serialization_failure(&error) => { attempt += 1; if attempt >= MAX_ONBOARDING_SERIALIZATION_ATTEMPTS { return Err(RegistryError::OnboardingStaleRevision); } } result => return result, } } } /// Ensures the workspace enters the server-owned onboarding cohort exactly once. pub async fn ensure_onboarding_eligibility( &self, workspace_id: &WorkspaceId, occurred_at: OffsetDateTime, ) -> Result { Ok(self .ensure_onboarding_eligibility_snapshot(workspace_id, occurred_at) .await? .projection) } /// Ensures eligibility and returns the authoritative projection together /// with the durable import context from the same locked transaction. pub async fn ensure_onboarding_eligibility_snapshot( &self, workspace_id: &WorkspaceId, occurred_at: OffsetDateTime, ) -> Result { self.with_onboarding_retry(|| async { let mut transaction = begin_onboarding_transaction(&self.pool).await?; lock_onboarding_workspace(&mut transaction, workspace_id).await?; let eligible_since = ensure_onboarding_eligible_in_transaction( &mut transaction, workspace_id, occurred_at, ) .await?; super::onboarding_import::record_import_funnel_milestones_in_transaction( &mut transaction, workspace_id, occurred_at, ) .await?; let mut projection = get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?; if projection.completed && !projection.was_completed { let event = ProductEvent { id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())), workspace_id: workspace_id.clone(), kind: ProductEventKind::OnboardingCompleted, schema_version: PRODUCT_EVENT_SCHEMA_VERSION, milestone: None, eligible: true, eligible_since: Some(eligible_since), idempotency_key: "onboarding:completed:v1".to_owned(), occurred_at: projection.first_call_at.unwrap_or(occurred_at), }; super::product_event::append_product_event_in_transaction(&mut transaction, &event) .await?; projection = get_onboarding_projection_in_transaction(&mut transaction, workspace_id) .await?; } let import_context = super::onboarding_import::get_onboarding_import_context_in_transaction( &mut transaction, workspace_id, ) .await?; transaction.commit().await?; Ok(OnboardingSnapshot { projection, import_context, }) }) .await } /// Records the server-owned completion once the authoritative projection is terminal. pub async fn ensure_onboarding_completion( &self, workspace_id: &WorkspaceId, _occurred_at: OffsetDateTime, ) -> Result { self.with_onboarding_retry(|| async { let mut transaction = begin_onboarding_transaction(&self.pool).await?; lock_onboarding_workspace(&mut transaction, workspace_id).await?; let projection = get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?; if !projection.completed { transaction.commit().await?; return Ok(projection); } let Some(eligible_since) = projection.eligible_since else { transaction.commit().await?; return Ok(projection); }; let event = ProductEvent { id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())), workspace_id: workspace_id.clone(), kind: ProductEventKind::OnboardingCompleted, schema_version: PRODUCT_EVENT_SCHEMA_VERSION, milestone: None, eligible: true, eligible_since: Some(eligible_since), idempotency_key: "onboarding:completed:v1".to_owned(), occurred_at: projection.first_call_at.ok_or( RegistryError::InvalidExecutionRecord { field: "onboarding.first_call_at", }, )?, }; super::product_event::append_product_event_in_transaction(&mut transaction, &event) .await?; let projection = get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?; transaction.commit().await?; Ok(projection) }) .await } pub async fn get_onboarding_projection( &self, workspace_id: &WorkspaceId, ) -> Result { let row = sqlx::query(ONBOARDING_PROJECTION_SQL) .bind(workspace_id.as_str()) .fetch_one(&self.pool) .await?; map_projection(workspace_id, &row) } /// Reads the authoritative projection and the durable import context from /// one workspace-locked transaction so revision and context cannot diverge. pub async fn get_onboarding_snapshot( &self, workspace_id: &WorkspaceId, ) -> Result { self.with_onboarding_retry(|| async { let mut transaction = begin_onboarding_transaction(&self.pool).await?; lock_onboarding_workspace(&mut transaction, workspace_id).await?; let snapshot = get_onboarding_snapshot_in_transaction(&mut transaction, workspace_id).await?; transaction.commit().await?; Ok(snapshot) }) .await } pub async fn reset_onboarding_selection( &self, workspace_id: &WorkspaceId, expected_revision: i64, occurred_at: OffsetDateTime, ) -> Result { Ok(self .reset_onboarding_selection_snapshot(workspace_id, expected_revision, occurred_at) .await? .projection) } /// Resets the terminal/import selection and returns the resulting /// projection with its (now absent) import context from one snapshot. pub async fn reset_onboarding_selection_snapshot( &self, workspace_id: &WorkspaceId, expected_revision: i64, occurred_at: OffsetDateTime, ) -> Result { self.with_onboarding_retry(|| async { let mut transaction = begin_onboarding_transaction(&self.pool).await?; lock_onboarding_workspace(&mut transaction, workspace_id).await?; let current = get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?; if current.revision != expected_revision { return Err(RegistryError::OnboardingStaleRevision); } 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 ) values ($1, null, null, null, null, null, null, null, $2, null) on conflict (workspace_id) do update set operation_id = null, operation_version = null, agent_id = null, catalog_revision = null, platform_api_key_id = null, invocation_log_id = null, test_log_id = null, evidence_after = excluded.evidence_after, selected_at = null", ) .bind(workspace_id.as_str()) .bind(occurred_at) .execute(&mut *transaction) .await?; // Reset clears the durable import context as well, but keeps the // existing evidence boundary (evidence_after) intact. sqlx::query("delete from onboarding_import_selections where workspace_id = $1") .bind(workspace_id.as_str()) .execute(&mut *transaction) .await?; let projection = get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?; let import_context = super::onboarding_import::get_onboarding_import_context_in_transaction( &mut transaction, workspace_id, ) .await?; transaction.commit().await?; Ok(OnboardingSnapshot { projection, import_context, }) }) .await } pub async fn record_onboarding_milestone( &self, request: RecordOnboardingMilestoneRequest<'_>, ) -> Result { let snapshot = self.record_onboarding_milestone_snapshot(request).await?; Ok(OnboardingMilestoneResult { accepted: snapshot.accepted, projection: snapshot.snapshot.projection, }) } /// Records a presentation milestone and returns the projection and import /// context read from the same transaction, avoiding a post-mutation pool /// read that could pair the revision with a newer context. pub async fn record_onboarding_milestone_snapshot( &self, request: RecordOnboardingMilestoneRequest<'_>, ) -> Result { let kind = match request.milestone { OnboardingPresentationMilestone::Eligible => ProductEventKind::OnboardingEligible, OnboardingPresentationMilestone::Started => ProductEventKind::OnboardingStarted, OnboardingPresentationMilestone::Resumed => ProductEventKind::OnboardingResumed, OnboardingPresentationMilestone::Dismissed => ProductEventKind::OnboardingDismissed, OnboardingPresentationMilestone::Abandoned => ProductEventKind::OnboardingAbandoned, }; self.record_onboarding_event_snapshot( request.workspace_id, request.event_id, kind, request.idempotency_key, request.expected_revision, request.occurred_at, request.eligible_since, ) .await } pub async fn record_onboarding_completion( &self, request: RecordOnboardingCompletionRequest<'_>, ) -> Result { let snapshot = self.record_onboarding_completion_snapshot(request).await?; Ok(OnboardingMilestoneResult { accepted: snapshot.accepted, projection: snapshot.snapshot.projection, }) } /// Records the authoritative completion and returns the projection and /// import context from the same transaction. pub async fn record_onboarding_completion_snapshot( &self, request: RecordOnboardingCompletionRequest<'_>, ) -> Result { self.record_onboarding_event_snapshot( request.workspace_id, request.event_id, ProductEventKind::OnboardingCompleted, request.idempotency_key, request.expected_revision, request.occurred_at, Some(request.eligible_since), ) .await } #[allow(clippy::too_many_arguments)] async fn record_onboarding_event_snapshot( &self, workspace_id: &WorkspaceId, event_id: &ProductEventId, kind: ProductEventKind, idempotency_key: &str, expected_revision: i64, occurred_at: OffsetDateTime, eligible_since: Option, ) -> Result { if idempotency_key.starts_with(PRODUCT_EVENT_SERVER_IDEMPOTENCY_PREFIX) { return Err(RegistryError::InvalidExecutionRecord { field: "product_event.reserved_idempotency_key", }); } self.with_onboarding_retry(|| async { let mut transaction = begin_onboarding_transaction(&self.pool).await?; lock_onboarding_workspace(&mut transaction, workspace_id).await?; let current = get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?; if kind == ProductEventKind::OnboardingCompleted && !current.completed { return Err(RegistryError::OnboardingIncomplete); } let event = ProductEvent { id: event_id.clone(), workspace_id: workspace_id.clone(), kind, schema_version: PRODUCT_EVENT_SCHEMA_VERSION, milestone: None, eligible: eligible_since.is_some(), eligible_since, idempotency_key: idempotency_key.to_owned(), occurred_at, }; if current.revision != expected_revision { let replay = super::product_event::get_product_event_by_idempotency_key_in_transaction( &mut transaction, workspace_id, idempotency_key, ) .await?; if replay.is_some_and(|record| event.is_semantic_replay_of(&record.event)) { let import_context = super::onboarding_import::get_onboarding_import_context_in_transaction( &mut transaction, workspace_id, ) .await?; transaction.commit().await?; return Ok(OnboardingEventSnapshot { accepted: false, snapshot: OnboardingSnapshot { projection: current, import_context, }, }); } return Err(RegistryError::OnboardingStaleRevision); } let outcome = super::product_event::append_product_event_in_transaction(&mut transaction, &event) .await?; let projection = get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?; let import_context = super::onboarding_import::get_onboarding_import_context_in_transaction( &mut transaction, workspace_id, ) .await?; transaction.commit().await?; Ok(OnboardingEventSnapshot { accepted: outcome == AppendProductEventOutcome::Recorded, snapshot: OnboardingSnapshot { projection, import_context, }, }) }) .await } } /// Ensures the workspace is in the server-owned onboarding eligible cohort and /// returns its authoritative `eligible_since` timestamp. Idempotent: the /// cohort event is created at most once per workspace. pub(super) async fn ensure_onboarding_eligible_in_transaction( transaction: &mut Transaction<'_, Postgres>, workspace_id: &WorkspaceId, occurred_at: OffsetDateTime, ) -> Result { let eligible = super::product_event::get_product_event_by_idempotency_key_in_transaction( transaction, workspace_id, "onboarding:eligible:v1", ) .await?; if let Some(record) = eligible { return Ok(record.event.eligible_since.unwrap_or(occurred_at)); } let event = ProductEvent { id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())), workspace_id: workspace_id.clone(), kind: ProductEventKind::OnboardingEligible, schema_version: PRODUCT_EVENT_SCHEMA_VERSION, milestone: None, eligible: true, eligible_since: Some(occurred_at), idempotency_key: "onboarding:eligible:v1".to_owned(), occurred_at, }; super::product_event::append_product_event_in_transaction(transaction, &event).await?; Ok(occurred_at) } pub(super) async fn lock_onboarding_workspace( transaction: &mut Transaction<'_, Postgres>, workspace_id: &WorkspaceId, ) -> Result<(), RegistryError> { let present = sqlx::query("select id from workspaces where id = $1 for update") .bind(workspace_id.as_str()) .fetch_optional(&mut **transaction) .await? .is_some(); if !present { return Err(RegistryError::WorkspaceNotFound { workspace_id: workspace_id.as_str().to_owned(), }); } Ok(()) } pub(super) async fn get_onboarding_projection_in_transaction( transaction: &mut Transaction<'_, Postgres>, workspace_id: &WorkspaceId, ) -> Result { let row = sqlx::query(ONBOARDING_PROJECTION_SQL) .bind(workspace_id.as_str()) .fetch_one(&mut **transaction) .await?; map_projection(workspace_id, &row) } pub(super) async fn get_onboarding_snapshot_in_transaction( transaction: &mut Transaction<'_, Postgres>, workspace_id: &WorkspaceId, ) -> Result { let projection = get_onboarding_projection_in_transaction(transaction, workspace_id).await?; let import_context = super::onboarding_import::get_onboarding_import_context_in_transaction( transaction, workspace_id, ) .await?; Ok(OnboardingSnapshot { projection, import_context, }) } fn map_projection( workspace_id: &WorkspaceId, row: &sqlx::postgres::PgRow, ) -> Result { let operation_id = row .try_get::, _>("operation_id")? .map(OperationId::new); let operation_active = row .try_get::, _>("operation_active")? .unwrap_or(false); let tested = row.try_get::, _>("tested")?.unwrap_or(false); let published = row .try_get::, _>("published")? .unwrap_or(false); let agent_id = row .try_get::, _>("agent_id")? .map(AgentId::new); let agent_active = row .try_get::, _>("agent_active")? .unwrap_or(false); let key_id = row .try_get::, _>("platform_api_key_id")? .map(PlatformApiKeyId::new); let key_active = row .try_get::, _>("key_active")? .unwrap_or(false); let connected = row .try_get::, _>("connected")? .unwrap_or(false); let first_call_log_id = row .try_get::, _>("first_call_log_id")? .map(InvocationLogId::new); let flags = [ operation_id.is_some() && operation_active, tested, published, agent_id.is_some() && agent_active, key_id.is_some() && key_active, connected, first_call_log_id.is_some(), ]; Ok(OnboardingProjection { workspace_id: workspace_id.clone(), revision: row.try_get("revision")?, completed: flags.into_iter().all(|flag| flag), was_completed: row.try_get("was_completed")?, steps: OnboardingStepId::ORDERED .into_iter() .zip(flags) .map(|(id, completed)| OnboardingStep { id, completed }) .collect(), operation_id, operation_version: row .try_get::, _>("published_version")? .map(|value| { u32::try_from(value).map_err(|_| RegistryError::InvalidNumericValue { field: "onboarding.operation_version", value: i64::from(value), }) }) .transpose()?, agent_id, catalog_revision: row.try_get("catalog_revision")?, platform_api_key_id: key_id, first_call_log_id, first_call_tool_name: row.try_get("first_call_tool_name")?, first_call_at: row.try_get("first_call_at")?, first_call_request_id: row.try_get("first_call_request_id")?, first_call_trace_id: row.try_get("first_call_trace_id")?, eligible_since: row.try_get("eligible_since")?, }) }