From fbf2cebfa012a7c92b08af7bfa0340177308b2a6 Mon Sep 17 00:00:00 2001 From: DarkSky <25152247+darkskygit@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:20:44 +0800 Subject: [PATCH] fix(server): data migration (#15730) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #### PR Dependency Tree * **PR #15730** 👈 This tree was auto-generated by [Charcoal](https://github.com/danerwilliams/charcoal) ## Summary by CodeRabbit * **Bug Fixes** * Payment records missing provider or source identity now require repair instead of being automatically adopted or matched through legacy identifiers. * RevenueCat subscription confirmation checks for expected subscription identities, and subscription entitlements include provider and recurrence details. * Pending uploads with missing expiration dates remain pending during cutover rather than being marked deleted. * **Improvements** * Embedding projections are refreshed when source content or revision details change, with updated processing order. --- .../runtime/backend_runtime/payment/apply.rs | 27 +- .../payment/command/catalog.rs | 2 +- .../backend_runtime/payment/command/mod.rs | 2 +- .../backend_runtime/payment/command/portal.rs | 2 +- .../payment/command/revenuecat.rs | 39 +-- .../runtime/backend_runtime/payment/mod.rs | 7 +- .../backend_runtime/payment/projection.rs | 19 +- .../runtime/backend_runtime/payment/read.rs | 55 ++-- .../backend_runtime/payment/snapshot.rs | 10 +- .../runtime/backend_runtime/payment/tests.rs | 259 +++++++++------ .../runtime/backend_runtime/payment/write.rs | 120 ++----- .../backend/native/src/runtime/migrations.rs | 301 +++++++++++++++++- .../native/src/runtime/sql/embedding.sql | 20 +- .../native/src/runtime/sql/embedding_v2.sql | 24 ++ .../__snapshots__/migrations.spec.ts.md | 19 +- .../__snapshots__/migrations.spec.ts.snap | Bin 1431 -> 1345 bytes .../src/data/__tests__/migrations.spec.ts | 82 +++-- .../server/src/data/commands/cutover.ts | 42 +-- 18 files changed, 626 insertions(+), 404 deletions(-) create mode 100644 packages/backend/native/src/runtime/sql/embedding_v2.sql diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/apply.rs b/packages/backend/native/src/runtime/backend_runtime/payment/apply.rs index ed6e4f75b2..c7dfe3431f 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/apply.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/apply.rs @@ -10,11 +10,11 @@ use super::{ RuntimeError, RuntimeResult, entitlement::{RuntimeEntitlementTarget, apply_transitions, load_decision_time, lock_targets, transition_before}, }, - PaymentConnection, PaymentScope, PaymentSnapshot, ReceiptDisposition, SnapshotCoverage, adopt_legacy_entitlement, - complete_receipts_and_operation, discover_payment_scopes, entitlement_subject, expire_missing_sources, - load_financial_restrictions, lock_receipts_and_operation, lock_subscription_rows, required_scope_expansion, - reserve_snapshot_mails, reserve_workspace_upgrade_mails, upsert_customers, upsert_financial_facts, upsert_invoices, - upsert_licenses, upsert_subscription, upsert_trials, + PaymentConnection, PaymentScope, PaymentSnapshot, ReceiptDisposition, SnapshotCoverage, + complete_receipts_and_operation, discover_payment_scopes, expire_missing_sources, load_financial_restrictions, + lock_receipts_and_operation, lock_subscription_rows, required_scope_expansion, reserve_snapshot_mails, + reserve_workspace_upgrade_mails, upsert_customers, upsert_financial_facts, upsert_invoices, upsert_licenses, + upsert_subscription, upsert_trials, }; use crate::runtime::Deployment; @@ -155,23 +155,9 @@ pub(super) async fn apply_payment_snapshot( now, ) .await?; - let entitlement_subject = entitlement_subject(&namespace, &subscription.source_id); - let target = RuntimeEntitlementTarget { - target_type: subscription.target_type.clone(), - target_id: subscription.target_id.clone(), - }; - adopt_legacy_entitlement( - &mut tx, - &subscription.source_id, - &entitlement_subject, - &namespace, - &target, - now, - ) - .await?; } - expire_missing_sources(&mut tx, &snapshot, &namespace, &stored, now).await?; + expire_missing_sources(&mut tx, &snapshot, &stored, now).await?; upsert_trials(&mut tx, &snapshot, &namespace, now).await?; upsert_invoices(&mut tx, &snapshot, &namespace, now).await?; upsert_licenses(&mut tx, &snapshot, now).await?; @@ -275,6 +261,7 @@ fn validate_snapshot(snapshot: &PaymentSnapshot) -> RuntimeResult<()> { || subscription.external_ref.is_none() || subscription.external_product_id.is_none() || subscription.external_customer_id.is_none() + || subscription.external_subscription_id.as_deref() != Some(subscription.source_id.as_str()) || subscription.external_ref.as_deref() == Some(subscription.source_id.as_str()) => { return Err(RuntimeError::invalid_input( diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/catalog.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/catalog.rs index 082971d4e5..91338ba47b 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/catalog.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/catalog.rs @@ -197,7 +197,7 @@ impl PaymentRuntime { ) -> RuntimeResult { validate_identity(user_id, "payment user")?; let namespace_key = canonical_namespace(namespace)?; - if let Some(customer_id) = load_or_adopt_stripe_customer(&self.pool, user_id, &namespace_key).await? { + if let Some(customer_id) = load_stripe_customer(&self.pool, user_id, &namespace_key).await? { return Ok(customer_id); } let email = email diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/mod.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/mod.rs index 9c5102250b..562acba377 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/mod.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/mod.rs @@ -27,7 +27,7 @@ use sqlx::Row; use super::{ CustomerSnapshot, OperationCompletion, OperationIntent, PaymentConnection, PaymentFormField, PaymentFormValue, PaymentRuntime, PaymentScope, PaymentSendDecision, PaymentSnapshot, PaymentStep, PaymentStepState, SnapshotCoverage, - TrialSnapshot, freeze_operation, load_or_adopt_stripe_customer, mark_operation_step_sent, record_operation_error, + TrialSnapshot, freeze_operation, load_stripe_customer, mark_operation_step_sent, record_operation_error, record_operation_step_result, snapshot::parse_lookup_key, stripe_client::{ diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/portal.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/portal.rs index a5afe044d9..5219893da9 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/portal.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/portal.rs @@ -8,7 +8,7 @@ impl PaymentRuntime { validate_identity(actor_user_id, "payment actor")?; let stripe = self.stripe()?; let namespace_key = canonical_namespace(stripe.namespace())?; - let customer_id = load_or_adopt_stripe_customer(&self.pool, actor_user_id, &namespace_key) + let customer_id = load_stripe_customer(&self.pool, actor_user_id, &namespace_key) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_customer_not_found"))?; let mut form = StripeForm::default(); diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/revenuecat.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/revenuecat.rs index 11d604e421..21880bdf50 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/revenuecat.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/revenuecat.rs @@ -29,27 +29,6 @@ impl PaymentRuntime { .revenuecat_config .as_ref() .ok_or_else(|| RuntimeError::invalid_state("RevenueCat payment provider is not configured"))?; - let namespace = client - .namespace() - .canonical_key() - .map_err(|_| RuntimeError::invalid_state("invalid RevenueCat provider namespace"))?; - if let Some(row) = sqlx::query( - "SELECT target_id FROM provider_subscriptions WHERE provider='revenuecat' AND provider_namespace=$1 AND \ - external_ref=$2 ORDER BY id LIMIT 1", - ) - .bind(&namespace) - .bind(transaction_id) - .fetch_optional(&self.pool) - .await - .map_err(|error| RuntimeError::database("load RevenueCat store transaction", error))? - { - if row.get::("target_id") != user_id { - return Err(RuntimeError::invalid_state( - "RevenueCat store transaction belongs to another user", - )); - } - return self.list_subscriptions("user", user_id).await; - } let subscriptions = client .subscriptions_by_store_id(transaction_id) .await @@ -57,14 +36,6 @@ impl PaymentRuntime { if subscriptions.is_empty() { return self.list_subscriptions("user", user_id).await; } - if subscriptions - .iter() - .any(|subscription| subscription.store_subscription_identifier != transaction_id) - { - return Err(RuntimeError::invalid_state( - "RevenueCat store transaction result is not canonical", - )); - } let source_customers = subscriptions .iter() .map(|subscription| subscription.customer_id.as_deref()) @@ -182,7 +153,7 @@ impl PaymentRuntime { return Err(RuntimeError::invalid_state("payment_operation_blocked")); } if let Some(snapshot) = self - .confirmed_revenuecat_identify(user_id, transaction_id, &source_ids, &frozen.id) + .confirmed_revenuecat_identify(user_id, &source_ids, &frozen.id) .await? { return self @@ -220,7 +191,7 @@ impl PaymentRuntime { ) .await?; let Some(snapshot) = self - .confirmed_revenuecat_identify(user_id, transaction_id, &source_ids, &frozen.id) + .confirmed_revenuecat_identify(user_id, &source_ids, &frozen.id) .await? else { return Ok(IdentifyOutcome::Pending); @@ -234,7 +205,6 @@ impl PaymentRuntime { async fn confirmed_revenuecat_identify( &self, user_id: &str, - transaction_id: &str, expected_source_ids: &[String], operation_id: &str, ) -> RuntimeResult> { @@ -252,7 +222,6 @@ impl PaymentRuntime { .map_err(provider_runtime_error)?; let present = subscriptions .iter() - .filter(|subscription| subscription.store_subscription_identifier == transaction_id) .map(|subscription| subscription.id.as_str()) .collect::>(); if expected_source_ids @@ -322,7 +291,7 @@ pub(in crate::runtime::backend_runtime::payment) async fn recover_one_revenuecat source_customer_id: _, customer_id, source_ids, - store_subscription_identifier, + store_subscription_identifier: _, } = &step.request else { return Err(RuntimeError::invalid_state("RevenueCat identify operation is invalid")); @@ -339,7 +308,7 @@ pub(in crate::runtime::backend_runtime::payment) async fn recover_one_revenuecat return Ok(None); }; if let Some(snapshot) = runtime - .confirmed_revenuecat_identify(customer_id, store_subscription_identifier, source_ids, &operation_id) + .confirmed_revenuecat_identify(customer_id, source_ids, &operation_id) .await? { return runtime.apply_with_connection(connection, snapshot).await.map(Some); diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/mod.rs b/packages/backend/native/src/runtime/backend_runtime/payment/mod.rs index efc4c92bb8..0e7b69b663 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/mod.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/mod.rs @@ -27,6 +27,8 @@ use operation::FrozenOperation; use operation::{ PaymentSendDecision, freeze_operation, mark_operation_step_sent, record_operation_error, record_operation_step_result, }; +#[cfg(test)] +use projection::entitlement_subject; use projection::reconcile_cloud_winners; use read::{ ReceiptDisposition, StoredSubscription, discover_payment_scopes, load_financial_restrictions, @@ -41,9 +43,8 @@ use stripe_snapshot::{push_stripe_dispute, push_stripe_refund, stripe_invoice_sn use types::*; use worker::PaymentWorker; use write::{ - adopt_legacy_entitlement, complete_receipts_and_operation, entitlement_subject, expire_missing_sources, - load_or_adopt_stripe_customer, upsert_customers, upsert_financial_facts, upsert_invoices, upsert_licenses, - upsert_subscription, upsert_trials, + complete_receipts_and_operation, expire_missing_sources, load_stripe_customer, upsert_customers, + upsert_financial_facts, upsert_invoices, upsert_licenses, upsert_subscription, upsert_trials, }; #[cfg(test)] diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/projection.rs b/packages/backend/native/src/runtime/backend_runtime/payment/projection.rs index 49ce8e3b38..1281fd7525 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/projection.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/projection.rs @@ -17,7 +17,6 @@ use super::{ entitlement::{EntitlementWrite, RuntimeEntitlementTarget, upsert}, }, apply::restriction_name, - entitlement_subject, }; struct ProjectedSource { @@ -25,6 +24,9 @@ struct ProjectedSource { namespace: String, target: RuntimeEntitlementTarget, starts_at: Option>, + recurring: SubscriptionRecurring, + variant: serde_json::Value, + external_subscription_id: Option, candidate: CloudSourceCandidate, } @@ -45,7 +47,7 @@ pub(super) async fn reconcile_cloud_winners( .collect::>(); let rows = sqlx::query( r#"SELECT id,provider::text AS provider,provider_namespace,source_identity,target_type,target_id, - plan,recurring,status,gives_access,quantity,trial_end,period_start,period_end,will_renew + plan,recurring,status,gives_access,quantity,trial_end,period_start,period_end,will_renew,external_subscription_id,metadata->'variant' AS variant FROM provider_subscriptions WHERE provider_namespace IS NOT NULL AND source_identity IS NOT NULL AND ((target_type='user' AND target_id=ANY($1) AND plan IN ('pro','lifetime_pro','ai')) @@ -142,6 +144,11 @@ pub(super) async fn reconcile_cloud_winners( namespace: namespace.clone(), target: target.clone(), starts_at: row.get("period_start"), + recurring, + variant: row + .get::, _>("variant") + .unwrap_or(serde_json::Value::Null), + external_subscription_id: row.get("external_subscription_id"), candidate: CloudSourceCandidate { provider_namespace: namespace, target_id: target.target_id.clone(), @@ -191,6 +198,10 @@ pub(super) async fn reconcile_cloud_winners( metadata: json!({ "providerNamespace": source.namespace, "providerSubscriptionId": source.id, + "provider": subscription.provider.as_str(), + "recurring": source.recurring.as_str(), + "variant": source.variant, + "stripeSubscriptionId": (subscription.provider == Provider::Stripe).then_some(source.external_subscription_id).flatten(), "financialRestriction": restriction_name(source.candidate.restriction), "selected": selected, }), @@ -205,3 +216,7 @@ pub(super) async fn reconcile_cloud_winners( } Ok(()) } + +pub(super) fn entitlement_subject(namespace: &str, source_id: &str) -> String { + format!("{namespace}:source:{}:{source_id}", source_id.len()) +} diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/read.rs b/packages/backend/native/src/runtime/backend_runtime/payment/read.rs index 873566d3a0..4c2ea30435 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/read.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/read.rs @@ -168,8 +168,7 @@ pub(super) async fn lock_subscription_rows( .then_some(snapshot.customer_id.as_deref()) .flatten(); let rows = sqlx::query( - r#"SELECT id,provider_namespace,source_identity,external_subscription_id,target_type,target_id,external_customer_id, - iap_store::text AS iap_store,external_ref,external_product_id + r#"SELECT id,provider_namespace,source_identity,target_type,target_id,external_customer_id FROM provider_subscriptions WHERE (provider_namespace=$1 AND (source_identity=ANY($2) OR ($3::text IS NOT NULL AND external_customer_id=$3))) OR (provider=$4::"Provider" AND external_subscription_id=ANY($5)) @@ -184,39 +183,27 @@ pub(super) async fn lock_subscription_rows( .fetch_all(&mut **tx) .await .map_err(|error| RuntimeError::database("lock payment subscription rows", error))?; - Ok( - rows - .into_iter() - .filter_map(|row| { - let source_id: Option = row.get::, _>("source_identity").or_else(|| { - let external_id = row.get::, _>("external_subscription_id"); - let iap_store = row.get::, _>("iap_store"); - let external_ref = row.get::, _>("external_ref"); - let external_product_id = row.get::, _>("external_product_id"); - snapshot.subscriptions.iter().find_map(|subscription| { - let matches_external_id = external_id.is_some() && subscription.external_subscription_id == external_id; - let matches_revenuecat_legacy = snapshot.provider() == affine_core::payment::Provider::RevenueCat - && subscription.iap_store == iap_store - && subscription.external_ref == external_ref - && subscription.external_product_id == external_product_id; - (matches_external_id || matches_revenuecat_legacy).then(|| subscription.source_id.clone()) - }) - }); - source_id.map(|source_id| StoredSubscription { - id: row.get("id"), - namespace: row - .get::, _>("provider_namespace") - .unwrap_or_else(|| namespace.to_string()), - source_id, - target: RuntimeEntitlementTarget { - target_type: row.get("target_type"), - target_id: row.get("target_id"), - }, - customer_id: row.get("external_customer_id"), - }) + rows + .into_iter() + .map(|row| { + let namespace = row + .get::, _>("provider_namespace") + .ok_or_else(|| RuntimeError::invalid_state("legacy payment source requires pre-repair"))?; + let source_id = row + .get::, _>("source_identity") + .ok_or_else(|| RuntimeError::invalid_state("legacy payment source requires pre-repair"))?; + Ok(StoredSubscription { + id: row.get("id"), + namespace, + source_id, + target: RuntimeEntitlementTarget { + target_type: row.get("target_type"), + target_id: row.get("target_id"), + }, + customer_id: row.get("external_customer_id"), }) - .collect(), - ) + }) + .collect() } pub(super) async fn lock_receipts_and_operation( diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/snapshot.rs b/packages/backend/native/src/runtime/backend_runtime/payment/snapshot.rs index e3e2759b6e..fc982d9f74 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/snapshot.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/snapshot.rs @@ -80,10 +80,12 @@ pub(super) async fn stripe_subscription_snapshot( .map_err(|error| RuntimeError::database("load Stripe customer target", error))? .ok_or_else(|| RuntimeError::invalid_state("Stripe customer has no canonical user mapping"))?; let stored_namespace: Option = customer.get("provider_namespace"); - if stored_namespace - .as_deref() - .is_some_and(|stored| stored != namespace_key) - { + if stored_namespace.is_none() { + return Err(RuntimeError::invalid_state( + "legacy Stripe customer requires pre-repair", + )); + } + if stored_namespace.as_deref() != Some(namespace_key.as_str()) { return Err(RuntimeError::invalid_state( "Stripe customer belongs to another provider namespace", )); diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/tests.rs b/packages/backend/native/src/runtime/backend_runtime/payment/tests.rs index 470edfc077..6f5de01503 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/tests.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/tests.rs @@ -1136,20 +1136,20 @@ async fn operation_intent_is_frozen_before_send_and_blocks_overlapping_work() { .execute(&pool) .await .unwrap(); - assert_eq!( - load_or_adopt_stripe_customer(&pool, &legacy_user, &account_namespace_key) + assert!( + load_stripe_customer(&pool, &legacy_user, &account_namespace_key) .await - .unwrap(), - Some(legacy_customer) + .unwrap_err() + .to_string() + .contains("requires pre-repair") ); - assert_eq!( - sqlx::query_scalar::<_, String>("SELECT provider_namespace FROM user_stripe_customers WHERE user_id=$1") + let stored: Option = + sqlx::query_scalar("SELECT provider_namespace FROM user_stripe_customers WHERE user_id=$1") .bind(&legacy_user) .fetch_one(&pool) .await - .unwrap(), - account_namespace_key - ); + .unwrap(); + assert!(stored.is_none()); cleanup(&pool, &account_namespace_key, &account_marker).await; } @@ -2364,74 +2364,7 @@ async fn failed_atomic_batch_rolls_back_and_incomplete_snapshot_writes_nothing() .unwrap(); assert_eq!(counts, (0, 0, 0)); - let canonical_subject = entitlement_subject(&namespace, &source_id); - sqlx::query( - "INSERT INTO entitlements(id,target_type,target_id,source,subject_id,plan,status,metadata) \ - VALUES($1,'user',$2,'cloud_subscription',$3,'pro','active',$4)", - ) - .bind(uuid::Uuid::new_v4().to_string()) - .bind(&user) - .bind(&source_id) - .bind(json!({"providerNamespace": "payment:v1:revenuecat:sandbox:5:other"})) - .execute(&pool) - .await - .unwrap(); - let cross_provider_legacy = apply_payment_snapshot( - &mut connection, - snapshot( - provider_namespace.clone(), - SnapshotCoverage::Single, - &customer_id, - vec![subscription(&user, &customer_id, &source_id)], - ), - Deployment::Cloud, - ) - .await - .unwrap_err(); - assert!(cross_provider_legacy.to_string().contains("ambiguous legacy")); - sqlx::query("DELETE FROM entitlements WHERE source='cloud_subscription' AND subject_id=$1") - .bind(&source_id) - .execute(&pool) - .await - .unwrap(); - for subject in [&source_id, &canonical_subject] { - sqlx::query( - "INSERT INTO entitlements(id,target_type,target_id,source,subject_id,plan,status,metadata) \ - VALUES($1,'user',$2,'cloud_subscription',$3,'pro','active','{}')", - ) - .bind(uuid::Uuid::new_v4().to_string()) - .bind(&user) - .bind(subject) - .execute(&pool) - .await - .unwrap(); - } - let duplicate_entitlement = match apply_payment_snapshot( - &mut connection, - snapshot( - provider_namespace, - SnapshotCoverage::Single, - &customer_id, - vec![subscription(&user, &customer_id, &source_id)], - ), - Deployment::Cloud, - ) - .await - { - Ok(_) => panic!("duplicate legacy and canonical entitlements were accepted"), - Err(error) => error, - }; - assert!( - duplicate_entitlement - .to_string() - .contains("conflicting payment entitlement subject") - ); drop(connection); - sqlx::query("DELETE FROM entitlements WHERE source='cloud_subscription' AND subject_id=ANY($1)") - .bind([source_id.as_str(), canonical_subject.as_str()]) - .execute(&pool) - .await - .unwrap(); cleanup(&pool, &namespace, &marker).await; } @@ -2846,7 +2779,7 @@ async fn canonical_source_identity_conflict_cannot_be_adopted_across_namespaces( let error = match apply_payment_snapshot( &mut connection, snapshot( - primary_namespace, + primary_namespace.clone(), SnapshotCoverage::Single, &customer_id, vec![subscription(&user, &customer_id, &source_id)], @@ -2871,6 +2804,48 @@ async fn canonical_source_identity_conflict_cannot_be_adopted_across_namespaces( .await .unwrap(); assert_eq!(stored, (conflicting_namespace.clone(), conflicting_customer)); + for missing_namespace in [true, false] { + let stored_namespace = (!missing_namespace).then_some(namespace.as_str()); + let stored_source = missing_namespace.then_some(source_id.as_str()); + sqlx::query( + "UPDATE provider_subscriptions SET provider_namespace=$2,source_identity=$3 WHERE external_subscription_id=$1", + ) + .bind(&source_id) + .bind(stored_namespace) + .bind(stored_source) + .execute(&pool) + .await + .unwrap(); + let error = apply_payment_snapshot( + &mut connection, + snapshot( + primary_namespace.clone(), + SnapshotCoverage::Single, + &customer_id, + vec![subscription(&user, &customer_id, &source_id)], + ), + Deployment::Cloud, + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("requires pre-repair"), "{error}"); + let unchanged: (Option, Option) = sqlx::query_as( + "SELECT provider_namespace,source_identity FROM provider_subscriptions WHERE external_subscription_id=$1", + ) + .bind(&source_id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + unchanged, + (stored_namespace.map(str::to_string), stored_source.map(str::to_string)) + ); + } + sqlx::query("DELETE FROM provider_subscriptions WHERE external_subscription_id=$1") + .bind(&source_id) + .execute(&pool) + .await + .unwrap(); drop(connection); cleanup(&pool, &namespace, &marker).await; cleanup(&pool, &conflicting_namespace, &marker).await; @@ -2913,32 +2888,15 @@ async fn revenuecat_access_and_missing_source_rules_fail_closed() { .await .unwrap() .unwrap(); - let legacy_id = uuid::Uuid::new_v4().to_string(); + let canonical_id = uuid::Uuid::new_v4().to_string(); sqlx::query( r#"INSERT INTO provider_subscriptions( - id,provider,target_type,target_id,plan,recurring,status,external_customer_id, - external_product_id,iap_store,external_ref,metadata) - VALUES($1,'revenuecat','user',$2,'ai','yearly','active',$3,'rc-product','app_store',$4,$5)"#, + id,provider,provider_namespace,source_identity,target_type,target_id,plan,recurring,status,external_customer_id, + external_subscription_id,external_product_id,iap_store,external_ref,metadata) + VALUES($1,'revenuecat',$2,$3,'user',$4,'ai','yearly','active',$5,$3,'rc-product','app_store',$6,'{}')"#, ) - .bind(&legacy_id) - .bind(&user) - .bind(&customer_id) - .bind(format!("store-{source_id}")) - .bind(json!({"providerNamespace": namespace})) - .execute(&pool) - .await - .unwrap(); - sqlx::query( - "INSERT INTO entitlements(id,target_type,target_id,source,subject_id,plan,status,metadata) \ - VALUES($1,'user',$2,'cloud_subscription',$3,'ai','active',$4)", - ) - .bind(uuid::Uuid::new_v4().to_string()) - .bind(&user) - .bind(&source_id) - .bind(json!({"providerNamespace": namespace})) - .execute(&pool) - .await - .unwrap(); + .bind(&canonical_id).bind(&namespace).bind(&source_id).bind(&user).bind(&customer_id) + .bind(format!("store-{source_id}")).execute(&pool).await.unwrap(); apply_payment_snapshot( &mut connection, snapshot( @@ -2961,7 +2919,7 @@ async fn revenuecat_access_and_missing_source_rules_fail_closed() { .fetch_one(&pool) .await .unwrap(); - assert_eq!(identities.0, legacy_id); + assert_eq!(identities.0, canonical_id); assert_eq!(identities.1, source_id); assert_ne!(identities.1, identities.2); assert_eq!(identities.3, "expired"); @@ -3050,6 +3008,33 @@ async fn revenuecat_access_and_missing_source_rules_fail_closed() { ] ); + let mut grace = revenuecat_subscription(&user, &customer_id, &source_id); + grace.gives_access = Some(true); + grace.lifecycle = ProviderLifecycle::InGracePeriod; + apply_payment_snapshot( + &mut connection, + snapshot( + provider_namespace.clone(), + SnapshotCoverage::Single, + &customer_id, + vec![grace], + ), + Deployment::Cloud, + ) + .await + .unwrap(); + let display: (String, serde_json::Value) = + sqlx::query_as("SELECT status,metadata FROM entitlements WHERE source='cloud_subscription' AND subject_id=$1") + .bind(entitlement_subject(&namespace, &source_id)) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(display.0, "grace"); + assert_eq!(display.1["provider"], "revenuecat"); + assert_eq!(display.1["recurring"], "yearly"); + assert!(display.1["variant"].is_null()); + assert!(display.1["stripeSubscriptionId"].is_null()); + let mut transfer = snapshot( provider_namespace.clone(), SnapshotCoverage::Single, @@ -3114,13 +3099,81 @@ async fn revenuecat_access_and_missing_source_rules_fail_closed() { cleanup(&pool, &namespace, &marker).await; cleanup(&pool, &stripe_namespace_key, &marker).await; + let multi_marker = format!("{marker}-multi"); + let multi_user = insert_user(&pool, &multi_marker).await; + let multi_namespace = ProviderNamespace { + provider: Provider::RevenueCat, + environment: ProviderEnvironment::Sandbox, + account: multi_marker.clone(), + }; + let multi_key = multi_namespace.canonical_key().unwrap(); + let shared_store = format!("store-{multi_marker}"); + let mut multi_sources = (0..2) + .map(|index| { + let mut source = revenuecat_subscription(&multi_user, &multi_user, &format!("rc-{multi_marker}-{index}")); + source.gives_access = Some(true); + source.external_ref = Some(shared_store.clone()); + source.external_product_id = Some(format!("rc-product-{index}")); + source + }) + .collect::>(); + let mut scopes = vec![ + PaymentScope::customer(&multi_key, &multi_user).unwrap(), + PaymentScope::cloud_target("user", &multi_user, Plan::Ai).unwrap(), + ]; + scopes.extend( + multi_sources + .iter() + .map(|source| PaymentScope::source(&multi_key, &source.source_id).unwrap()), + ); + let mut multi_connection = PaymentConnection::try_acquire(&pool, scopes).await.unwrap().unwrap(); + apply_payment_snapshot( + &mut multi_connection, + snapshot( + multi_namespace, + SnapshotCoverage::Single, + &multi_user, + std::mem::take(&mut multi_sources), + ), + Deployment::Cloud, + ) + .await + .unwrap(); + let counts: (i64, i64, i64) = sqlx::query_as( + "SELECT count(*),count(DISTINCT source_identity),count(DISTINCT external_ref) FROM provider_subscriptions WHERE \ + provider_namespace=$1", + ) + .bind(&multi_key) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(counts, (2, 2, 1)); + let entitlement_counts: (i64, i64) = sqlx::query_as( + "SELECT count(*),count(*) FILTER (WHERE status='active') FROM entitlements WHERE subject_id LIKE $1", + ) + .bind(format!("{multi_key}%")) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(entitlement_counts, (2, 1)); + drop(multi_connection); + cleanup(&pool, &multi_key, &multi_marker).await; + let provisional_marker = format!("{marker}-provisional"); let provisional_user = insert_user(&pool, &provisional_marker).await; let provisional_source = format!("rc-source-{provisional_marker}"); let transaction_id = format!("store-{provisional_marker}"); let anonymous_customer = format!("$RCAnonymousID:{provisional_marker}"); - let anonymous_item = revenuecat_item(&anonymous_customer, &provisional_source, &transaction_id); - let confirmed_item = revenuecat_item(&provisional_user, &provisional_source, &transaction_id); + let anonymous_item = revenuecat_item( + &anonymous_customer, + &provisional_source, + &format!("current-{transaction_id}"), + ); + let confirmed_item = revenuecat_item( + &provisional_user, + &provisional_source, + &format!("renewed-{transaction_id}"), + ); let page = |items: Vec| json!({ "items": items, "next_page": null }).to_string(); let (endpoint, mut requests) = mock_http(vec![ MockResponse { diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/write.rs b/packages/backend/native/src/runtime/backend_runtime/payment/write.rs index b778a90904..bf5ca45b08 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/write.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/write.rs @@ -8,48 +8,32 @@ use super::{ PaymentSnapshot, SnapshotCoverage, StoredSubscription, SubscriptionSnapshot, }; -pub(super) async fn load_or_adopt_stripe_customer( +pub(super) async fn load_stripe_customer( pool: &PgPool, user_id: &str, namespace: &str, ) -> RuntimeResult> { - let mut tx = pool - .begin() - .await - .map_err(|error| RuntimeError::database("begin Stripe customer lookup", error))?; let customer = - sqlx::query("SELECT stripe_customer_id,provider_namespace FROM user_stripe_customers WHERE user_id=$1 FOR UPDATE") + sqlx::query("SELECT stripe_customer_id,provider_namespace FROM user_stripe_customers WHERE user_id=$1") .bind(user_id) - .fetch_optional(&mut *tx) + .fetch_optional(pool) .await .map_err(|error| RuntimeError::database("load Stripe customer", error))?; let Some(customer) = customer else { - tx.commit() - .await - .map_err(|error| RuntimeError::database("commit empty Stripe customer lookup", error))?; return Ok(None); }; - let customer_id: String = customer.get("stripe_customer_id"); - match customer.get::, _>("provider_namespace") { - Some(stored) if stored != namespace => { - return Err(RuntimeError::invalid_state( - "Stripe user customer belongs to another provider namespace", - )); - } - None => { - sqlx::query("UPDATE user_stripe_customers SET provider_namespace=$2 WHERE user_id=$1") - .bind(user_id) - .bind(namespace) - .execute(&mut *tx) - .await - .map_err(|error| RuntimeError::database("adopt legacy Stripe customer", error))?; - } - Some(_) => {} + let stored: Option = customer.get("provider_namespace"); + if stored.is_none() { + return Err(RuntimeError::invalid_state( + "legacy Stripe customer requires pre-repair", + )); } - tx.commit() - .await - .map_err(|error| RuntimeError::database("commit Stripe customer lookup", error))?; - Ok(Some(customer_id)) + if stored.as_deref() != Some(namespace) { + return Err(RuntimeError::invalid_state( + "Stripe user customer belongs to another provider namespace", + )); + } + Ok(Some(customer.get("stripe_customer_id"))) } pub(super) async fn upsert_customers( @@ -78,7 +62,7 @@ pub(super) async fn upsert_customers( stripe_customer_id=EXCLUDED.stripe_customer_id, provider_namespace=EXCLUDED.provider_namespace WHERE user_stripe_customers.stripe_customer_id=EXCLUDED.stripe_customer_id - AND (user_stripe_customers.provider_namespace IS NULL OR user_stripe_customers.provider_namespace=EXCLUDED.provider_namespace)"#, + AND user_stripe_customers.provider_namespace=EXCLUDED.provider_namespace"#, ) .bind(&customer.user_id) .bind(&customer.external_customer_id) @@ -102,21 +86,15 @@ pub(super) async fn upsert_subscription( now: chrono::DateTime, ) -> RuntimeResult { let rows = sqlx::query( - r#"SELECT id,provider_namespace FROM provider_subscriptions + r#"SELECT id,provider_namespace,source_identity FROM provider_subscriptions WHERE (provider_namespace=$1 AND source_identity=$2) OR (provider=$3::"Provider" AND $4::text IS NOT NULL AND external_subscription_id=$4) - OR (provider='revenuecat' AND $5::text IS NOT NULL AND iap_store::text=$5 - AND external_ref=$6 AND external_product_id=$7 AND external_customer_id=$8) ORDER BY (provider_namespace=$1) DESC,id FOR UPDATE"#, ) .bind(namespace) .bind(&subscription.source_id) .bind(snapshot.provider().as_str()) .bind(&subscription.external_subscription_id) - .bind(&subscription.iap_store) - .bind(&subscription.external_ref) - .bind(&subscription.external_product_id) - .bind(&subscription.external_customer_id) .fetch_all(&mut **tx) .await .map_err(|error| RuntimeError::database("find canonical payment subscription", error))?; @@ -128,6 +106,18 @@ pub(super) async fn upsert_subscription( { return Err(RuntimeError::invalid_state("conflicting payment source identity")); } + if rows.first().is_some_and(|row| { + row.get::, _>("provider_namespace").is_none() + || row.get::, _>("source_identity").is_none() + }) { + return Err(RuntimeError::invalid_state("legacy payment source requires pre-repair")); + } + if rows + .first() + .is_some_and(|row| row.get::("source_identity") != subscription.source_id) + { + return Err(RuntimeError::invalid_state("conflicting payment source identity")); + } let id = rows .first() .map(|row| row.get("id")) @@ -183,51 +173,9 @@ pub(super) async fn upsert_subscription( Ok(id) } -pub(super) async fn adopt_legacy_entitlement( - tx: &mut Transaction<'_, Postgres>, - legacy_subject: &str, - canonical_subject: &str, - namespace: &str, - target: &super::super::entitlement::RuntimeEntitlementTarget, - now: chrono::DateTime, -) -> RuntimeResult<()> { - let rows = sqlx::query( - "SELECT id,subject_id,target_type,target_id,metadata FROM entitlements WHERE source='cloud_subscription' AND \ - subject_id=ANY($1) ORDER BY id FOR UPDATE", - ) - .bind([legacy_subject, canonical_subject]) - .fetch_all(&mut **tx) - .await - .map_err(|error| RuntimeError::database("lock legacy payment entitlement", error))?; - if rows.len() > 1 { - return Err(RuntimeError::invalid_state("conflicting payment entitlement subject")); - } - if let Some(row) = rows - .first() - .filter(|row| row.get::, _>("subject_id").as_deref() == Some(legacy_subject)) - { - let metadata: serde_json::Value = row.get("metadata"); - if row.get::("target_type") != target.target_type - || row.get::("target_id") != target.target_id - || metadata.get("providerNamespace").and_then(|value| value.as_str()) != Some(namespace) - { - return Err(RuntimeError::invalid_state("ambiguous legacy payment entitlement")); - } - sqlx::query("UPDATE entitlements SET subject_id=$2,updated_at=$3 WHERE id=$1") - .bind(row.get::("id")) - .bind(canonical_subject) - .bind(now) - .execute(&mut **tx) - .await - .map_err(|error| RuntimeError::database("adopt legacy payment entitlement", error))?; - } - Ok(()) -} - pub(super) async fn expire_missing_sources( tx: &mut Transaction<'_, Postgres>, snapshot: &PaymentSnapshot, - namespace: &str, stored: &[StoredSubscription], now: chrono::DateTime, ) -> RuntimeResult<()> { @@ -264,14 +212,6 @@ pub(super) async fn expire_missing_sources( .execute(&mut **tx) .await .map_err(|error| RuntimeError::database("expire missing payment subscription", error))?; - sqlx::query( - "UPDATE entitlements SET status='expired',updated_at=$2 WHERE source='cloud_subscription' AND subject_id=$1", - ) - .bind(entitlement_subject(namespace, &missing.source_id)) - .bind(now) - .execute(&mut **tx) - .await - .map_err(|error| RuntimeError::database("expire missing payment entitlement", error))?; } Ok(()) } @@ -472,7 +412,3 @@ pub(super) async fn complete_receipts_and_operation( } Ok(()) } - -pub(super) fn entitlement_subject(namespace: &str, source_id: &str) -> String { - format!("{namespace}:source:{}:{source_id}", source_id.len()) -} diff --git a/packages/backend/native/src/runtime/migrations.rs b/packages/backend/native/src/runtime/migrations.rs index f06a00b500..9f0c7197c3 100644 --- a/packages/backend/native/src/runtime/migrations.rs +++ b/packages/backend/native/src/runtime/migrations.rs @@ -5,6 +5,7 @@ use super::{RuntimeError, RuntimeResult, types::EmbeddingHealth}; pub(crate) const RUNTIME_MIGRATIONS: &str = include_str!("sql/runtime_migrations.sql"); const EMBEDDING_MIGRATION: &str = include_str!("sql/embedding.sql"); +const EMBEDDING_V2_MIGRATION: &str = include_str!("sql/embedding_v2.sql"); const SEARCH_PROJECTION_MIGRATION: &str = include_str!("sql/search_projection.sql"); const SEARCH_PROJECTION_V2_MIGRATION: &str = include_str!("sql/search_projection_v2.sql"); const EMBEDDING_ADVISORY_LOCK: i64 = 0x4146_4649_4e45_0046; @@ -50,7 +51,8 @@ pub(crate) async fn embedding_schema_health(pool: &PgPool) -> RuntimeResult RuntimeResult RuntimeResult RuntimeResult = sqlx::query_scalar( - "SELECT tablename FROM pg_tables WHERE schemaname='public' AND tablename LIKE 'embedding_%' ORDER BY tablename", + let admin_pool = PgPool::connect(&database_url).await.unwrap(); + let schema = format!("embedding_migration_{}", uuid::Uuid::new_v4().simple()); + admin_pool + .execute(format!("CREATE SCHEMA {schema}").as_str()) + .await + .unwrap(); + let options = database_url + .parse::() + .unwrap() + .options([("search_path", format!("{schema},public"))]); + let pool = PgPool::connect_with(options.clone()).await.unwrap(); + migrate_component( + &pool, + "embedding", + EMBEDDING_ADVISORY_LOCK, + &[(1, &[EMBEDDING_MIGRATION])], ) + .await + .unwrap(); + + let health = embedding_schema_health(&pool).await.unwrap(); + assert!(!health.enabled); + assert_eq!(health.reason.as_deref(), Some("schema_not_migrated")); + assert_eq!(health.schema_version, None); + + let index_id = uuid::Uuid::new_v4(); + let source_id = uuid::Uuid::new_v4(); + let generation_token = uuid::Uuid::new_v4(); + sqlx::query( + "INSERT INTO \ + embedding_indexes(id,workspace_id,fingerprint,route_source,provider,model_id,endpoint_fingerprint,\ + contract_version,health_status) \ + VALUES($1,'migration-workspace','fingerprint','managed','openai','model','endpoint',1,'ready')", + ) + .bind(index_id) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO \ + embedding_sources(id,workspace_id,source_kind,source_key,content_revision,descriptor_revision,recipe_revision,\ + document_projection) VALUES($1,'migration-workspace','document','doc','content','descriptor','recipe','{}')", + ) + .bind(source_id) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO embedding_projections(source_id,index_id,status,active_generation_token,next_attempt_at) \ + VALUES($1,$2,'ready',$3,now() + interval '1 day')", + ) + .bind(source_id) + .bind(index_id) + .bind(generation_token) + .execute(&pool) + .await + .unwrap(); + + let mut projection_reader = pool.begin().await.unwrap(); + sqlx::query("SELECT source_id FROM embedding_projections LIMIT 1") + .fetch_one(&mut *projection_reader) + .await + .unwrap(); + let error = migrate_embedding_tables_inner(&pool).await.unwrap_err(); + assert!(error.to_string().contains("lock timeout"), "{error}"); + let versions: Vec = + sqlx::query_scalar("SELECT version FROM native_schema_migrations WHERE component='embedding' ORDER BY version") + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(versions, vec![1]); + let unchanged_schema: (bool, bool) = sqlx::query_as( + "SELECT pg_get_indexdef('embedding_projection_claim_idx'::regclass) NOT LIKE '%NULLS FIRST%', \ + to_regprocedure(format('%I.enqueue_changed_embedding_source()', $1::text)) IS NULL", + ) + .bind(&schema) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(unchanged_schema, (true, true)); + let health = embedding_schema_health(&pool).await.unwrap(); + assert!(!health.enabled); + assert_eq!(health.reason.as_deref(), Some("schema_not_migrated")); + assert_eq!(health.schema_version, None); + projection_reader.rollback().await.unwrap(); + + let mut writer = pool.begin().await.unwrap(); + sqlx::query("UPDATE embedding_sources SET content_revision=content_revision || '-before-upgrade' WHERE id=$1") + .bind(source_id) + .execute(&mut *writer) + .await + .unwrap(); + let migration_pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .unwrap(); + let migration_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&migration_pool) + .await + .unwrap(); + let migration = tokio::spawn(async move { + let health = migrate_embedding_tables_inner(&migration_pool).await; + migration_pool.close().await; + health + }); + tokio::time::timeout(std::time::Duration::from_secs(2), async { + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM pg_locks WHERE pid=$1 AND relation='embedding_sources'::regclass AND \ + mode='ShareRowExclusiveLock' AND NOT granted)", + ) + .bind(migration_pid) + .fetch_one(&pool) + .await + .unwrap(); + if waiting { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("embedding v2 must wait for source writers before locking projections"); + tokio::time::timeout( + std::time::Duration::from_secs(2), + sqlx::query("UPDATE embedding_projections SET priority=1 WHERE source_id=$1") + .bind(source_id) + .execute(&mut *writer), + ) + .await + .expect("source writer must finish projection work while migration waits") + .unwrap(); + writer.commit().await.unwrap(); + let health = migration.await.unwrap().unwrap(); + assert_eq!(health.schema_version, Some(2)); + assert_eq!(embedding_schema_health(&pool).await.unwrap().schema_version, Some(2)); + for version in [1, 2] { + sqlx::query( + "UPDATE native_schema_migrations SET checksum=repeat('0',64) WHERE component='embedding' AND version=$1", + ) + .bind(version) + .execute(&pool) + .await + .unwrap(); + let health = embedding_schema_health(&pool).await.unwrap(); + assert!(!health.enabled); + assert_eq!(health.reason.as_deref(), Some("schema_not_migrated")); + assert_eq!(health.schema_version, None); + let sql = if version == 1 { + EMBEDDING_MIGRATION + } else { + EMBEDDING_V2_MIGRATION + }; + sqlx::query("UPDATE native_schema_migrations SET checksum=$2 WHERE component='embedding' AND version=$1") + .bind(version) + .bind(migration_checksum(&[sql])) + .execute(&pool) + .await + .unwrap(); + } + assert_eq!(embedding_schema_health(&pool).await.unwrap().schema_version, Some(2)); + let applied: Vec<(i32, String, chrono::DateTime)> = sqlx::query_as( + "SELECT version,checksum,applied_at FROM native_schema_migrations WHERE component='embedding' ORDER BY version", + ) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(applied.len(), 2); + for (row, (version, sql)) in applied + .iter() + .zip([(1, EMBEDDING_MIGRATION), (2, EMBEDDING_V2_MIGRATION)]) + { + assert_eq!(row.0, version); + assert_eq!(row.1, migration_checksum(&[sql])); + } + migrate_embedding_tables_inner(&pool).await.unwrap(); + migrate_component( + &pool, + "embedding", + EMBEDDING_ADVISORY_LOCK, + &[(1, &[EMBEDDING_MIGRATION])], + ) + .await + .unwrap(); + let repeated: Vec<(i32, String, chrono::DateTime)> = sqlx::query_as( + "SELECT version,checksum,applied_at FROM native_schema_migrations WHERE component='embedding' ORDER BY version", + ) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(applied, repeated); + + let tables: Vec = sqlx::query_scalar( + "SELECT tablename FROM pg_tables WHERE schemaname=$1 AND tablename LIKE 'embedding_%' ORDER BY tablename", + ) + .bind(&schema) .fetch_all(&pool) .await .unwrap(); @@ -271,6 +480,80 @@ mod tests { .await .unwrap(); assert_eq!(dimensions, 1024); + let claim_index: String = sqlx::query_scalar( + "SELECT indexdef FROM pg_indexes WHERE schemaname=$1 AND indexname='embedding_projection_claim_idx'", + ) + .bind(&schema) + .fetch_one(&pool) + .await + .unwrap(); + assert!(claim_index.contains("next_attempt_at NULLS FIRST")); + + sqlx::query("UPDATE embedding_sources SET content_revision=content_revision WHERE id=$1") + .bind(source_id) + .execute(&pool) + .await + .unwrap(); + let unchanged: (String, uuid::Uuid, bool) = sqlx::query_as( + "SELECT status,active_generation_token,next_attempt_at IS NOT NULL FROM embedding_projections WHERE source_id=$1", + ) + .bind(source_id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(unchanged, ("ready".to_string(), generation_token, true)); + for field in ["content_revision", "descriptor_revision", "recipe_revision"] { + sqlx::query( + "UPDATE embedding_projections SET status='ready',next_attempt_at=now() + interval '1 day' WHERE source_id=$1", + ) + .bind(source_id) + .execute(&pool) + .await + .unwrap(); + sqlx::query(&format!( + "UPDATE embedding_sources SET {field}={field} || '-changed' WHERE id=$1" + )) + .bind(source_id) + .execute(&pool) + .await + .unwrap(); + let requeued: (String, uuid::Uuid, bool) = sqlx::query_as( + "SELECT status,active_generation_token,next_attempt_at IS NULL FROM embedding_projections WHERE source_id=$1", + ) + .bind(source_id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(requeued, ("pending".to_string(), generation_token, true), "{field}"); + } + for status in ["pending", "running", "retry_wait", "failed"] { + sqlx::query( + "UPDATE embedding_projections SET status=$2,next_attempt_at=now() + interval '1 day' WHERE source_id=$1", + ) + .bind(source_id) + .bind(status) + .execute(&pool) + .await + .unwrap(); + sqlx::query("UPDATE embedding_sources SET content_revision=content_revision || '-changed' WHERE id=$1") + .bind(source_id) + .execute(&pool) + .await + .unwrap(); + let unchanged: (String, bool) = + sqlx::query_as("SELECT status,next_attempt_at IS NOT NULL FROM embedding_projections WHERE source_id=$1") + .bind(source_id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(unchanged, (status.to_string(), true)); + } + + pool.close().await; + admin_pool + .execute(format!("DROP SCHEMA {schema} CASCADE").as_str()) + .await + .unwrap(); } #[test] diff --git a/packages/backend/native/src/runtime/sql/embedding.sql b/packages/backend/native/src/runtime/sql/embedding.sql index 0bdbd19241..3581c4e0a9 100644 --- a/packages/backend/native/src/runtime/sql/embedding.sql +++ b/packages/backend/native/src/runtime/sql/embedding.sql @@ -107,7 +107,7 @@ CREATE TABLE embedding_chunks ( ); CREATE INDEX embedding_projection_claim_idx - ON embedding_projections (priority DESC, next_attempt_at NULLS FIRST, updated_at) + ON embedding_projections (priority DESC, next_attempt_at, updated_at) WHERE status IN ('pending', 'retry_wait', 'running'); CREATE INDEX embedding_sources_workspace_idx ON embedding_sources (workspace_id, source_kind) WHERE deleted_at IS NULL; @@ -120,21 +120,3 @@ CREATE INDEX embedding_chunks_scope_idx ON embedding_chunks (workspace_id, index_id, source_id); CREATE INDEX embedding_chunks_artifact_idx ON embedding_chunks (workspace_id, artifact_id) WHERE artifact_id IS NOT NULL; - -CREATE FUNCTION enqueue_changed_embedding_source() RETURNS trigger -LANGUAGE plpgsql AS $$ -BEGIN - UPDATE embedding_projections SET status='pending', next_attempt_at=NULL, updated_at=now() - WHERE source_id=NEW.id AND status='ready'; - RETURN NEW; -END; -$$; - -CREATE TRIGGER embedding_source_revision_changed -AFTER UPDATE OF content_revision, descriptor_revision, recipe_revision ON embedding_sources -FOR EACH ROW WHEN ( - OLD.content_revision IS DISTINCT FROM NEW.content_revision - OR OLD.descriptor_revision IS DISTINCT FROM NEW.descriptor_revision - OR OLD.recipe_revision IS DISTINCT FROM NEW.recipe_revision -) -EXECUTE FUNCTION enqueue_changed_embedding_source(); diff --git a/packages/backend/native/src/runtime/sql/embedding_v2.sql b/packages/backend/native/src/runtime/sql/embedding_v2.sql new file mode 100644 index 0000000000..c55b8c60a6 --- /dev/null +++ b/packages/backend/native/src/runtime/sql/embedding_v2.sql @@ -0,0 +1,24 @@ +LOCK TABLE embedding_sources IN SHARE ROW EXCLUSIVE MODE; + +DROP INDEX embedding_projection_claim_idx; +CREATE INDEX embedding_projection_claim_idx + ON embedding_projections (priority DESC, next_attempt_at NULLS FIRST, updated_at) + WHERE status IN ('pending', 'retry_wait', 'running'); + +CREATE FUNCTION enqueue_changed_embedding_source() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + UPDATE embedding_projections SET status='pending', next_attempt_at=NULL, updated_at=now() + WHERE source_id=NEW.id AND status='ready'; + RETURN NEW; +END; +$$; + +CREATE TRIGGER embedding_source_revision_changed +AFTER UPDATE OF content_revision, descriptor_revision, recipe_revision ON embedding_sources +FOR EACH ROW WHEN ( + OLD.content_revision IS DISTINCT FROM NEW.content_revision + OR OLD.descriptor_revision IS DISTINCT FROM NEW.descriptor_revision + OR OLD.recipe_revision IS DISTINCT FROM NEW.recipe_revision +) +EXECUTE FUNCTION enqueue_changed_embedding_source(); diff --git a/packages/backend/server/src/data/__tests__/__snapshots__/migrations.spec.ts.md b/packages/backend/server/src/data/__tests__/__snapshots__/migrations.spec.ts.md index c13de5a550..40a4a499b1 100644 --- a/packages/backend/server/src/data/__tests__/__snapshots__/migrations.spec.ts.md +++ b/packages/backend/server/src/data/__tests__/__snapshots__/migrations.spec.ts.md @@ -4,32 +4,25 @@ The actual snapshot is saved in `migrations.spec.ts.snap`. Generated by [AVA](https://avajs.dev). -## mixed-version cutover keeps legacy writes readable and rejects malformed canonical rows +## mixed-version cutover preserves legacy pending uploads and rejects ownerless workspaces > Snapshot 1 { cutover: { + cloudPassed: { + activeUnsignedSelfhostEntitlements: 0, + normalizedUnsignedSelfhostEntitlements: 0, + ownerlessWorkspaces: 0, + }, failure: 'Canonical cutover validation failed: ownerlessWorkspaces=1', normalized: { - attachment: { - deleted: true, - status: 'pending', - }, - blob: { - deleted: true, - status: 'pending', - }, entitlement: { status: 'needs_reupload', }, }, passed: { activeUnsignedSelfhostEntitlements: 0, - malformedBlobReservations: 0, - malformedCommentAttachmentReservations: 0, - normalizedMalformedBlobReservations: 1, - normalizedMalformedCommentAttachmentReservations: 1, normalizedUnsignedSelfhostEntitlements: 1, ownerlessWorkspaces: 0, }, diff --git a/packages/backend/server/src/data/__tests__/__snapshots__/migrations.spec.ts.snap b/packages/backend/server/src/data/__tests__/__snapshots__/migrations.spec.ts.snap index 6b2cfe19e5cfb1414ca9dd6b6e2c57776e654f77..8281122a9fb90881adfc52a113d05e65503fe122 100644 GIT binary patch literal 1345 zcmV-H1-|-0RzV?JdIzc|+nVs~DgIZx7;0d+v{TlF!2E3;MpJ>W%wUxUy znfAQ~{5Yf)X3~`Rm^u7%9H&nz|E>Yhfje~I0UZc*;5i+5R|me*fr6o|Q&HE^rww4I z0X(Wwt2t`R03ri8t5P?rRO7q>yk!8N8o;kAeQWM$3t230DlEsc>IQM!dxQ%?9+-nE zrj1U0j{8A7rQvwbJ|4x9@A6=j#vLB`9+&;h?vu&evz)9)N4a{>j%?Y7#+I!_aT@Z# zKhx${8ssOyrE5%&`Y)d%&Ye`m#5f9KP55d&H~f2DE}~?5L`;`wnB>J;8JfXE`x<;5I4n` za;CV7^5kTtuAWoN7cx$J2g0x|c{3R7S#wm{u;R^l9Ui&lO{O{R#N(3klbOsoR|H-z z0-qNFr=;8#Jy#lbmw@|JnvuJM$4fx71iV@TzEtVO+^o6@ludr znvH~iA|mfF1#_)f$o*0FWM=s@`6}MNTs77&o|;gZMocR!CpKdrm}3b|%ai_x8|gb+ z?@m_mi$ZeQ7Ng<7^+c)>@o-e|D|>^uc{tN%1y{=o?iDjDxK+k(D1RXCAp>rzq z(FkG{1=>{^Li0NGqwk0oR<~SQ>fEo}tBS7QYaFO8oZ_|Y#$l2f`aiP&YGeyu z>>lt&(|NJGzQ`D%KUS9e-QM;j;C{4P^)5xUFfF@M2Ej=uif52=$G}mM{4!kwY znweSSIs&(aCrRMD*`aTbT}g7AkSXzSl~vW;SuICb^|nTwuEksJ@8;y6LGe~TmJk2{ D)KiI< literal 1431 zcmV;I1!(#~RzV62& z6btoj@^&ZP{3Gwp?oP3XD$;@%!HS0-q=E$zts*Fj&|Vd_P$;4v>On7psFy!cLI1400r)^52SW14X0r)m zf#@JMA=d${B`Qc|j8qrg&VYx=5>R7NH$2cw7|)<*3s7rtxQRGSsPHHKz!$xYbh@aI z*xWuwy#>=3iclPQ1?blT)Z}qDb=d(wWL(fN;r$a=)+@jU1?VZj8w&8gBArxOeo})d zUn;<*MOtM%O=*wR7M~o)>62>TE5KC+&{bfQ3OuC(u?n14fzMUoXI0wAl=o3B4QOe= zR!yQdO4QvNuvY_)%G8!j)lO)@Ne%cw1Fp#QdrN86KpeD)k|%YF`aw5ki|;!o@&a3| z(peh#9u@tL3KfB;>V9R?!xSA^G2=t{ZnF@iYxt=12ypmPD)3uITJa zVz-m6XpnH5&9W7ZSP`2S<3g}75#wSw#~xJW9*;%B7ro&mXFytEyB6=dF5^5-C;X(t zQo-hLvgw+fxobZ0Q^pJ4Ss+RlCHGPC~yFOH@ z%6aPeT*PT_PZ)MZf4*ga;>fhcfi~{V(#U1raGKLiJSte(m_fAXb%5%?aUFPFml{Hq z`^WfD2R_k(-*sR^6*yc4-mC&wtH6DRB(Ii+$8H1IE7Ob;Ej567nN~0L{aXg`jscuE zmX9M#8b|8q25`{;zLJPdnRvwjel&nzB;s0`_=f>pGXT_<6Yp6@9Awre#HyCg8Bo;_jO7Q*E75*%HF5>=l#Jv41nCiq_>{^oX;f=gLzbbbI z@#H?nSvs4|uAA^T<@|{_?AsmB&$6<31W+8{J<ml;|*Y{0ld5dWKKzT$O4X7z;O#WV*wX$ykC`N zV%b~d~XXC(I!C7PIf4 { +test('mixed-version cutover preserves legacy pending uploads and rejects ownerless workspaces', async t => { const owner = await t.context.models.user.create({ email: `${randomUUID()}@affine.pro`, }); @@ -541,14 +541,6 @@ test('mixed-version cutover keeps legacy writes readable and rejects malformed c WHERE workspace_id = ${workspace.id} ORDER BY key `; - const newReaderBlobs = await t.context.db.blob.findMany({ - where: { workspaceId: workspace.id }, - orderBy: { key: 'asc' }, - }); - const newReaderAttachments = await t.context.db.commentAttachment.findMany({ - where: { workspaceId: workspace.id }, - orderBy: { key: 'asc' }, - }); const typeRows = await t.context.db.$queryRaw>` SELECT typname AS name FROM pg_type @@ -704,13 +696,13 @@ test('mixed-version cutover keeps legacy writes readable and rejects malformed c }, }); const command = new CutoverCommand(t.context.db); - const malformedKey = `malformed-${randomUUID()}`; - const malformedAttachmentKey = `malformed-attachment-${randomUUID()}`; + const legacyPendingKey = `legacy-pending-${randomUUID()}`; + const legacyPendingAttachmentKey = `legacy-pending-attachment-${randomUUID()}`; await t.context.db.$executeRaw` INSERT INTO blobs ( workspace_id, key, size, mime, status, reservation_expires_at ) VALUES ( - ${workspace.id}, ${malformedKey}, 1, 'application/octet-stream', + ${workspace.id}, ${legacyPendingKey}, 1, 'application/octet-stream', 'pending'::"BlobStatus", NULL ) `; @@ -719,38 +711,73 @@ test('mixed-version cutover keeps legacy writes readable and rejects malformed c workspace_id, doc_id, key, size, mime, name, status, reservation_expires_at ) VALUES ( - ${workspace.id}, 'doc', ${malformedAttachmentKey}, 1, 'text/plain', - 'malformed.txt', 'pending'::"BlobStatus", NULL + ${workspace.id}, 'doc', ${legacyPendingAttachmentKey}, 1, 'text/plain', + 'legacy-pending.txt', 'pending'::"BlobStatus", NULL ) `; + const cloudPassed = await command.execute('cloud'); const passed = await command.execute('selfhosted'); - const normalizedBlob = await t.context.db.blob.findFirstOrThrow({ - where: { workspaceId: workspace.id, key: malformedKey }, - select: { status: true, deletedAt: true }, + const pendingBlob = await t.context.db.blob.findFirstOrThrow({ + where: { workspaceId: workspace.id, key: legacyPendingKey }, + select: { status: true, deletedAt: true, reservationExpiresAt: true }, }); - const normalizedAttachment = + const pendingAttachment = await t.context.db.commentAttachment.findFirstOrThrow({ where: { workspaceId: workspace.id, docId: 'doc', - key: malformedAttachmentKey, + key: legacyPendingAttachmentKey, + }, + select: { status: true, deletedAt: true, reservationExpiresAt: true }, + }); + t.deepEqual(pendingBlob, { + status: 'pending', + deletedAt: null, + reservationExpiresAt: null, + }); + t.deepEqual(pendingAttachment, pendingBlob); + + await t.context.db.$executeRaw` + UPDATE blobs SET status = 'completed'::"BlobStatus" + WHERE workspace_id = ${workspace.id} AND key = ${legacyPendingKey} + `; + await t.context.db.$executeRaw` + UPDATE comment_attachments SET status = 'completed'::"BlobStatus" + WHERE workspace_id = ${workspace.id} AND doc_id = 'doc' + AND key = ${legacyPendingAttachmentKey} + `; + const completedBlob = await t.context.db.blob.findFirstOrThrow({ + where: { workspaceId: workspace.id, key: legacyPendingKey }, + select: { status: true, deletedAt: true }, + }); + const completedAttachment = + await t.context.db.commentAttachment.findFirstOrThrow({ + where: { + workspaceId: workspace.id, + docId: 'doc', + key: legacyPendingAttachmentKey, }, select: { status: true, deletedAt: true }, }); + t.deepEqual(completedBlob, { status: 'completed', deletedAt: null }); + t.deepEqual(completedAttachment, completedBlob); + const newReaderBlobs = await t.context.db.blob.findMany({ + where: { workspaceId: workspace.id, key: { in: [oldBlobKey, newBlobKey] } }, + orderBy: { key: 'asc' }, + }); + const newReaderAttachments = await t.context.db.commentAttachment.findMany({ + where: { + workspaceId: workspace.id, + key: { in: [oldAttachmentKey, newAttachmentKey] }, + }, + orderBy: { key: 'asc' }, + }); const normalized = { entitlement: await t.context.db.entitlement.findUniqueOrThrow({ where: { id: unsigned.id }, select: { status: true }, }), - blob: { - status: normalizedBlob.status, - deleted: normalizedBlob.deletedAt !== null, - }, - attachment: { - status: normalizedAttachment.status, - deleted: normalizedAttachment.deletedAt !== null, - }, }; await t.context.db.workspace.create({ @@ -806,6 +833,7 @@ test('mixed-version cutover keeps legacy writes readable and rejects malformed c })), }, cutover: { + cloudPassed, passed, normalized, failure: failure?.message, diff --git a/packages/backend/server/src/data/commands/cutover.ts b/packages/backend/server/src/data/commands/cutover.ts index 2013ce42a1..2764c53513 100644 --- a/packages/backend/server/src/data/commands/cutover.ts +++ b/packages/backend/server/src/data/commands/cutover.ts @@ -3,11 +3,7 @@ import { Prisma, PrismaClient } from '@prisma/client'; interface CutoverValidationResult { normalizedUnsignedSelfhostEntitlements: number; - normalizedMalformedBlobReservations: number; - normalizedMalformedCommentAttachmentReservations: number; ownerlessWorkspaces: number; - malformedBlobReservations: number; - malformedCommentAttachmentReservations: number; activeUnsignedSelfhostEntitlements: number; } @@ -41,29 +37,11 @@ export class CutoverCommand { AND status IN ('active', 'grace') ` : 0; - const normalizedMalformedBlobReservations = await tx.$executeRaw` - UPDATE blobs - SET deleted_at = clock_timestamp() - WHERE status = 'pending' - AND reservation_expires_at IS NULL - AND deleted_at IS NULL - `; - const normalizedMalformedCommentAttachmentReservations = - await tx.$executeRaw` - UPDATE comment_attachments - SET deleted_at = clock_timestamp() - WHERE status = 'pending' - AND reservation_expires_at IS NULL - AND deleted_at IS NULL - `; - const [validation] = await tx.$queryRaw< Array< Omit< CutoverValidationResult, - | 'normalizedUnsignedSelfhostEntitlements' - | 'normalizedMalformedBlobReservations' - | 'normalizedMalformedCommentAttachmentReservations' + 'normalizedUnsignedSelfhostEntitlements' > > >` @@ -79,20 +57,6 @@ export class CutoverCommand { AND member.state = 'active' ) ) AS "ownerlessWorkspaces", - ( - SELECT count(*)::int - FROM blobs - WHERE status = 'pending' - AND reservation_expires_at IS NULL - AND deleted_at IS NULL - ) AS "malformedBlobReservations", - ( - SELECT count(*)::int - FROM comment_attachments - WHERE status = 'pending' - AND reservation_expires_at IS NULL - AND deleted_at IS NULL - ) AS "malformedCommentAttachmentReservations", ( SELECT count(*)::int FROM entitlements @@ -109,8 +73,6 @@ export class CutoverCommand { const result = { normalizedUnsignedSelfhostEntitlements, - normalizedMalformedBlobReservations, - normalizedMalformedCommentAttachmentReservations, ...validation, }; const failures = Object.entries(result).filter( @@ -134,7 +96,7 @@ export class CutoverCommand { ); this.logger.log( - `Canonical cutover validation passed for ${deployment}; normalized ${result.normalizedUnsignedSelfhostEntitlements} unsigned self-hosted entitlements, ${result.normalizedMalformedBlobReservations} blob reservations, and ${result.normalizedMalformedCommentAttachmentReservations} comment attachment reservations.` + `Canonical cutover validation passed for ${deployment}; normalized ${result.normalizedUnsignedSelfhostEntitlements} unsigned self-hosted entitlements.` ); return result; }