use std::time::Duration; use super::onboarding_import_selection::{ context_count_for, event_count, insert_import_application, selected_version, }; use super::*; /// A concurrent archive of the exact pending candidate must never be selected. /// /// The blocker holds the candidate's `operations` row lock while the selection /// reads its snapshot and blocks on the same row lock; the archive then commits /// before the selection updates durable state. With only `READ COMMITTED` and a /// lock-free validation the selection would record a drifted, archived /// operation; the selection must instead abort (whole-transaction retry) and /// surface a stale-revision or unavailable conflict without mutation. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn concurrent_archive_vs_select_rejects_without_mutation() { let database = TestDatabase::new().await; let registry = database.registry().await; let pool = database.raw_pool().await; let observer = database.raw_pool().await; let workspace_id = WorkspaceId::new("ws_default"); let operation = test_operation("op_conc_archive", 1, OperationStatus::Draft); registry .create_operation(&workspace_id, &operation, None) .await .unwrap(); insert_import_application( &pool, "ws_default", "idem_conc_archive", &[( "candidate", "createLead", "created", "op_conc_archive", Some(1), )], ) .await; let initial = registry .get_onboarding_projection(&workspace_id) .await .unwrap(); let registered = registry .register_onboarding_import_context(RegisterOnboardingImportContextRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_conc_archive", plan_digest: &"b".repeat(64), expected_revision: initial.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap(); // Hold the exact candidate row lock in an independent transaction. let mut blocker = pool.begin().await.unwrap(); let blocker_pid: i32 = sqlx::query_scalar("select pg_backend_pid()") .fetch_one(&mut *blocker) .await .unwrap(); sqlx::query("select id from operations where workspace_id = $1 and id = $2 for update") .bind("ws_default") .bind("op_conc_archive") .fetch_one(&mut *blocker) .await .unwrap(); let select_registry = registry.clone(); let select_workspace = workspace_id.clone(); let select_task = tokio::spawn(async move { select_registry .select_onboarding_import_draft(SelectOnboardingImportDraftRequest { workspace_id: &select_workspace, application_idempotency_key: "idem_conc_archive", plan_digest: &"b".repeat(64), operation_id: &crank_core::OperationId::new("op_conc_archive"), operation_version: 1, expected_revision: registered.revision, occurred_at: OffsetDateTime::now_utc(), }) .await }); // Observe the in-flight selection waiting on the exact blocker. if select_task.is_finished() { panic!( "selection finished before the blocker: {:?}", select_task.await.unwrap() ); } wait_for_blocked_reader(&observer, blocker_pid).await; sqlx::query( "update operations set status = 'archived', updated_at = now() where workspace_id = 'ws_default' and id = 'op_conc_archive'", ) .execute(&mut *blocker) .await .unwrap(); blocker.commit().await.unwrap(); let error = select_task .await .unwrap() .expect_err("an archived pending candidate must never be selected"); assert!( matches!( error, RegistryError::OnboardingStaleRevision | RegistryError::OnboardingImportDraftUnavailable ), "unexpected selection error: {error:?}" ); assert_eq!(selected_version(&pool).await, None); assert_eq!(context_count_for(&pool, "ws_default").await, 1); database.cleanup().await; } /// A concurrent version edit of the exact pending candidate must never be /// selected with the stale version. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn concurrent_version_edit_vs_select_rejects_without_mutation() { let database = TestDatabase::new().await; let registry = database.registry().await; let pool = database.raw_pool().await; let observer = database.raw_pool().await; let workspace_id = WorkspaceId::new("ws_default"); let operation = test_operation("op_conc_edit", 1, OperationStatus::Draft); registry .create_operation(&workspace_id, &operation, None) .await .unwrap(); insert_import_application( &pool, "ws_default", "idem_conc_edit", &[( "candidate", "createLead", "created", "op_conc_edit", Some(1), )], ) .await; let initial = registry .get_onboarding_projection(&workspace_id) .await .unwrap(); let registered = registry .register_onboarding_import_context(RegisterOnboardingImportContextRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_conc_edit", plan_digest: &"b".repeat(64), expected_revision: initial.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap(); let mut blocker = pool.begin().await.unwrap(); let blocker_pid: i32 = sqlx::query_scalar("select pg_backend_pid()") .fetch_one(&mut *blocker) .await .unwrap(); sqlx::query("select id from operations where workspace_id = $1 and id = $2 for update") .bind("ws_default") .bind("op_conc_edit") .fetch_one(&mut *blocker) .await .unwrap(); let select_registry = registry.clone(); let select_workspace = workspace_id.clone(); let select_task = tokio::spawn(async move { select_registry .select_onboarding_import_draft(SelectOnboardingImportDraftRequest { workspace_id: &select_workspace, application_idempotency_key: "idem_conc_edit", plan_digest: &"b".repeat(64), operation_id: &crank_core::OperationId::new("op_conc_edit"), operation_version: 1, expected_revision: registered.revision, occurred_at: OffsetDateTime::now_utc(), }) .await }); if select_task.is_finished() { panic!( "selection finished before the blocker: {:?}", select_task.await.unwrap() ); } wait_for_blocked_reader(&observer, blocker_pid).await; sqlx::query( "update operations set current_draft_version = 2, updated_at = now() where workspace_id = 'ws_default' and id = 'op_conc_edit'", ) .execute(&mut *blocker) .await .unwrap(); blocker.commit().await.unwrap(); let error = select_task .await .unwrap() .expect_err("a drifted pending candidate version must never be selected"); assert!( matches!( error, RegistryError::OnboardingStaleRevision | RegistryError::OnboardingImportDraftUnavailable ), "unexpected selection error: {error:?}" ); assert_eq!(selected_version(&pool).await, None); database.cleanup().await; } /// Concurrent first observations must enter the server-owned cohort exactly /// once without aborting, and every caller must observe the same authoritative /// `eligible_since`. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn concurrent_first_eligibility_is_single_and_consistent() { let database = TestDatabase::new().await; let registry = database.registry().await; let pool = database.raw_pool().await; let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(9)); let mut tasks = Vec::new(); for index in 0..8 { // Legacy connect() deliberately has one connection per registry. // Independent pools and a barrier make these transactions overlap. let registry = if index == 0 { registry.clone() } else { database.registry().await }; let ready = barrier.clone(); tasks.push(tokio::spawn(async move { ready.wait().await; registry .ensure_onboarding_eligibility( &WorkspaceId::new("ws_default"), OffsetDateTime::now_utc(), ) .await })); } barrier.wait().await; let mut eligible_since = None; for task in tasks { let projection = task .await .unwrap() .expect("concurrent first observation must not abort"); let since = projection .eligible_since .expect("every observer must see the server-owned cohort"); match &eligible_since { None => eligible_since = Some(since), Some(existing) => assert_eq!(existing, &since), } } assert_eq!(event_count(&pool, "onboarding_eligible").await, 1); database.cleanup().await; } /// A snapshot must always pair its projection revision with matching import /// choices, even while the only candidate is concurrently archived. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn concurrent_archive_never_pairs_stale_revision_with_newer_choices() { let database = TestDatabase::new().await; let registry = database.registry().await; let pool = database.raw_pool().await; let observer = database.raw_pool().await; let workspace_id = WorkspaceId::new("ws_default"); let operation = test_operation("op_conc_snapshot", 1, OperationStatus::Draft); registry .create_operation(&workspace_id, &operation, None) .await .unwrap(); insert_import_application( &pool, "ws_default", "idem_conc_snapshot", &[( "candidate", "createLead", "created", "op_conc_snapshot", Some(1), )], ) .await; let initial = registry .get_onboarding_projection(&workspace_id) .await .unwrap(); let registered = registry .register_onboarding_import_context(RegisterOnboardingImportContextRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_conc_snapshot", plan_digest: &"b".repeat(64), expected_revision: initial.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap(); let draft_revision = registered.revision; // The projection reads the old catalog before its context read waits on // the immutable application. No report mutation or production test hook. let mut blocker = pool.begin().await.unwrap(); let blocker_pid: i32 = sqlx::query_scalar("select pg_backend_pid()") .fetch_one(&mut *blocker) .await .unwrap(); sqlx::query( "select idempotency_key from import_plan_applications where workspace_id = $1 and idempotency_key = $2 for update", ) .bind("ws_default") .bind("idem_conc_snapshot") .fetch_one(&mut *blocker) .await .unwrap(); let reader = registry.clone(); let reader_workspace = workspace_id.clone(); let read_task = tokio::spawn(async move { reader .get_onboarding_snapshot(&reader_workspace) .await .unwrap() }); wait_for_blocked_reader(&observer, blocker_pid).await; sqlx::query( "update operations set status = 'archived', updated_at = now() where workspace_id = 'ws_default' and id = 'op_conc_snapshot'", ) .execute(&mut *blocker) .await .unwrap(); blocker.commit().await.unwrap(); let snapshot = read_task.await.unwrap(); assert_eq!( snapshot.projection.revision, draft_revision, "the projection was read before the concurrent commit" ); let context = snapshot.import_context.expect("the context must survive"); assert!( context.choices[0].selectable, "choices must use the same old snapshot as the revision" ); let current = registry .get_onboarding_snapshot(&workspace_id) .await .unwrap(); assert_ne!(current.projection.revision, draft_revision); assert!(!current.import_context.unwrap().choices[0].selectable); database.cleanup().await; } /// Wait for an observed database lock, never assume a task started after a sleep. async fn wait_for_blocked_reader(pool: &sqlx::PgPool, blocker_pid: i32) { tokio::time::timeout(Duration::from_secs(10), async { loop { let blocked: bool = sqlx::query_scalar( "select exists(select 1 from pg_stat_activity where datname = current_database() and pid <> $1 and $1 = any(pg_blocking_pids(pid)))", ) .bind(blocker_pid) .fetch_one(pool) .await .unwrap(); if blocked { break; } tokio::time::sleep(Duration::from_millis(10)).await; } }) .await .unwrap_or_else(|_| panic!("the reader must contend on blocker {blocker_pid}")); }