test_rule_sql.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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_rule_adapter_fails_closed_for_dialect_hash_and_authorization():
  148. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  149. plan, plan_hash = sql_plan()
  150. node = node_for(plan, plan_hash)
  151. with pytest.raises(NodeExecutionError, match="dialect"):
  152. SqlGlotRulePlanAdapter(Manager("mysql")).execute(
  153. plan=plan,
  154. node=node,
  155. parameters={},
  156. write_authorized=True,
  157. )
  158. node["config"]["execution_plan_hash"] = "0" * 64
  159. with pytest.raises(NodeExecutionError, match="hash"):
  160. SqlGlotRulePlanAdapter(Manager()).execute(
  161. plan=plan,
  162. node=node,
  163. parameters={},
  164. write_authorized=True,
  165. )
  166. node["config"]["execution_plan_hash"] = plan_hash
  167. with pytest.raises(NodeExecutionError, match="authorization"):
  168. SqlGlotRulePlanAdapter(Manager()).execute(
  169. plan=plan,
  170. node=node,
  171. parameters={},
  172. write_authorized=False,
  173. )
  174. def test_sqlglot_rule_adapter_rejects_unimplemented_idempotency_strategy():
  175. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  176. plan, plan_hash = sql_plan()
  177. node = node_for(plan, plan_hash)
  178. node["idempotency"] = {
  179. "strategy": "partition_replace",
  180. "key": "task4",
  181. }
  182. with pytest.raises(NodeExecutionError, match="idempotency"):
  183. SqlGlotRulePlanAdapter(Manager()).execute(
  184. plan=plan,
  185. node=node,
  186. parameters={},
  187. write_authorized=True,
  188. )
  189. def test_rule_executor_matches_node_idempotency_to_persisted_component():
  190. from app.runner.rules import RulePlanExecutor
  191. plan, plan_hash = sql_plan()
  192. node = node_for(plan, plan_hash)
  193. class Repository:
  194. def load(self, **_kwargs):
  195. return {
  196. "component_binding_id": node["config"]["component_binding_id"],
  197. "rule_version_id": plan["rule_version_id"],
  198. "backend": "sql_pushdown",
  199. "plan": plan,
  200. "plan_hash": plan_hash,
  201. "plan_status": "published",
  202. "rule_status": "published",
  203. "component_kind": "rule.apply",
  204. "binding_idempotency": {
  205. "strategy": "upsert",
  206. "key": "different_id",
  207. },
  208. }
  209. class Adapter:
  210. def execute(self, **_kwargs):
  211. return {"rows_in": 0, "rows_out": 0, "rows_rejected": 0}
  212. with pytest.raises(NodeExecutionError, match="idempotency"):
  213. RulePlanExecutor(
  214. Repository(),
  215. adapters={"sql_pushdown": Adapter()},
  216. ).execute(node, {}, write_authorized=True)
  217. def test_rule_executor_rechecks_canonical_rule_schema_and_compiler_attestations():
  218. from app.core.data_rules.compilers.sql import COMPILER_VERSION
  219. from app.runner.rules import RulePlanExecutor
  220. plan, plan_hash = sql_plan()
  221. node = node_for(plan, plan_hash)
  222. def record(**overrides):
  223. value = {
  224. "component_binding_id": node["config"]["component_binding_id"],
  225. "rule_version_id": plan["rule_version_id"],
  226. "backend": "sql_pushdown",
  227. "compiler_version": COMPILER_VERSION,
  228. "plan": plan,
  229. "plan_hash": plan_hash,
  230. "schema_hashes": {
  231. "rule_spec_hash": plan["rule_spec_hash"],
  232. "input_schema_snapshot_id": plan[
  233. "input_schema_snapshot_id"
  234. ],
  235. "input_schema_hash": plan["input_schema_hash"],
  236. "output_schema_snapshot_id": plan[
  237. "output_schema_snapshot_id"
  238. ],
  239. "output_schema_hash": plan["output_schema_hash"],
  240. },
  241. "canonical_rule_spec_hash": plan["rule_spec_hash"],
  242. "canonical_input_schema_snapshot_id": plan[
  243. "input_schema_snapshot_id"
  244. ],
  245. "canonical_input_schema_hash": plan["input_schema_hash"],
  246. "canonical_output_schema_snapshot_id": plan[
  247. "output_schema_snapshot_id"
  248. ],
  249. "canonical_output_schema_hash": plan["output_schema_hash"],
  250. "plan_status": "published",
  251. "rule_status": "published",
  252. "component_kind": "rule.apply",
  253. "binding_idempotency": node["idempotency"],
  254. }
  255. value.update(overrides)
  256. return value
  257. class Repository:
  258. def __init__(self, value):
  259. self.value = value
  260. def load(self, **_kwargs):
  261. return self.value
  262. class Adapter:
  263. def execute(self, **_kwargs):
  264. return {"rows_in": 0, "rows_out": 0, "rows_rejected": 0}
  265. for tampered in (
  266. {"compiler_version": "dataops-sqlglot-99.0.0"},
  267. {"canonical_rule_spec_hash": "f" * 64},
  268. {"canonical_input_schema_hash": "e" * 64},
  269. {"canonical_output_schema_snapshot_id": new_governance_uid()},
  270. ):
  271. with pytest.raises(NodeExecutionError, match="attestation"):
  272. RulePlanExecutor(
  273. Repository(record(**tampered)),
  274. adapters={"sql_pushdown": Adapter()},
  275. ).execute(node, {}, write_authorized=True)
  276. def test_sqlglot_rule_adapter_reports_unknown_commit_outcome():
  277. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  278. plan, plan_hash = sql_plan()
  279. with pytest.raises(NodeExecutionError) as error:
  280. SqlGlotRulePlanAdapter(Manager(unknown_commit=True)).execute(
  281. plan=plan,
  282. node=node_for(plan, plan_hash),
  283. parameters={},
  284. write_authorized=True,
  285. )
  286. assert error.value.commit_outcome == "unknown"
  287. def test_sqlglot_rule_adapter_rejects_function_injected_into_attested_plan():
  288. from app.core.data_rules.compilers.sql import bound_sql_plan_hash
  289. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  290. plan, _ = sql_plan()
  291. plan["statements"][0]["sql"] = plan["statements"][0]["sql"].replace(
  292. 'SELECT "id"', 'SELECT pg_sleep(1)'
  293. )
  294. with pytest.raises(ValueError, match="unsupported"):
  295. bound_sql_plan_hash(plan)
  296. # A malicious publisher cannot bypass the AST allowlist by recomputing a
  297. # hash because the adapter independently validates the compiler subset.
  298. node = node_for(plan, "0" * 64)
  299. with pytest.raises(NodeExecutionError, match="invalid"):
  300. SqlGlotRulePlanAdapter(Manager()).execute(
  301. plan=plan,
  302. node=node,
  303. parameters={},
  304. write_authorized=True,
  305. )
  306. @pytest.mark.parametrize(
  307. "unique_rows",
  308. [
  309. [],
  310. [
  311. {
  312. "constraint_name": "customer_id_idx",
  313. "constraint_type": "UNIQUE",
  314. "columns": "id",
  315. },
  316. {
  317. "constraint_name": "mobile_idx",
  318. "constraint_type": "UNIQUE",
  319. "columns": "mobile",
  320. },
  321. ],
  322. ],
  323. )
  324. def test_mysql_upsert_requires_exact_key_and_no_alternate_unique_path(
  325. unique_rows,
  326. ):
  327. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  328. plan, plan_hash = sql_plan("mysql")
  329. with pytest.raises(NodeExecutionError, match="unique"):
  330. SqlGlotRulePlanAdapter(
  331. Manager("mysql", unique_rows=unique_rows)
  332. ).execute(
  333. plan=plan,
  334. node=node_for(plan, plan_hash),
  335. parameters={},
  336. write_authorized=True,
  337. )