test_rule_sql.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. "publication_audit_trusted": True,
  204. "logical_evidence_trusted": True,
  205. "physical_evidence_trusted": True,
  206. "component_kind": "rule.apply",
  207. "binding_idempotency": {
  208. "strategy": "upsert",
  209. "key": "different_id",
  210. },
  211. }
  212. class Adapter:
  213. def execute(self, **_kwargs):
  214. return {"rows_in": 0, "rows_out": 0, "rows_rejected": 0}
  215. with pytest.raises(NodeExecutionError, match="idempotency"):
  216. RulePlanExecutor(
  217. Repository(),
  218. adapters={"sql_pushdown": Adapter()},
  219. ).execute(node, {}, write_authorized=True)
  220. def test_rule_executor_rechecks_canonical_rule_schema_and_compiler_attestations():
  221. from app.core.data_rules.compilers.sql import COMPILER_VERSION
  222. from app.runner.rules import RulePlanExecutor
  223. plan, plan_hash = sql_plan()
  224. node = node_for(plan, plan_hash)
  225. def record(**overrides):
  226. value = {
  227. "component_binding_id": node["config"]["component_binding_id"],
  228. "rule_version_id": plan["rule_version_id"],
  229. "backend": "sql_pushdown",
  230. "compiler_version": COMPILER_VERSION,
  231. "plan": plan,
  232. "plan_hash": plan_hash,
  233. "schema_hashes": {
  234. "rule_spec_hash": plan["rule_spec_hash"],
  235. "input_schema_snapshot_id": plan[
  236. "input_schema_snapshot_id"
  237. ],
  238. "input_schema_hash": plan["input_schema_hash"],
  239. "output_schema_snapshot_id": plan[
  240. "output_schema_snapshot_id"
  241. ],
  242. "output_schema_hash": plan["output_schema_hash"],
  243. },
  244. "canonical_rule_spec_hash": plan["rule_spec_hash"],
  245. "canonical_input_schema_snapshot_id": plan[
  246. "input_schema_snapshot_id"
  247. ],
  248. "canonical_input_schema_hash": plan["input_schema_hash"],
  249. "canonical_output_schema_snapshot_id": plan[
  250. "output_schema_snapshot_id"
  251. ],
  252. "canonical_output_schema_hash": plan["output_schema_hash"],
  253. "plan_status": "published",
  254. "rule_status": "published",
  255. "publication_audit_trusted": True,
  256. "logical_evidence_trusted": True,
  257. "physical_evidence_trusted": True,
  258. "component_kind": "rule.apply",
  259. "binding_idempotency": node["idempotency"],
  260. }
  261. value.update(overrides)
  262. return value
  263. class Repository:
  264. def __init__(self, value):
  265. self.value = value
  266. def load(self, **_kwargs):
  267. return self.value
  268. class Adapter:
  269. def execute(self, **_kwargs):
  270. return {"rows_in": 0, "rows_out": 0, "rows_rejected": 0}
  271. for tampered in (
  272. {"compiler_version": "dataops-sqlglot-99.0.0"},
  273. {"canonical_rule_spec_hash": "f" * 64},
  274. {"canonical_input_schema_hash": "e" * 64},
  275. {"canonical_output_schema_snapshot_id": new_governance_uid()},
  276. ):
  277. with pytest.raises(NodeExecutionError, match="attestation"):
  278. RulePlanExecutor(
  279. Repository(record(**tampered)),
  280. adapters={"sql_pushdown": Adapter()},
  281. ).execute(node, {}, write_authorized=True)
  282. def test_sqlglot_rule_adapter_reports_unknown_commit_outcome():
  283. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  284. plan, plan_hash = sql_plan()
  285. with pytest.raises(NodeExecutionError) as error:
  286. SqlGlotRulePlanAdapter(Manager(unknown_commit=True)).execute(
  287. plan=plan,
  288. node=node_for(plan, plan_hash),
  289. parameters={},
  290. write_authorized=True,
  291. )
  292. assert error.value.commit_outcome == "unknown"
  293. def test_sqlglot_rule_adapter_rejects_function_injected_into_attested_plan():
  294. from app.core.data_rules.compilers.sql import bound_sql_plan_hash
  295. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  296. plan, _ = sql_plan()
  297. plan["statements"][0]["sql"] = plan["statements"][0]["sql"].replace(
  298. 'SELECT "id"', 'SELECT pg_sleep(1)'
  299. )
  300. with pytest.raises(ValueError, match="unsupported"):
  301. bound_sql_plan_hash(plan)
  302. # A malicious publisher cannot bypass the AST allowlist by recomputing a
  303. # hash because the adapter independently validates the compiler subset.
  304. node = node_for(plan, "0" * 64)
  305. with pytest.raises(NodeExecutionError, match="invalid"):
  306. SqlGlotRulePlanAdapter(Manager()).execute(
  307. plan=plan,
  308. node=node,
  309. parameters={},
  310. write_authorized=True,
  311. )
  312. @pytest.mark.parametrize(
  313. "unique_rows",
  314. [
  315. [],
  316. [
  317. {
  318. "constraint_name": "customer_id_idx",
  319. "constraint_type": "UNIQUE",
  320. "columns": "id",
  321. },
  322. {
  323. "constraint_name": "mobile_idx",
  324. "constraint_type": "UNIQUE",
  325. "columns": "mobile",
  326. },
  327. ],
  328. ],
  329. )
  330. def test_mysql_upsert_requires_exact_key_and_no_alternate_unique_path(
  331. unique_rows,
  332. ):
  333. from app.runner.rule_sql import SqlGlotRulePlanAdapter
  334. plan, plan_hash = sql_plan("mysql")
  335. with pytest.raises(NodeExecutionError, match="unique"):
  336. SqlGlotRulePlanAdapter(
  337. Manager("mysql", unique_rows=unique_rows)
  338. ).execute(
  339. plan=plan,
  340. node=node_for(plan, plan_hash),
  341. parameters={},
  342. write_authorized=True,
  343. )