test_rule_sql.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. from __future__ import annotations
  2. from contextlib import contextmanager
  3. import pytest
  4. from app.core.common.identifiers import new_governance_uid
  5. from app.core.data_source.errors import DataSourceWriteOutcomeUnknown
  6. from app.runner.nodes import NodeExecutionError
  7. class Definition:
  8. def __init__(self, dialect):
  9. self.database_type = dialect
  10. self.extra_properties = {
  11. "sql_rule_capabilities": {
  12. "dialect": dialect,
  13. "timezone": "Asia/Shanghai",
  14. "collation": "C" if dialect == "postgresql" else "utf8mb4_0900_bin",
  15. "rounding_mode": "half_away_from_zero",
  16. "regex_engine": "posix" if dialect == "postgresql" else "icu",
  17. }
  18. }
  19. class Definitions:
  20. def __init__(self, definition):
  21. self.definition = definition
  22. def get(self, _uid):
  23. return self.definition
  24. class Result:
  25. def __init__(self, *, scalar=None, rowcount=0, rows=None):
  26. self._scalar = scalar
  27. self.rowcount = rowcount
  28. self._rows = rows or []
  29. def scalar_one(self):
  30. return self._scalar
  31. def mappings(self):
  32. return self
  33. def all(self):
  34. return self._rows
  35. class Connection:
  36. def __init__(self, unique_rows=None):
  37. self.calls = []
  38. self.unique_rows = unique_rows
  39. def execute(self, statement, parameters):
  40. self.calls.append((str(statement), parameters))
  41. if len(self.calls) == 1:
  42. return Result(scalar=3)
  43. if len(self.calls) == 2:
  44. return Result(scalar=2)
  45. if "information_schema" in str(statement):
  46. return Result(
  47. rows=self.unique_rows
  48. if self.unique_rows is not None
  49. else [
  50. {
  51. "constraint_name": "customer_pkey",
  52. "constraint_type": "PRIMARY KEY",
  53. "columns": ["id"],
  54. }
  55. ]
  56. )
  57. return Result(rowcount=2)
  58. class Manager:
  59. def __init__(
  60. self,
  61. dialect="postgresql",
  62. *,
  63. unknown_commit=False,
  64. unique_rows=None,
  65. ):
  66. self.definitions = Definitions(Definition(dialect))
  67. self.connection = Connection(unique_rows)
  68. self.unknown_commit = unknown_commit
  69. self.calls = []
  70. @contextmanager
  71. def connect(self, uid, purpose):
  72. self.calls.append((uid, purpose))
  73. yield self.connection
  74. if self.unknown_commit:
  75. raise DataSourceWriteOutcomeUnknown()
  76. def sql_plan(dialect="postgresql"):
  77. from app.core.data_rules.compilers.sql import (
  78. COMPILER_VERSION,
  79. bound_sql_plan_hash,
  80. )
  81. uid = new_governance_uid()
  82. capabilities = Definition(dialect).extra_properties["sql_rule_capabilities"]
  83. quote = '"' if dialect == "postgresql" else "`"
  84. plan = {
  85. "schema_version": "1.0",
  86. "compiler_version": COMPILER_VERSION,
  87. "dialect": dialect,
  88. "capabilities": capabilities,
  89. "data_source_uid": uid,
  90. "rule_version_id": new_governance_uid(),
  91. "rule_spec_hash": "a" * 64,
  92. "input_schema_snapshot_id": new_governance_uid(),
  93. "input_schema_hash": "b" * 64,
  94. "output_schema_snapshot_id": new_governance_uid(),
  95. "output_schema_hash": "c" * 64,
  96. "input_binding_id": new_governance_uid(),
  97. "output_binding_id": new_governance_uid(),
  98. "statements": [
  99. {
  100. "purpose": "write",
  101. "sql": (
  102. f"INSERT INTO {quote}clean{quote}.{quote}customer{quote} "
  103. f"({quote}id{quote}) SELECT {quote}id{quote} "
  104. f"FROM {quote}raw{quote}.{quote}customer{quote}"
  105. ),
  106. "parameters": {},
  107. }
  108. ],
  109. "result_contract": {
  110. "rows_in": "counted",
  111. "rows_out": "counted",
  112. "rows_rejected": "counted",
  113. },
  114. }
  115. return plan, bound_sql_plan_hash(plan)
  116. def node_for(plan, plan_hash):
  117. return {
  118. "id": "task4_rule",
  119. "type": "rule.apply",
  120. "purpose": "write",
  121. "idempotency": {"strategy": "upsert", "key": "id"},
  122. "config": {
  123. "component_binding_id": new_governance_uid(),
  124. "rule_version_id": plan["rule_version_id"],
  125. "execution_plan_hash": plan_hash,
  126. },
  127. }
  128. def test_sqlglot_rule_adapter_verifies_and_executes_one_transaction():
  129. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  130. plan, plan_hash = sql_plan()
  131. node = node_for(plan, plan_hash)
  132. manager = Manager()
  133. result = SqlGlotRulePlanAdapter(manager).execute(
  134. plan=plan,
  135. node=node,
  136. parameters={},
  137. write_authorized=True,
  138. )
  139. assert result == {
  140. "rows_in": 3,
  141. "rows_out": 2,
  142. "rows_rejected": 1,
  143. "commit_outcome": "committed",
  144. }
  145. assert manager.calls == [(plan["data_source_uid"], "dataflow_write")]
  146. assert len(manager.connection.calls) == 4
  147. def test_sqlglot_quality_adapter_executes_published_sql_plan_read_only():
  148. from app.runner.rule_sql import SqlGlotQualityPlanAdapter
  149. plan, plan_hash = sql_plan()
  150. node = node_for(plan, plan_hash)
  151. node["type"] = "quality.check"
  152. node["purpose"] = "read"
  153. del node["idempotency"]
  154. manager = Manager()
  155. result = SqlGlotQualityPlanAdapter(manager).execute(
  156. plan=plan,
  157. node=node,
  158. parameters={},
  159. write_authorized=False,
  160. )
  161. assert result == {
  162. "rows_in": 3,
  163. "rows_out": 2,
  164. "rows_rejected": 1,
  165. "rows_quarantined": 0,
  166. "violation_count": 1,
  167. "violations": [{"step_id": "quality_check", "count": 1}],
  168. "commit_outcome": "not_applicable",
  169. }
  170. assert manager.calls == [(plan["data_source_uid"], "dataflow_read")]
  171. assert len(manager.connection.calls) == 2
  172. def test_sqlglot_quality_adapter_fails_closed_for_write_or_runtime_parameters():
  173. from app.runner.rule_sql import SqlGlotQualityPlanAdapter
  174. plan, plan_hash = sql_plan()
  175. node = node_for(plan, plan_hash)
  176. node["type"] = "quality.check"
  177. node["purpose"] = "read"
  178. del node["idempotency"]
  179. adapter = SqlGlotQualityPlanAdapter(Manager())
  180. with pytest.raises(NodeExecutionError, match="read only"):
  181. adapter.execute(
  182. plan=plan,
  183. node={**node, "purpose": "write"},
  184. parameters={},
  185. write_authorized=False,
  186. )
  187. with pytest.raises(NodeExecutionError, match="runtime parameters"):
  188. adapter.execute(
  189. plan=plan,
  190. node=node,
  191. parameters={"partition": "2026-07-24"},
  192. write_authorized=False,
  193. )
  194. def test_sqlglot_rule_adapter_fails_closed_for_dialect_hash_and_authorization():
  195. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  196. plan, plan_hash = sql_plan()
  197. node = node_for(plan, plan_hash)
  198. with pytest.raises(NodeExecutionError, match="dialect"):
  199. SqlGlotRulePlanAdapter(Manager("mysql")).execute(
  200. plan=plan,
  201. node=node,
  202. parameters={},
  203. write_authorized=True,
  204. )
  205. node["config"]["execution_plan_hash"] = "0" * 64
  206. with pytest.raises(NodeExecutionError, match="hash"):
  207. SqlGlotRulePlanAdapter(Manager()).execute(
  208. plan=plan,
  209. node=node,
  210. parameters={},
  211. write_authorized=True,
  212. )
  213. node["config"]["execution_plan_hash"] = plan_hash
  214. with pytest.raises(NodeExecutionError, match="authorization"):
  215. SqlGlotRulePlanAdapter(Manager()).execute(
  216. plan=plan,
  217. node=node,
  218. parameters={},
  219. write_authorized=False,
  220. )
  221. def test_sqlglot_rule_adapter_rejects_unimplemented_idempotency_strategy():
  222. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  223. plan, plan_hash = sql_plan()
  224. node = node_for(plan, plan_hash)
  225. node["idempotency"] = {
  226. "strategy": "partition_replace",
  227. "key": "task4",
  228. }
  229. with pytest.raises(NodeExecutionError, match="idempotency"):
  230. SqlGlotRulePlanAdapter(Manager()).execute(
  231. plan=plan,
  232. node=node,
  233. parameters={},
  234. write_authorized=True,
  235. )
  236. def test_rule_executor_matches_node_idempotency_to_persisted_component():
  237. from app.runner.rules import RulePlanExecutor
  238. plan, plan_hash = sql_plan()
  239. node = node_for(plan, plan_hash)
  240. class Repository:
  241. def load(self, **_kwargs):
  242. return {
  243. "component_binding_id": node["config"]["component_binding_id"],
  244. "rule_version_id": plan["rule_version_id"],
  245. "backend": "sql_pushdown",
  246. "plan": plan,
  247. "plan_hash": plan_hash,
  248. "plan_status": "published",
  249. "rule_status": "published",
  250. "publication_audit_trusted": True,
  251. "logical_evidence_trusted": True,
  252. "physical_evidence_trusted": True,
  253. "component_kind": "rule.apply",
  254. "binding_idempotency": {
  255. "strategy": "upsert",
  256. "key": "different_id",
  257. },
  258. }
  259. class Adapter:
  260. def execute(self, **_kwargs):
  261. return {"rows_in": 0, "rows_out": 0, "rows_rejected": 0}
  262. with pytest.raises(NodeExecutionError, match="idempotency"):
  263. RulePlanExecutor(
  264. Repository(),
  265. adapters={"sql_pushdown": Adapter()},
  266. ).execute(node, {}, write_authorized=True)
  267. def test_rule_executor_rechecks_canonical_rule_schema_and_compiler_attestations():
  268. from app.core.data_rules.compilers.sql import COMPILER_VERSION
  269. from app.runner.rules import RulePlanExecutor
  270. plan, plan_hash = sql_plan()
  271. node = node_for(plan, plan_hash)
  272. def record(**overrides):
  273. value = {
  274. "component_binding_id": node["config"]["component_binding_id"],
  275. "rule_version_id": plan["rule_version_id"],
  276. "backend": "sql_pushdown",
  277. "compiler_version": COMPILER_VERSION,
  278. "plan": plan,
  279. "plan_hash": plan_hash,
  280. "schema_hashes": {
  281. "rule_spec_hash": plan["rule_spec_hash"],
  282. "input_schema_snapshot_id": plan[
  283. "input_schema_snapshot_id"
  284. ],
  285. "input_schema_hash": plan["input_schema_hash"],
  286. "output_schema_snapshot_id": plan[
  287. "output_schema_snapshot_id"
  288. ],
  289. "output_schema_hash": plan["output_schema_hash"],
  290. },
  291. "canonical_rule_spec_hash": plan["rule_spec_hash"],
  292. "canonical_input_schema_snapshot_id": plan[
  293. "input_schema_snapshot_id"
  294. ],
  295. "canonical_input_schema_hash": plan["input_schema_hash"],
  296. "canonical_output_schema_snapshot_id": plan[
  297. "output_schema_snapshot_id"
  298. ],
  299. "canonical_output_schema_hash": plan["output_schema_hash"],
  300. "plan_status": "published",
  301. "rule_status": "published",
  302. "publication_audit_trusted": True,
  303. "logical_evidence_trusted": True,
  304. "physical_evidence_trusted": True,
  305. "component_kind": "rule.apply",
  306. "binding_idempotency": node["idempotency"],
  307. }
  308. value.update(overrides)
  309. return value
  310. class Repository:
  311. def __init__(self, value):
  312. self.value = value
  313. def load(self, **_kwargs):
  314. return self.value
  315. class Adapter:
  316. def execute(self, **_kwargs):
  317. return {"rows_in": 0, "rows_out": 0, "rows_rejected": 0}
  318. for tampered in (
  319. {"compiler_version": "dataops-sqlglot-99.0.0"},
  320. {"canonical_rule_spec_hash": "f" * 64},
  321. {"canonical_input_schema_hash": "e" * 64},
  322. {"canonical_output_schema_snapshot_id": new_governance_uid()},
  323. ):
  324. with pytest.raises(NodeExecutionError, match="attestation"):
  325. RulePlanExecutor(
  326. Repository(record(**tampered)),
  327. adapters={"sql_pushdown": Adapter()},
  328. ).execute(node, {}, write_authorized=True)
  329. def test_sqlglot_rule_adapter_reports_unknown_commit_outcome():
  330. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  331. plan, plan_hash = sql_plan()
  332. with pytest.raises(NodeExecutionError) as error:
  333. SqlGlotRulePlanAdapter(Manager(unknown_commit=True)).execute(
  334. plan=plan,
  335. node=node_for(plan, plan_hash),
  336. parameters={},
  337. write_authorized=True,
  338. )
  339. assert error.value.commit_outcome == "unknown"
  340. def test_sqlglot_rule_adapter_rejects_function_injected_into_attested_plan():
  341. from app.core.data_rules.compilers.sql import bound_sql_plan_hash
  342. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  343. plan, _ = sql_plan()
  344. plan["statements"][0]["sql"] = plan["statements"][0]["sql"].replace(
  345. 'SELECT "id"', 'SELECT pg_sleep(1)'
  346. )
  347. with pytest.raises(ValueError, match="unsupported"):
  348. bound_sql_plan_hash(plan)
  349. # A malicious publisher cannot bypass the AST allowlist by recomputing a
  350. # hash because the adapter independently validates the compiler subset.
  351. node = node_for(plan, "0" * 64)
  352. with pytest.raises(NodeExecutionError, match="invalid"):
  353. SqlGlotRulePlanAdapter(Manager()).execute(
  354. plan=plan,
  355. node=node,
  356. parameters={},
  357. write_authorized=True,
  358. )
  359. @pytest.mark.parametrize(
  360. "unique_rows",
  361. [
  362. [],
  363. [
  364. {
  365. "constraint_name": "customer_id_idx",
  366. "constraint_type": "UNIQUE",
  367. "columns": "id",
  368. },
  369. {
  370. "constraint_name": "mobile_idx",
  371. "constraint_type": "UNIQUE",
  372. "columns": "mobile",
  373. },
  374. ],
  375. ],
  376. )
  377. def test_mysql_upsert_requires_exact_key_and_no_alternate_unique_path(
  378. unique_rows,
  379. ):
  380. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  381. plan, plan_hash = sql_plan("mysql")
  382. with pytest.raises(NodeExecutionError, match="unique"):
  383. SqlGlotRulePlanAdapter(
  384. Manager("mysql", unique_rows=unique_rows)
  385. ).execute(
  386. plan=plan,
  387. node=node_for(plan, plan_hash),
  388. parameters={},
  389. write_authorized=True,
  390. )