use sqlx::Row; use super::*; fn count_sql(table: &str) -> sqlx::AssertSqlSafe { sqlx::AssertSqlSafe(format!("select count(*) from {table}")) } async fn count_rows(pool: &sqlx::PgPool, sql: sqlx::AssertSqlSafe) -> i64 { let value: i64 = sqlx::query_scalar::<_, i64>(sql) .fetch_one(pool) .await .unwrap(); value } async fn seed_import_plan_fixture(pool: &sqlx::PgPool) { let now = time::OffsetDateTime::now_utc(); sqlx::query( "insert into workspaces (id, slug, display_name, status, settings_json, created_at, updated_at) values ('ws_import_plan', 'import-plan', 'Import Plan', 'active', '{}'::jsonb, $1, $1)", ) .bind(now) .bind(now) .execute(pool) .await .unwrap(); sqlx::query( "insert into import_jobs ( id, workspace_id, kind, source_format, status, preview_payload, created_at, expires_at ) values ( 'job_v14', 'ws_import_plan', 'openapi', 'openapi', 'ready', '{}'::jsonb, $1, $1 + interval '1 hour' )", ) .bind(now) .bind(now) .execute(pool) .await .unwrap(); let digest = "ab".repeat(32); sqlx::query( "insert into import_plans ( workspace_id, id, job_id, digest, payload, created_at, expires_at ) values ( 'ws_import_plan', 'plan_v14', 'job_v14', $1, '{}'::jsonb, $2, $2 + interval '1 hour' )", ) .bind(&digest) .bind(now) .execute(pool) .await .unwrap(); sqlx::query( "insert into import_plan_applications ( workspace_id, idempotency_key, plan_id, plan_digest, report, created_at ) values ( 'ws_import_plan', 'idem_v14', 'plan_v14', $1, '{}'::jsonb, $2 )", ) .bind(&digest) .bind(now) .execute(pool) .await .unwrap(); } #[tokio::test] async fn fresh_install_exposes_import_plan_objects_with_cascading_job_fk() { let database_url = crank_test_support::postgres_schema_url("test_v14_fresh").await; let pool = sqlx::PgPool::connect(&database_url).await.unwrap(); MigrationAuthority::apply(&pool).await.unwrap(); assert_eq!( MigrationAuthority::preflight(&pool).await.unwrap(), MigrationPreflight::Current { version: 30 } ); let tables = sqlx::query( "select table_name from information_schema.tables where table_schema = current_schema() and table_name in ('import_plans', 'import_plan_applications') order by table_name", ) .fetch_all(&pool) .await .unwrap(); let names = tables .iter() .map(|row| row.get::("table_name")) .collect::>(); assert_eq!(names, vec!["import_plan_applications", "import_plans"]); // The plan FK to the job is immediate with ON DELETE CASCADE: a plan never // outlives its job. The applications table keeps only its workspace FK — // replay evidence must survive plan and job cleanup. let foreign_keys = sqlx::query( "select c.conname, c.condeferrable, c.condeferred, c.confdeltype::text as delete_rule from pg_catalog.pg_constraint c join pg_catalog.pg_class t on t.oid = c.conrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace where n.nspname = current_schema() and c.contype = 'f' and c.conname in ( 'import_plans_job_fk', 'import_plans_workspace_id_fkey', 'import_plan_applications_workspace_id_fkey' ) order by c.conname", ) .fetch_all(&pool) .await .unwrap(); assert_eq!( foreign_keys.len(), 3, "workspace-scoped FKs must all exist and the applications plan FK must be absent" ); for row in &foreign_keys { assert!( !row.get::("condeferrable"), "v14 plan FKs must be immediate, not deferrable" ); assert!( !row.get::("condeferred"), "v14 plan FKs must start immediate" ); assert_eq!( row.get::("delete_rule"), "c", "only workspace-cascading FKs may remain" ); } let plan_fk_absent: bool = sqlx::query_scalar( "select not exists ( select 1 from pg_catalog.pg_constraint c join pg_catalog.pg_class t on t.oid = c.conrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace where n.nspname = current_schema() and c.conname = 'import_plan_applications_plan_fk' )", ) .fetch_one(&pool) .await .unwrap(); assert!( plan_fk_absent, "replay evidence must not be pinned to the plan row" ); let unique: bool = sqlx::query_scalar( "select exists ( select 1 from pg_catalog.pg_constraint c join pg_catalog.pg_class t on t.oid = c.conrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace where n.nspname = current_schema() and t.relname = 'import_jobs' and c.conname = 'import_jobs_workspace_id_unique' and c.contype = 'u' )", ) .fetch_one(&pool) .await .unwrap(); assert!( unique, "workspace-scoped import job identity must be unique" ); } #[tokio::test] async fn healthy_v13_upgrades_to_v14_without_changing_prior_ledger() { let database_url = crank_test_support::postgres_schema_url("test_v13_to_v14_import_plan").await; let pool = sqlx::PgPool::connect(&database_url).await.unwrap(); MigrationAuthority::apply(&pool).await.unwrap(); let now = time::OffsetDateTime::now_utc(); sqlx::query( "insert into workspaces (id, slug, display_name, status, settings_json, created_at, updated_at) values ('ws_v13_data', 'v13-data', 'V13 Data', 'active', '{}'::jsonb, $1, $1)", ) .bind(now) .bind(now) .execute(&pool) .await .unwrap(); sqlx::query( "insert into import_jobs ( id, workspace_id, kind, source_format, status, preview_payload, created_at, expires_at ) values ( 'job_v13_data', 'ws_v13_data', 'openapi', 'openapi', 'ready', '{\"marker\":\"preserved\"}'::jsonb, $1, $1 + interval '1 hour' )", ) .bind(now) .bind(now) .execute(&pool) .await .unwrap(); remove_v14_schema(&pool).await; let job_before: String = sqlx::query_scalar( "select preview_payload::text || status from import_jobs where id = 'job_v13_data'", ) .fetch_one(&pool) .await .unwrap(); let prior = sqlx::query( "select version, name, checksum, phase, compatibility, applied_at from __crank_migrations where version <= 13 order by version", ) .fetch_all(&pool) .await .unwrap() .into_iter() .map(|row| { ( row.get::("version"), row.get::("name"), row.get::("checksum"), row.get::("phase"), row.get::("compatibility"), row.get::("applied_at"), ) }) .collect::>(); assert_eq!(prior.len(), 13, "the prior ledger must cover v1..v13"); assert_eq!( MigrationAuthority::preflight(&pool).await.unwrap(), MigrationPreflight::MigrationRequired { current: 13, target: 30, } ); MigrationAuthority::apply(&pool).await.unwrap(); let after = sqlx::query( "select version, name, checksum, phase, compatibility, applied_at from __crank_migrations where version <= 13 order by version", ) .fetch_all(&pool) .await .unwrap() .into_iter() .map(|row| { ( row.get::("version"), row.get::("name"), row.get::("checksum"), row.get::("phase"), row.get::("compatibility"), row.get::("applied_at"), ) }) .collect::>(); assert_eq!( after, prior, "prior ledger must survive the v13 -> v14 upgrade" ); let job_after: String = sqlx::query_scalar( "select preview_payload::text || status from import_jobs where id = 'job_v13_data'", ) .fetch_one(&pool) .await .unwrap(); assert_eq!( job_after, job_before, "existing import jobs must be untouched by the upgrade" ); let objects: i64 = count_rows( &pool, sqlx::AssertSqlSafe(String::from( "select count(*) from information_schema.tables where table_schema = current_schema() and table_name in ('import_plans', 'import_plan_applications')", )), ) .await; assert_eq!(objects, 2, "both v14 objects must exist after the upgrade"); } #[tokio::test] async fn wrong_workspace_foreign_key_is_rejected_immediately() { let database_url = crank_test_support::postgres_schema_url("test_v14_wrong_workspace").await; let pool = sqlx::PgPool::connect(&database_url).await.unwrap(); MigrationAuthority::apply(&pool).await.unwrap(); let now = time::OffsetDateTime::now_utc(); let mut transaction = pool.begin().await.unwrap(); for (workspace, label) in [("ws_job_owner", "job-owner"), ("ws_intruder", "intruder")] { sqlx::query( "insert into workspaces (id, slug, display_name, status, settings_json, created_at, updated_at) values ($1, $2, $2, 'active', '{}'::jsonb, $3, $3)", ) .bind(workspace) .bind(label) .bind(now) .execute(&mut *transaction) .await .unwrap(); } sqlx::query( "insert into import_jobs ( id, workspace_id, kind, source_format, status, preview_payload, created_at, expires_at ) values ( 'job_owned', 'ws_job_owner', 'openapi', 'openapi', 'ready', '{}'::jsonb, $1, $1 + interval '1 hour' )", ) .bind(now) .bind(now) .execute(&mut *transaction) .await .unwrap(); let digest = "ab".repeat(32); let error = sqlx::query( "insert into import_plans ( workspace_id, id, job_id, digest, payload, created_at, expires_at ) values ( 'ws_intruder', 'plan_cross_workspace', 'job_owned', $1, '{}'::jsonb, $2, $2 + interval '1 hour' )", ) .bind(&digest) .bind(now) .execute(&mut *transaction) .await .expect_err("a plan may not bind a job from another workspace"); assert!( error .to_string() .contains("violates foreign key constraint"), "wrong-workspace reference must fail the job FK: {}", error ); transaction.rollback().await.unwrap(); } #[tokio::test] async fn update_guards_reject_plan_and_application_mutations() { let database_url = crank_test_support::postgres_schema_url("test_v14_immutable").await; let pool = sqlx::PgPool::connect(&database_url).await.unwrap(); MigrationAuthority::apply(&pool).await.unwrap(); seed_import_plan_fixture(&pool).await; for statement in [ "update import_plans set expires_at = expires_at + interval '1 hour' where id = 'plan_v14'", "update import_plan_applications set report = report || jsonb_build_object('tampered', true) where idempotency_key = 'idem_v14'", ] { let error = sqlx::query(statement) .execute(&pool) .await .expect_err("import plan rows must be immutable"); assert!( error.to_string().contains("import plan rows are immutable"), "statement '{}' must hit the immutability guard: {}", statement, error ); } } #[tokio::test] async fn deletion_cascades_to_plans_but_preserves_application_anchor() { let database_url = crank_test_support::postgres_schema_url("test_v14_deletion_retention").await; let pool = sqlx::PgPool::connect(&database_url).await.unwrap(); MigrationAuthority::apply(&pool).await.unwrap(); seed_import_plan_fixture(&pool).await; // Deleting the plan succeeds: application rows are replay evidence, not // dependents. The anchor must keep its full replay data. let mut transaction = pool.begin().await.unwrap(); sqlx::query("delete from import_plans where id = 'plan_v14'") .execute(&mut *transaction) .await .unwrap(); transaction .commit() .await .expect("plan deletion must not be blocked by the application row"); let application_count = count_rows(&pool, count_sql("import_plan_applications")).await; assert_eq!( application_count, 1, "application must remain as replay evidence after plan deletion" ); // Re-create the plan anchored to its job, then delete the expired job: // the cascade must take the plan with it while the anchor survives. let now = time::OffsetDateTime::now_utc(); let digest = "ab".repeat(32); sqlx::query( "insert into import_plans ( workspace_id, id, job_id, digest, payload, created_at, expires_at ) values ( 'ws_import_plan', 'plan_v14', 'job_v14', $1, '{}'::jsonb, $2, $2 + interval '1 hour' )", ) .bind(&digest) .bind(now) .execute(&pool) .await .unwrap(); let mut transaction = pool.begin().await.unwrap(); sqlx::query("delete from import_jobs where id = 'job_v14'") .execute(&mut *transaction) .await .unwrap(); transaction .commit() .await .expect("job deletion must cascade to its plan, not be blocked by it"); assert_eq!( count_rows(&pool, count_sql("import_jobs")).await, 0, "the expired job must be gone" ); assert_eq!( count_rows(&pool, count_sql("import_plans")).await, 0, "the plan must cascade with its job" ); // The anchor row survives both deletions and is still replayable data. let anchor = sqlx::query( "select idempotency_key, plan_id, plan_digest, report from import_plan_applications where workspace_id = 'ws_import_plan'", ) .fetch_one(&pool) .await .expect("the application anchor must survive job and plan deletion"); assert_eq!( anchor.try_get::("idempotency_key").unwrap(), "idem_v14", "the idempotency identity must survive for replay" ); assert_eq!( anchor.try_get::("plan_id").unwrap(), "plan_v14", "the stored plan_id stays a history string, not an FK" ); assert_eq!(anchor.try_get::("plan_digest").unwrap(), digest); let report = anchor.try_get::("report").unwrap(); assert!(report.is_object(), "the report must stay valid jsonb"); } #[tokio::test] async fn workspace_deletion_cascades_to_jobs_plans_and_applications() { let database_url = crank_test_support::postgres_schema_url("test_v14_workspace_cascade").await; let pool = sqlx::PgPool::connect(&database_url).await.unwrap(); MigrationAuthority::apply(&pool).await.unwrap(); seed_import_plan_fixture(&pool).await; let mut transaction = pool.begin().await.unwrap(); sqlx::query("delete from workspaces where id = 'ws_import_plan'") .execute(&mut *transaction) .await .unwrap(); transaction .commit() .await .expect("workspace deletion must succeed after the cascades"); for table in ["import_jobs", "import_plans", "import_plan_applications"] { let count = count_rows(&pool, count_sql(table)).await; assert_eq!(count, 0, "{table} rows must cascade with the workspace"); } }