test_database_migrations.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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_data_element_migration_adds_versioned_governance_tables():
  164. migration = (
  165. ROOT
  166. / "migrations"
  167. / "versions"
  168. / "20260722_105_data_research_elements.py"
  169. ).read_text(encoding="utf-8")
  170. assert 'revision = "20260722_105"' in migration
  171. assert 'down_revision = "20260722_100"' in migration
  172. for table in ("data_elements", "data_element_versions", "candidate_decisions"):
  173. assert f"CREATE TABLE IF NOT EXISTS public.{table}" in migration
  174. assert "UNIQUE (data_element_uid, version)" in migration
  175. assert "DROP TABLE" not in migration.upper()
  176. def test_ontology_migration_adds_versioned_control_plane_tables():
  177. migration = (
  178. ROOT / "migrations" / "versions" / "20260722_110_data_research_ontology.py"
  179. ).read_text(encoding="utf-8")
  180. assert 'revision = "20260722_110"' in migration
  181. assert 'down_revision = "20260722_105"' in migration
  182. for table in (
  183. "ontologies",
  184. "ontology_versions",
  185. "ontology_domain_links",
  186. "ontology_change_sets",
  187. "ontology_publish_runs",
  188. ):
  189. assert f"CREATE TABLE IF NOT EXISTS public.{table}" in migration
  190. assert "UNIQUE (ontology_uid, version)" in migration
  191. assert "DROP TABLE" not in migration.upper()
  192. def test_alembic_configuration_is_environment_only():
  193. ini = (ROOT / "alembic.ini").read_text(encoding="utf-8")
  194. env = (ROOT / "migrations" / "env.py").read_text(encoding="utf-8")
  195. assert "sqlalchemy.url" not in ini
  196. assert "SQLALCHEMY_DATABASE_URI" in env
  197. assert "DATABASE_URL" in env
  198. assert "password" not in env.lower()
  199. def test_baseline_migration_is_non_destructive():
  200. baseline = (
  201. ROOT / "migrations" / "versions" / "20260716_01_baseline.py"
  202. ).read_text(encoding="utf-8")
  203. assert "def upgrade" in baseline
  204. assert "def downgrade" in baseline
  205. assert "drop_table" not in baseline
  206. for table in EXPECTED_BASELINE_TABLES:
  207. assert table in baseline
  208. @pytest.mark.integration
  209. def test_alembic_upgrade_is_repeatable_and_downgrade_preserves_tables():
  210. admin_url = os.environ.get("TEST_POSTGRES_ADMIN_URL")
  211. if not admin_url:
  212. pytest.skip("TEST_POSTGRES_ADMIN_URL is not configured")
  213. parsed = make_url(admin_url)
  214. database_name = f"dataops_migration_{uuid.uuid4().hex[:12]}"
  215. target_url = parsed.set(database=database_name).render_as_string(
  216. hide_password=False
  217. )
  218. connection = psycopg2.connect(admin_url)
  219. connection.autocommit = True
  220. try:
  221. with connection.cursor() as cursor:
  222. cursor.execute(f'CREATE DATABASE "{database_name}"')
  223. env = os.environ.copy()
  224. env["SQLALCHEMY_DATABASE_URI"] = target_url
  225. command = [str(ROOT / ".venv" / "bin" / "alembic"), "-c", "alembic.ini"]
  226. subprocess.run(command + ["upgrade", "head"], cwd=ROOT, env=env, check=True)
  227. subprocess.run(command + ["upgrade", "head"], cwd=ROOT, env=env, check=True)
  228. engine = create_engine(target_url)
  229. try:
  230. tables = set(inspect(engine).get_table_names(schema="public"))
  231. assert EXPECTED_BASELINE_TABLES | {"alembic_version"} <= tables
  232. assert tables >= EXPECTED_UPGRADED_TABLES
  233. finally:
  234. engine.dispose()
  235. subprocess.run(command + ["downgrade", "-1"], cwd=ROOT, env=env, check=True)
  236. engine = create_engine(target_url)
  237. try:
  238. tables = set(inspect(engine).get_table_names(schema="public"))
  239. assert tables >= EXPECTED_BASELINE_TABLES
  240. finally:
  241. engine.dispose()
  242. finally:
  243. with connection.cursor() as cursor:
  244. cursor.execute(
  245. "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
  246. "WHERE datname = %s AND pid <> pg_backend_pid()",
  247. (database_name,),
  248. )
  249. cursor.execute(f'DROP DATABASE IF EXISTS "{database_name}"')
  250. connection.close()
  251. @pytest.mark.integration
  252. @pytest.mark.parametrize(
  253. ("legacy_rows", "diagnostic"),
  254. (
  255. ((1, 1), "duplicate rule_run_id"),
  256. ((101,), "rows above 100"),
  257. ),
  258. )
  259. def test_upgrade_from_150_rejects_malformed_legacy_samples(
  260. legacy_rows,
  261. diagnostic,
  262. ):
  263. admin_url = os.environ.get("TEST_POSTGRES_ADMIN_URL")
  264. if not admin_url:
  265. pytest.skip("TEST_POSTGRES_ADMIN_URL is not configured")
  266. parsed = make_url(admin_url)
  267. database_name = f"dataops_evidence_{uuid.uuid4().hex[:12]}"
  268. target_url = parsed.set(database=database_name).render_as_string(
  269. hide_password=False
  270. )
  271. admin = psycopg2.connect(admin_url)
  272. admin.autocommit = True
  273. try:
  274. with admin.cursor() as cursor:
  275. cursor.execute(f'CREATE DATABASE "{database_name}"')
  276. env = os.environ.copy()
  277. env["SQLALCHEMY_DATABASE_URI"] = target_url
  278. command = [
  279. str(ROOT / ".venv" / "bin" / "alembic"),
  280. "-c",
  281. "alembic.ini",
  282. ]
  283. subprocess.run(
  284. command + ["upgrade", "20260723_150"],
  285. cwd=ROOT,
  286. env=env,
  287. check=True,
  288. )
  289. database = psycopg2.connect(target_url)
  290. try:
  291. database.autocommit = True
  292. with database.cursor() as cursor:
  293. cursor.execute("SET session_replication_role = replica")
  294. run_id = str(uuid.uuid4())
  295. cursor.execute(
  296. """
  297. INSERT INTO public.rule_runs (
  298. id, deployment_id, component_binding_id,
  299. rule_version_id, plan_hash, status, correlation_id
  300. ) VALUES (%s, %s, %s, %s, %s, 'failed', %s)
  301. """,
  302. (
  303. run_id,
  304. str(uuid.uuid4()),
  305. str(uuid.uuid4()),
  306. str(uuid.uuid4()),
  307. "a" * 64,
  308. str(uuid.uuid4()),
  309. ),
  310. )
  311. for count in legacy_rows:
  312. cursor.execute(
  313. """
  314. INSERT INTO public.rule_violation_samples (
  315. id, rule_run_id, artifact_ref, sample_count,
  316. redaction_policy, expires_at
  317. ) VALUES (%s, %s, %s, %s, 'legacy-v1', NOW())
  318. """,
  319. (
  320. str(uuid.uuid4()),
  321. run_id,
  322. f"minio://legacy/{uuid.uuid4()}",
  323. count,
  324. ),
  325. )
  326. cursor.execute("SET session_replication_role = origin")
  327. finally:
  328. database.close()
  329. failed = subprocess.run(
  330. command + ["upgrade", "head"],
  331. cwd=ROOT,
  332. env=env,
  333. text=True,
  334. capture_output=True,
  335. )
  336. assert failed.returncode != 0
  337. assert diagnostic in (failed.stdout + failed.stderr)
  338. database = psycopg2.connect(target_url)
  339. try:
  340. with database.cursor() as cursor:
  341. cursor.execute(
  342. "SELECT version_num FROM public.alembic_version"
  343. )
  344. assert cursor.fetchone()[0] == "20260723_150"
  345. finally:
  346. database.close()
  347. finally:
  348. with admin.cursor() as cursor:
  349. cursor.execute(
  350. "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
  351. "WHERE datname = %s AND pid <> pg_backend_pid()",
  352. (database_name,),
  353. )
  354. cursor.execute(f'DROP DATABASE IF EXISTS "{database_name}"')
  355. admin.close()
  356. @pytest.mark.integration
  357. def test_concurrent_alembic_upgrades_are_serialized():
  358. admin_url = os.environ.get("TEST_POSTGRES_ADMIN_URL")
  359. if not admin_url:
  360. pytest.skip("TEST_POSTGRES_ADMIN_URL is not configured")
  361. parsed = make_url(admin_url)
  362. database_name = f"dataops_concurrent_{uuid.uuid4().hex[:12]}"
  363. target_url = parsed.set(database=database_name).render_as_string(
  364. hide_password=False
  365. )
  366. connection = psycopg2.connect(admin_url)
  367. connection.autocommit = True
  368. try:
  369. with connection.cursor() as cursor:
  370. cursor.execute(f'CREATE DATABASE "{database_name}"')
  371. env = os.environ.copy()
  372. env["SQLALCHEMY_DATABASE_URI"] = target_url
  373. command = [
  374. str(ROOT / ".venv" / "bin" / "alembic"),
  375. "-c",
  376. "alembic.ini",
  377. "upgrade",
  378. "head",
  379. ]
  380. processes = [
  381. subprocess.Popen(
  382. command,
  383. cwd=ROOT,
  384. env=env,
  385. stdout=subprocess.PIPE,
  386. stderr=subprocess.STDOUT,
  387. text=True,
  388. )
  389. for _ in range(2)
  390. ]
  391. results = [process.communicate(timeout=120) for process in processes]
  392. failures = [
  393. output
  394. for process, (output, _) in zip(processes, results)
  395. if process.returncode != 0
  396. ]
  397. assert failures == []
  398. engine = create_engine(target_url)
  399. try:
  400. assert set(inspect(engine).get_table_names(schema="public")) >= (
  401. EXPECTED_UPGRADED_TABLES | {"alembic_version"}
  402. )
  403. finally:
  404. engine.dispose()
  405. finally:
  406. with connection.cursor() as cursor:
  407. cursor.execute(
  408. "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
  409. "WHERE datname = %s AND pid <> pg_backend_pid()",
  410. (database_name,),
  411. )
  412. cursor.execute(f'DROP DATABASE IF EXISTS "{database_name}"')
  413. connection.close()