test_database_migrations.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. from __future__ import annotations
  2. import os
  3. import subprocess
  4. import uuid
  5. from pathlib import Path
  6. import psycopg2
  7. import pytest
  8. from sqlalchemy import create_engine, inspect
  9. from sqlalchemy.engine import make_url
  10. ROOT = Path(__file__).resolve().parents[1]
  11. EXPECTED_BASELINE_TABLES = {
  12. "data_orders",
  13. "data_products",
  14. "metadata_review_records",
  15. "metadata_version_history",
  16. "task_list",
  17. "users",
  18. }
  19. EXPECTED_UPGRADED_TABLES = {
  20. "datasource_credentials",
  21. "datasource_credential_audit_events",
  22. "workflow_schedules",
  23. "workflow_runs",
  24. "workflow_task_runs",
  25. "workflow_engine_bindings",
  26. "workflow_plan_audits",
  27. "runner_task_executions",
  28. "workflow_canary_evidence",
  29. "workflow_gateway_operations",
  30. "workflow_migration_states",
  31. "workflow_dual_runs",
  32. "workflow_reconciliation_reports",
  33. "workflow_cutover_operations",
  34. "rule_sql_staging_receipts",
  35. "ingestion_sources",
  36. "source_artifacts",
  37. "ingestion_jobs",
  38. "evidence_fragments",
  39. "extraction_candidates",
  40. "data_elements",
  41. "data_element_versions",
  42. "candidate_decisions",
  43. "ontologies",
  44. "ontology_versions",
  45. "ontology_domain_links",
  46. "ontology_change_sets",
  47. "ontology_publish_runs",
  48. "governance_responsibility_scopes",
  49. "governance_responsibility_assignments",
  50. "governance_responsibility_audit_events",
  51. "catalog_snapshots",
  52. "device_assets",
  53. "device_asset_source_mappings",
  54. "device_asset_versions",
  55. "device_semantic_codes",
  56. "device_semantic_code_versions",
  57. "device_semantic_code_reviews",
  58. }
  59. def test_data_research_ingestion_migration_is_additive_and_constrained():
  60. migration = (
  61. ROOT
  62. / "migrations"
  63. / "versions"
  64. / "20260722_100_data_research_ingestion.py"
  65. ).read_text(encoding="utf-8")
  66. assert 'revision = "20260722_100"' in migration
  67. assert 'down_revision = "20260720_100"' in migration
  68. for table in (
  69. "ingestion_sources",
  70. "source_artifacts",
  71. "ingestion_jobs",
  72. "evidence_fragments",
  73. "extraction_candidates",
  74. ):
  75. assert f"CREATE TABLE IF NOT EXISTS public.{table}" in migration
  76. assert "idempotency_key" in migration
  77. assert "parser_version" in migration
  78. assert "locator JSONB" in migration
  79. assert "DROP TABLE" not in migration.upper()
  80. def test_catalog_execution_migration_adds_attempts_and_snapshots():
  81. migration = (
  82. ROOT
  83. / "migrations"
  84. / "versions"
  85. / "20260729_280_catalog_ingestion_execution.py"
  86. ).read_text(encoding="utf-8")
  87. assert 'revision = "20260729_280"' in migration
  88. assert 'down_revision = "20260729_270"' in migration
  89. assert "ADD COLUMN attempt_count" in migration
  90. assert "ADD COLUMN failure_stage" in migration
  91. assert "CREATE TABLE public.catalog_snapshots" in migration
  92. assert "UNIQUE (job_uid, attempt)" in migration
  93. assert "DROP TABLE" not in migration.upper()
  94. def test_device_asset_catalog_migration_is_versioned_and_traceable():
  95. migration = (
  96. ROOT
  97. / "migrations"
  98. / "versions"
  99. / "20260729_290_device_asset_catalog.py"
  100. ).read_text(encoding="utf-8")
  101. assert 'revision = "20260729_290"' in migration
  102. assert 'down_revision = "20260729_280"' in migration
  103. for table in (
  104. "device_assets",
  105. "device_asset_source_mappings",
  106. "device_asset_versions",
  107. ):
  108. assert f"CREATE TABLE public.{table}" in migration
  109. assert (
  110. "UNIQUE (source_uid, source_entity, asset_type, source_code)"
  111. in migration
  112. )
  113. assert "UNIQUE (asset_uid, version)" in migration
  114. assert "source_updated_at" in migration
  115. assert "snapshot JSONB NOT NULL" in migration
  116. assert "DROP TABLE" not in migration.upper()
  117. def test_device_semantics_migration_is_versioned_reviewed_and_traceable():
  118. migration = (
  119. ROOT
  120. / "migrations"
  121. / "versions"
  122. / "20260729_300_device_semantics.py"
  123. ).read_text(encoding="utf-8")
  124. assert 'revision = "20260729_300"' in migration
  125. assert 'down_revision = "20260729_290"' in migration
  126. for table in (
  127. "device_semantic_codes",
  128. "device_semantic_code_versions",
  129. "device_semantic_code_reviews",
  130. ):
  131. assert f"CREATE TABLE public.{table}" in migration
  132. assert "UNIQUE (ontology_uid, code_type, canonical_code)" in migration
  133. assert "UNIQUE (code_uid, version)" in migration
  134. assert "source_mappings JSONB NOT NULL" in migration
  135. assert "evidence_uids JSONB NOT NULL" in migration
  136. assert "decision IN ('approve','reject')" in migration
  137. assert "DROP TABLE" not in migration.upper()
  138. def test_device_entity_resolution_migration_is_non_destructive_and_reversible():
  139. migration = (
  140. ROOT
  141. / "migrations"
  142. / "versions"
  143. / "20260729_310_device_entity_resolution.py"
  144. ).read_text(encoding="utf-8")
  145. assert 'revision = "20260729_310"' in migration
  146. assert 'down_revision = "20260729_300"' in migration
  147. for table in (
  148. "device_entity_match_candidates",
  149. "device_entity_match_reviews",
  150. "device_entity_merge_events",
  151. "device_entity_merge_rollbacks",
  152. ):
  153. assert f"CREATE TABLE public.{table}" in migration
  154. assert "explanation JSONB NOT NULL" in migration
  155. assert "evidence_uids JSONB NOT NULL" in migration
  156. assert "decision IN ('approve','reject','auto_approve')" in migration
  157. assert "canonical_asset_uid" in migration
  158. assert "member_asset_uid" in migration
  159. assert "snapshot JSONB NOT NULL" in migration
  160. assert "DROP TABLE" not in migration.upper()
  161. assert "DELETE FROM public.device_assets" not in migration
  162. assert "UPDATE public.device_asset_source_mappings" not in migration
  163. def test_device_quality_migration_is_non_destructive_and_reversible():
  164. migration = (
  165. ROOT
  166. / "migrations"
  167. / "versions"
  168. / "20260729_320_device_quality.py"
  169. ).read_text(encoding="utf-8")
  170. assert 'revision = "20260729_320"' in migration
  171. assert 'down_revision = "20260729_310"' in migration
  172. for table in (
  173. "device_quality_profiles",
  174. "device_quality_profile_versions",
  175. "device_quality_runs",
  176. "device_quality_rule_results",
  177. "device_quality_violation_samples",
  178. "device_quality_asset_scores",
  179. ):
  180. assert f"CREATE TABLE public.{table}" in migration
  181. assert "rules JSONB NOT NULL" in migration
  182. assert "policy_hash CHAR(64) NOT NULL" in migration
  183. assert "evidence JSONB NOT NULL" in migration
  184. assert "UNIQUE (run_uid, rule_code)" in migration
  185. assert "UNIQUE (run_uid, asset_uid)" in migration
  186. assert "DROP TABLE" not in migration.upper()
  187. assert "DELETE FROM public.device_assets" not in migration
  188. assert "UPDATE public.device_asset_source_mappings" not in migration
  189. def test_device_quality_responsibility_type_migration_is_additive():
  190. migration = (
  191. ROOT
  192. / "migrations"
  193. / "versions"
  194. / "20260729_330_device_quality_responsibility_type.py"
  195. ).read_text(encoding="utf-8")
  196. assert 'revision = "20260729_330"' in migration
  197. assert 'down_revision = "20260729_320"' in migration
  198. assert "device_quality" in migration
  199. assert "DROP TABLE" not in migration.upper()
  200. assert "DELETE FROM" not in migration.upper()
  201. def test_data_element_migration_adds_versioned_governance_tables():
  202. migration = (
  203. ROOT
  204. / "migrations"
  205. / "versions"
  206. / "20260722_105_data_research_elements.py"
  207. ).read_text(encoding="utf-8")
  208. assert 'revision = "20260722_105"' in migration
  209. assert 'down_revision = "20260722_100"' in migration
  210. for table in ("data_elements", "data_element_versions", "candidate_decisions"):
  211. assert f"CREATE TABLE IF NOT EXISTS public.{table}" in migration
  212. assert "UNIQUE (data_element_uid, version)" in migration
  213. assert "DROP TABLE" not in migration.upper()
  214. def test_ontology_migration_adds_versioned_control_plane_tables():
  215. migration = (
  216. ROOT / "migrations" / "versions" / "20260722_110_data_research_ontology.py"
  217. ).read_text(encoding="utf-8")
  218. assert 'revision = "20260722_110"' in migration
  219. assert 'down_revision = "20260722_105"' in migration
  220. for table in (
  221. "ontologies",
  222. "ontology_versions",
  223. "ontology_domain_links",
  224. "ontology_change_sets",
  225. "ontology_publish_runs",
  226. ):
  227. assert f"CREATE TABLE IF NOT EXISTS public.{table}" in migration
  228. assert "UNIQUE (ontology_uid, version)" in migration
  229. assert "DROP TABLE" not in migration.upper()
  230. def test_alembic_configuration_is_environment_only():
  231. ini = (ROOT / "alembic.ini").read_text(encoding="utf-8")
  232. env = (ROOT / "migrations" / "env.py").read_text(encoding="utf-8")
  233. assert "sqlalchemy.url" not in ini
  234. assert "SQLALCHEMY_DATABASE_URI" in env
  235. assert "DATABASE_URL" in env
  236. assert "password" not in env.lower()
  237. def test_baseline_migration_is_non_destructive():
  238. baseline = (
  239. ROOT / "migrations" / "versions" / "20260716_01_baseline.py"
  240. ).read_text(encoding="utf-8")
  241. assert "def upgrade" in baseline
  242. assert "def downgrade" in baseline
  243. assert "drop_table" not in baseline
  244. for table in EXPECTED_BASELINE_TABLES:
  245. assert table in baseline
  246. @pytest.mark.integration
  247. def test_alembic_upgrade_is_repeatable_and_downgrade_preserves_tables():
  248. admin_url = os.environ.get("TEST_POSTGRES_ADMIN_URL")
  249. if not admin_url:
  250. pytest.skip("TEST_POSTGRES_ADMIN_URL is not configured")
  251. parsed = make_url(admin_url)
  252. database_name = f"dataops_migration_{uuid.uuid4().hex[:12]}"
  253. target_url = parsed.set(database=database_name).render_as_string(
  254. hide_password=False
  255. )
  256. connection = psycopg2.connect(admin_url)
  257. connection.autocommit = True
  258. try:
  259. with connection.cursor() as cursor:
  260. cursor.execute(f'CREATE DATABASE "{database_name}"')
  261. env = os.environ.copy()
  262. env["SQLALCHEMY_DATABASE_URI"] = target_url
  263. command = [str(ROOT / ".venv" / "bin" / "alembic"), "-c", "alembic.ini"]
  264. subprocess.run(command + ["upgrade", "head"], cwd=ROOT, env=env, check=True)
  265. subprocess.run(command + ["upgrade", "head"], cwd=ROOT, env=env, check=True)
  266. engine = create_engine(target_url)
  267. try:
  268. tables = set(inspect(engine).get_table_names(schema="public"))
  269. assert EXPECTED_BASELINE_TABLES | {"alembic_version"} <= tables
  270. assert tables >= EXPECTED_UPGRADED_TABLES
  271. finally:
  272. engine.dispose()
  273. subprocess.run(command + ["downgrade", "-1"], cwd=ROOT, env=env, check=True)
  274. engine = create_engine(target_url)
  275. try:
  276. tables = set(inspect(engine).get_table_names(schema="public"))
  277. assert tables >= EXPECTED_BASELINE_TABLES
  278. finally:
  279. engine.dispose()
  280. finally:
  281. with connection.cursor() as cursor:
  282. cursor.execute(
  283. "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
  284. "WHERE datname = %s AND pid <> pg_backend_pid()",
  285. (database_name,),
  286. )
  287. cursor.execute(f'DROP DATABASE IF EXISTS "{database_name}"')
  288. connection.close()
  289. @pytest.mark.integration
  290. @pytest.mark.parametrize(
  291. ("legacy_rows", "diagnostic"),
  292. (
  293. ((1, 1), "duplicate rule_run_id"),
  294. ((101,), "rows above 100"),
  295. ),
  296. )
  297. def test_upgrade_from_150_rejects_malformed_legacy_samples(
  298. legacy_rows,
  299. diagnostic,
  300. ):
  301. admin_url = os.environ.get("TEST_POSTGRES_ADMIN_URL")
  302. if not admin_url:
  303. pytest.skip("TEST_POSTGRES_ADMIN_URL is not configured")
  304. parsed = make_url(admin_url)
  305. database_name = f"dataops_evidence_{uuid.uuid4().hex[:12]}"
  306. target_url = parsed.set(database=database_name).render_as_string(
  307. hide_password=False
  308. )
  309. admin = psycopg2.connect(admin_url)
  310. admin.autocommit = True
  311. try:
  312. with admin.cursor() as cursor:
  313. cursor.execute(f'CREATE DATABASE "{database_name}"')
  314. env = os.environ.copy()
  315. env["SQLALCHEMY_DATABASE_URI"] = target_url
  316. command = [
  317. str(ROOT / ".venv" / "bin" / "alembic"),
  318. "-c",
  319. "alembic.ini",
  320. ]
  321. subprocess.run(
  322. command + ["upgrade", "20260723_150"],
  323. cwd=ROOT,
  324. env=env,
  325. check=True,
  326. )
  327. database = psycopg2.connect(target_url)
  328. try:
  329. database.autocommit = True
  330. with database.cursor() as cursor:
  331. cursor.execute("SET session_replication_role = replica")
  332. run_id = str(uuid.uuid4())
  333. cursor.execute(
  334. """
  335. INSERT INTO public.rule_runs (
  336. id, deployment_id, component_binding_id,
  337. rule_version_id, plan_hash, status, correlation_id
  338. ) VALUES (%s, %s, %s, %s, %s, 'failed', %s)
  339. """,
  340. (
  341. run_id,
  342. str(uuid.uuid4()),
  343. str(uuid.uuid4()),
  344. str(uuid.uuid4()),
  345. "a" * 64,
  346. str(uuid.uuid4()),
  347. ),
  348. )
  349. for count in legacy_rows:
  350. cursor.execute(
  351. """
  352. INSERT INTO public.rule_violation_samples (
  353. id, rule_run_id, artifact_ref, sample_count,
  354. redaction_policy, expires_at
  355. ) VALUES (%s, %s, %s, %s, 'legacy-v1', NOW())
  356. """,
  357. (
  358. str(uuid.uuid4()),
  359. run_id,
  360. f"minio://legacy/{uuid.uuid4()}",
  361. count,
  362. ),
  363. )
  364. cursor.execute("SET session_replication_role = origin")
  365. finally:
  366. database.close()
  367. failed = subprocess.run(
  368. command + ["upgrade", "head"],
  369. cwd=ROOT,
  370. env=env,
  371. text=True,
  372. capture_output=True,
  373. )
  374. assert failed.returncode != 0
  375. assert diagnostic in (failed.stdout + failed.stderr)
  376. database = psycopg2.connect(target_url)
  377. try:
  378. with database.cursor() as cursor:
  379. cursor.execute(
  380. "SELECT version_num FROM public.alembic_version"
  381. )
  382. assert cursor.fetchone()[0] == "20260723_150"
  383. finally:
  384. database.close()
  385. finally:
  386. with admin.cursor() as cursor:
  387. cursor.execute(
  388. "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
  389. "WHERE datname = %s AND pid <> pg_backend_pid()",
  390. (database_name,),
  391. )
  392. cursor.execute(f'DROP DATABASE IF EXISTS "{database_name}"')
  393. admin.close()
  394. @pytest.mark.integration
  395. def test_concurrent_alembic_upgrades_are_serialized():
  396. admin_url = os.environ.get("TEST_POSTGRES_ADMIN_URL")
  397. if not admin_url:
  398. pytest.skip("TEST_POSTGRES_ADMIN_URL is not configured")
  399. parsed = make_url(admin_url)
  400. database_name = f"dataops_concurrent_{uuid.uuid4().hex[:12]}"
  401. target_url = parsed.set(database=database_name).render_as_string(
  402. hide_password=False
  403. )
  404. connection = psycopg2.connect(admin_url)
  405. connection.autocommit = True
  406. try:
  407. with connection.cursor() as cursor:
  408. cursor.execute(f'CREATE DATABASE "{database_name}"')
  409. env = os.environ.copy()
  410. env["SQLALCHEMY_DATABASE_URI"] = target_url
  411. command = [
  412. str(ROOT / ".venv" / "bin" / "alembic"),
  413. "-c",
  414. "alembic.ini",
  415. "upgrade",
  416. "head",
  417. ]
  418. processes = [
  419. subprocess.Popen(
  420. command,
  421. cwd=ROOT,
  422. env=env,
  423. stdout=subprocess.PIPE,
  424. stderr=subprocess.STDOUT,
  425. text=True,
  426. )
  427. for _ in range(2)
  428. ]
  429. results = [process.communicate(timeout=120) for process in processes]
  430. failures = [
  431. output
  432. for process, (output, _) in zip(processes, results)
  433. if process.returncode != 0
  434. ]
  435. assert failures == []
  436. engine = create_engine(target_url)
  437. try:
  438. assert set(inspect(engine).get_table_names(schema="public")) >= (
  439. EXPECTED_UPGRADED_TABLES | {"alembic_version"}
  440. )
  441. finally:
  442. engine.dispose()
  443. finally:
  444. with connection.cursor() as cursor:
  445. cursor.execute(
  446. "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
  447. "WHERE datname = %s AND pid <> pg_backend_pid()",
  448. (database_name,),
  449. )
  450. cursor.execute(f'DROP DATABASE IF EXISTS "{database_name}"')
  451. connection.close()