artifacts.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  1. """Digest-bound, bounded Parquet artifacts owned by the DataOps Runner."""
  2. from __future__ import annotations
  3. import hashlib
  4. import json
  5. import os
  6. import re
  7. import tempfile
  8. from collections.abc import Mapping
  9. from contextlib import contextmanager, suppress
  10. from datetime import UTC, datetime, timedelta
  11. from typing import Any
  12. import polars as pl
  13. import pyarrow.parquet as pq
  14. from minio.error import S3Error
  15. from sqlalchemy import text
  16. from app.core.common.identifiers import (
  17. ensure_governance_uid,
  18. new_governance_uid,
  19. )
  20. from app.core.data_rules.execution_contracts import canonical_schema_hash
  21. PARQUET_CONTENT_TYPE = "application/x-parquet"
  22. _DIGEST = re.compile(r"^[0-9a-f]{64}$")
  23. class ArtifactCommitUnknown(RuntimeError):
  24. """A catalog transaction may have committed but cannot be confirmed."""
  25. class ArtifactHandoffPending(RuntimeError):
  26. """Another publisher owns the durable pending handoff."""
  27. def _parquet_footer_bounds(path: str) -> tuple[int, int]:
  28. try:
  29. metadata = pq.ParquetFile(path).metadata
  30. except Exception as exc:
  31. raise ValueError("artifact Parquet footer is invalid") from exc
  32. if metadata is None or metadata.num_row_groups < 1:
  33. raise ValueError("artifact Parquet footer is incomplete")
  34. uncompressed = sum(
  35. metadata.row_group(index).total_byte_size
  36. for index in range(metadata.num_row_groups)
  37. )
  38. if metadata.num_rows < 0 or uncompressed < 0:
  39. raise ValueError("artifact Parquet footer is invalid")
  40. return metadata.num_rows, uncompressed
  41. def _now_utc(clock) -> datetime:
  42. value = clock()
  43. if not isinstance(value, datetime):
  44. raise ValueError("artifact clock must return a datetime")
  45. if value.tzinfo is None:
  46. value = value.replace(tzinfo=UTC)
  47. return value.astimezone(UTC)
  48. def _timestamp(value: datetime) -> str:
  49. return value.astimezone(UTC).isoformat().replace("+00:00", "Z")
  50. def _parse_timestamp(value: Any) -> datetime:
  51. if not isinstance(value, str) or not value.endswith("Z"):
  52. raise ValueError("artifact expiry metadata is invalid")
  53. try:
  54. parsed = datetime.fromisoformat(value[:-1] + "+00:00")
  55. except ValueError as exc:
  56. raise ValueError("artifact expiry metadata is invalid") from exc
  57. return parsed.astimezone(UTC)
  58. def _uid(value: Any, label: str) -> str:
  59. try:
  60. return ensure_governance_uid({"uid": str(value)})
  61. except ValueError as exc:
  62. raise ValueError(f"{label} must be a valid UUIDv7") from exc
  63. def _inferred_schema_fields(
  64. frame: pl.DataFrame | pl.LazyFrame,
  65. ) -> list[dict[str, Any]]:
  66. schema = (
  67. frame.collect_schema()
  68. if isinstance(frame, pl.LazyFrame)
  69. else frame.schema
  70. )
  71. fields = []
  72. for name, dtype in schema.items():
  73. field: dict[str, Any] = {
  74. "name": name,
  75. "nullable": True,
  76. }
  77. if dtype == pl.Boolean:
  78. field["type"] = "boolean"
  79. elif dtype == pl.Date:
  80. field["type"] = "date"
  81. elif dtype == pl.String:
  82. field["type"] = "string"
  83. elif dtype.is_integer():
  84. field["type"] = "integer"
  85. elif dtype == pl.Float32:
  86. field["type"] = "float"
  87. elif dtype == pl.Float64:
  88. field["type"] = "double"
  89. elif dtype.is_decimal():
  90. field.update(
  91. {
  92. "type": "decimal",
  93. "precision": dtype.precision,
  94. "scale": dtype.scale,
  95. }
  96. )
  97. elif isinstance(dtype, pl.Datetime):
  98. field["type"] = (
  99. "timestamptz" if dtype.time_zone else "timestamp"
  100. )
  101. if dtype.time_zone:
  102. field["timezone"] = dtype.time_zone
  103. else:
  104. raise ValueError(f"unsupported artifact dtype for {name}")
  105. fields.append(field)
  106. return sorted(fields, key=lambda item: item["name"])
  107. def _normalized_schema_fields(value: Any) -> list[dict[str, Any]]:
  108. canonical_schema_hash(value)
  109. return sorted(
  110. [dict(field) for field in value],
  111. key=lambda item: item["name"],
  112. )
  113. def _schema_contract(value: Any) -> tuple[list[dict[str, Any]], str]:
  114. fields = _normalized_schema_fields(value)
  115. return fields, canonical_schema_hash(fields)
  116. def _validate_frame_schema(
  117. frame: pl.DataFrame | pl.LazyFrame,
  118. fields: list[dict[str, Any]],
  119. ) -> None:
  120. schema = (
  121. frame.collect_schema()
  122. if isinstance(frame, pl.LazyFrame)
  123. else frame.schema
  124. )
  125. expected_names = {field["name"] for field in fields}
  126. if set(schema.names()) != expected_names:
  127. raise ValueError("artifact schema fields do not match")
  128. for field in fields:
  129. dtype = schema[field["name"]]
  130. field_type = field["type"]
  131. matches = (
  132. (field_type == "boolean" and dtype == pl.Boolean)
  133. or (field_type == "date" and dtype == pl.Date)
  134. or (field_type == "string" and dtype == pl.String)
  135. or (field_type == "integer" and dtype.is_integer())
  136. or (field_type == "float" and dtype == pl.Float32)
  137. or (field_type == "double" and dtype == pl.Float64)
  138. or (
  139. field_type == "decimal"
  140. and dtype.is_decimal()
  141. and dtype.precision == field.get("precision")
  142. and dtype.scale == field.get("scale")
  143. )
  144. or (
  145. field_type == "timestamp"
  146. and isinstance(dtype, pl.Datetime)
  147. and dtype.time_zone is None
  148. )
  149. or (
  150. field_type == "timestamptz"
  151. and isinstance(dtype, pl.Datetime)
  152. and dtype.time_zone == field.get("timezone")
  153. )
  154. )
  155. if not matches:
  156. raise ValueError(
  157. f"artifact schema type for {field['name']} does not match"
  158. )
  159. if isinstance(frame, pl.DataFrame):
  160. for field in fields:
  161. if not field["nullable"] and frame[field["name"]].null_count():
  162. raise ValueError(
  163. f"artifact nullable contract for {field['name']} does not match"
  164. )
  165. def _metadata(value: Any) -> dict[str, str]:
  166. if not isinstance(value, Mapping):
  167. raise ValueError("artifact content metadata is missing")
  168. normalized = {}
  169. for key, item in value.items():
  170. name = str(key).lower()
  171. if name.startswith("x-amz-meta-"):
  172. name = name[len("x-amz-meta-") :]
  173. if name in {
  174. "sha256",
  175. "row-count",
  176. "schema-sha256",
  177. "expires-at",
  178. "artifact-bytes",
  179. }:
  180. normalized[name] = str(item)
  181. required = {
  182. "sha256",
  183. "row-count",
  184. "schema-sha256",
  185. "expires-at",
  186. "artifact-bytes",
  187. }
  188. if set(normalized) != required:
  189. raise ValueError("artifact content metadata is incomplete")
  190. if sum(len(key) + len(item) for key, item in normalized.items()) > 2_048:
  191. raise ValueError("artifact content metadata exceeds the safe limit")
  192. return normalized
  193. class ArtifactStore:
  194. """Read and write only server-owned, bounded Parquet artifacts."""
  195. def __init__(
  196. self,
  197. client,
  198. *,
  199. bucket: str,
  200. max_artifact_bytes: int,
  201. max_rows: int,
  202. memory_limit_bytes: int,
  203. max_ttl_seconds: int = 86400,
  204. clock=None,
  205. ):
  206. if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
  207. raise ValueError("artifact bucket name is invalid")
  208. self.client = client
  209. self.bucket = bucket
  210. self.max_artifact_bytes = int(max_artifact_bytes)
  211. self.max_rows = int(max_rows)
  212. self.memory_limit_bytes = int(memory_limit_bytes)
  213. self.max_ttl_seconds = int(max_ttl_seconds)
  214. self.clock = clock or (lambda: datetime.now(UTC))
  215. if (
  216. self.max_artifact_bytes < 1024
  217. or self.max_rows < 1
  218. or self.memory_limit_bytes < self.max_artifact_bytes
  219. or self.max_ttl_seconds < 1
  220. ):
  221. raise ValueError("artifact resource limits are invalid")
  222. if not self.client.bucket_exists(self.bucket):
  223. raise ValueError("artifact bucket does not exist")
  224. def _limits(self, value: Any = None) -> dict[str, int]:
  225. configured = {
  226. "max_rows": self.max_rows,
  227. "max_artifact_bytes": self.max_artifact_bytes,
  228. "memory_limit_bytes": self.memory_limit_bytes,
  229. }
  230. if value is None:
  231. return configured
  232. if not isinstance(value, dict) or set(value) != set(configured):
  233. raise ValueError("artifact limits must have a closed shape")
  234. result = {}
  235. for key, ceiling in configured.items():
  236. item = value[key]
  237. if (
  238. isinstance(item, bool)
  239. or not isinstance(item, int)
  240. or item < 1
  241. or item > ceiling
  242. ):
  243. raise ValueError(
  244. f"artifact {key} exceeds the configured ceiling"
  245. )
  246. result[key] = item
  247. return result
  248. def _parse_ref(self, ref: Any) -> str:
  249. prefix = f"minio://{self.bucket}/"
  250. if not isinstance(ref, str) or not ref.startswith(prefix):
  251. raise ValueError("artifact reference is not owned by this store")
  252. key = ref[len(prefix) :]
  253. match = re.fullmatch(
  254. r"rules/([0-9a-f-]{36})/([0-9a-f-]{36})\.parquet",
  255. key,
  256. )
  257. if match is None:
  258. raise ValueError("artifact reference is invalid")
  259. _uid(match.group(1), "artifact correlation id")
  260. _uid(match.group(2), "artifact id")
  261. return key
  262. def _validated_stat(
  263. self,
  264. key: str,
  265. *,
  266. expected_digest: str | None = None,
  267. limits: dict[str, int] | None = None,
  268. ) -> tuple[Any, dict[str, str]]:
  269. effective = self._limits(limits)
  270. stat = self.client.stat_object(self.bucket, key)
  271. size = int(getattr(stat, "size", -1))
  272. if size < 1 or size > effective["max_artifact_bytes"]:
  273. raise ValueError("artifact size exceeds the configured limit")
  274. if size > effective["memory_limit_bytes"]:
  275. raise ValueError("artifact download exceeds the memory limit")
  276. if str(getattr(stat, "content_type", "")).lower() != PARQUET_CONTENT_TYPE:
  277. raise ValueError("artifact content type is invalid")
  278. metadata = _metadata(getattr(stat, "metadata", None))
  279. digest = metadata["sha256"]
  280. if _DIGEST.fullmatch(digest) is None:
  281. raise ValueError("artifact digest metadata is invalid")
  282. if expected_digest is not None and digest != expected_digest:
  283. raise ValueError("artifact digest does not match")
  284. try:
  285. row_count = int(metadata["row-count"])
  286. metadata_size = int(metadata["artifact-bytes"])
  287. except (TypeError, ValueError) as exc:
  288. raise ValueError("artifact count metadata is invalid") from exc
  289. if row_count < 0 or row_count > effective["max_rows"]:
  290. raise ValueError("artifact row count exceeds the configured limit")
  291. if metadata_size != size:
  292. raise ValueError("artifact size metadata does not match")
  293. if _DIGEST.fullmatch(metadata["schema-sha256"]) is None:
  294. raise ValueError("artifact schema metadata is invalid")
  295. if _parse_timestamp(metadata["expires-at"]) <= _now_utc(self.clock):
  296. raise ValueError("artifact has expired")
  297. return stat, metadata
  298. def write(
  299. self,
  300. frame: pl.LazyFrame | pl.DataFrame,
  301. correlation_id: str,
  302. ttl_seconds: int,
  303. *,
  304. schema_fields: list[dict[str, Any]] | None = None,
  305. limits: dict[str, int] | None = None,
  306. ) -> dict[str, Any]:
  307. effective = self._limits(limits)
  308. correlation = _uid(correlation_id, "correlation_id")
  309. if (
  310. isinstance(ttl_seconds, bool)
  311. or not isinstance(ttl_seconds, int)
  312. or ttl_seconds < 1
  313. or ttl_seconds > self.max_ttl_seconds
  314. ):
  315. raise ValueError("artifact TTL is outside the configured limit")
  316. if isinstance(frame, pl.DataFrame):
  317. lazy = frame.lazy()
  318. elif isinstance(frame, pl.LazyFrame):
  319. lazy = frame
  320. else:
  321. raise ValueError("artifact frame must be a Polars frame")
  322. collected = lazy.head(effective["max_rows"] + 1).collect(
  323. engine="streaming"
  324. )
  325. if collected.height > effective["max_rows"]:
  326. raise ValueError("artifact row count exceeds the configured limit")
  327. if collected.estimated_size() > effective["memory_limit_bytes"]:
  328. raise ValueError("artifact frame exceeds the configured memory limit")
  329. fields, schema_digest = _schema_contract(
  330. schema_fields or _inferred_schema_fields(collected)
  331. )
  332. _validate_frame_schema(collected, fields)
  333. expires_at = _timestamp(
  334. _now_utc(self.clock) + timedelta(seconds=ttl_seconds)
  335. )
  336. artifact_id = new_governance_uid()
  337. key = f"rules/{correlation}/{artifact_id}.parquet"
  338. path = None
  339. uploaded = False
  340. try:
  341. with tempfile.NamedTemporaryFile(
  342. prefix="dataops-rule-artifact-",
  343. suffix=".parquet",
  344. delete=False,
  345. ) as handle:
  346. path = handle.name
  347. collected.write_parquet(path)
  348. size = os.path.getsize(path)
  349. if size < 1 or size > effective["max_artifact_bytes"]:
  350. raise ValueError("artifact size exceeds the configured limit")
  351. if size > effective["memory_limit_bytes"]:
  352. raise ValueError("serialized artifact exceeds the memory limit")
  353. if (
  354. size + collected.estimated_size()
  355. > effective["memory_limit_bytes"]
  356. ):
  357. raise ValueError(
  358. "artifact serialization exceeds the memory limit"
  359. )
  360. digest = hashlib.sha256()
  361. with open(path, "rb") as handle:
  362. while chunk := handle.read(1024 * 1024):
  363. digest.update(chunk)
  364. digest_hex = digest.hexdigest()
  365. with open(path, "rb") as handle:
  366. self.client.put_object(
  367. self.bucket,
  368. key,
  369. handle,
  370. size,
  371. content_type=PARQUET_CONTENT_TYPE,
  372. metadata={
  373. "sha256": digest_hex,
  374. "row-count": str(collected.height),
  375. "schema-sha256": schema_digest,
  376. "expires-at": expires_at,
  377. "artifact-bytes": str(size),
  378. },
  379. )
  380. uploaded = True
  381. self._validated_stat(
  382. key,
  383. expected_digest=digest_hex,
  384. limits=effective,
  385. )
  386. artifact_ref = f"minio://{self.bucket}/{key}"
  387. with self.stage(
  388. artifact_ref,
  389. digest_hex,
  390. expected_schema_fields=fields,
  391. limits=effective,
  392. ):
  393. pass
  394. except Exception:
  395. if uploaded:
  396. with suppress(Exception):
  397. self.client.remove_object(self.bucket, key)
  398. raise
  399. finally:
  400. if path is not None:
  401. with suppress(FileNotFoundError):
  402. os.unlink(path)
  403. return {
  404. "artifact_ref": artifact_ref,
  405. "digest": digest_hex,
  406. "row_count": collected.height,
  407. "schema_hash": schema_digest,
  408. "schema_fields": fields,
  409. "expires_at": expires_at,
  410. }
  411. def prepare_path(
  412. self,
  413. path: str,
  414. correlation_id: str,
  415. ttl_seconds: int,
  416. *,
  417. schema_fields: list[dict[str, Any]],
  418. limits: dict[str, int] | None = None,
  419. ) -> dict[str, Any]:
  420. """Validate a local Parquet file and reserve its server-owned key."""
  421. effective = self._limits(limits)
  422. correlation = _uid(correlation_id, "correlation_id")
  423. if (
  424. isinstance(ttl_seconds, bool)
  425. or not isinstance(ttl_seconds, int)
  426. or ttl_seconds < 1
  427. or ttl_seconds > self.max_ttl_seconds
  428. ):
  429. raise ValueError("artifact TTL is outside the configured limit")
  430. if not isinstance(path, str) or not os.path.isfile(path):
  431. raise ValueError("worker artifact path is invalid")
  432. size = os.path.getsize(path)
  433. if size < 1 or size > effective["max_artifact_bytes"]:
  434. raise ValueError("artifact size exceeds the configured limit")
  435. rows, uncompressed = _parquet_footer_bounds(path)
  436. if rows > effective["max_rows"]:
  437. raise ValueError("artifact row count exceeds the configured limit")
  438. if uncompressed > effective["memory_limit_bytes"]:
  439. raise ValueError(
  440. "Parquet footer uncompressed size exceeds the memory limit"
  441. )
  442. fields, schema_digest = _schema_contract(schema_fields)
  443. _validate_frame_schema(pl.scan_parquet(path), fields)
  444. digest = hashlib.sha256()
  445. with open(path, "rb") as handle:
  446. while chunk := handle.read(1024 * 1024):
  447. digest.update(chunk)
  448. digest_hex = digest.hexdigest()
  449. expires_at = _timestamp(
  450. _now_utc(self.clock) + timedelta(seconds=ttl_seconds)
  451. )
  452. artifact_id = new_governance_uid()
  453. key = f"rules/{correlation}/{artifact_id}.parquet"
  454. return {
  455. "artifact_ref": f"minio://{self.bucket}/{key}",
  456. "digest": digest_hex,
  457. "row_count": rows,
  458. "schema_hash": schema_digest,
  459. "schema_fields": fields,
  460. "expires_at": expires_at,
  461. }
  462. def upload_path(
  463. self,
  464. path: str,
  465. artifact: dict[str, Any],
  466. *,
  467. limits: dict[str, int] | None = None,
  468. ) -> dict[str, Any]:
  469. """Upload to an already reserved exact key and verify the object."""
  470. if not isinstance(artifact, dict):
  471. raise ValueError("prepared artifact metadata is invalid")
  472. required = {
  473. "artifact_ref",
  474. "digest",
  475. "row_count",
  476. "schema_hash",
  477. "schema_fields",
  478. "expires_at",
  479. }
  480. if set(artifact) != required:
  481. raise ValueError("prepared artifact metadata has a closed shape")
  482. key = self._parse_ref(artifact["artifact_ref"])
  483. correlation = key.split("/", 2)[1]
  484. ttl_seconds = int(
  485. (
  486. _parse_timestamp(artifact["expires_at"])
  487. - _now_utc(self.clock)
  488. ).total_seconds()
  489. )
  490. if ttl_seconds < 1 or ttl_seconds > self.max_ttl_seconds:
  491. raise ValueError("prepared artifact TTL is invalid")
  492. expected = self.prepare_path(
  493. path,
  494. correlation,
  495. ttl_seconds,
  496. schema_fields=artifact["schema_fields"],
  497. limits=limits,
  498. )
  499. for name in (
  500. "digest",
  501. "row_count",
  502. "schema_hash",
  503. "schema_fields",
  504. ):
  505. if expected[name] != artifact[name]:
  506. raise ValueError("prepared artifact no longer matches its path")
  507. effective = self._limits(limits)
  508. size = os.path.getsize(path)
  509. uploaded = False
  510. try:
  511. with open(path, "rb") as handle:
  512. self.client.put_object(
  513. self.bucket,
  514. key,
  515. handle,
  516. size,
  517. content_type=PARQUET_CONTENT_TYPE,
  518. metadata={
  519. "sha256": artifact["digest"],
  520. "row-count": str(artifact["row_count"]),
  521. "schema-sha256": artifact["schema_hash"],
  522. "expires-at": artifact["expires_at"],
  523. "artifact-bytes": str(size),
  524. },
  525. )
  526. uploaded = True
  527. with self.stage(
  528. artifact["artifact_ref"],
  529. artifact["digest"],
  530. expected_schema_fields=artifact["schema_fields"],
  531. limits=effective,
  532. ):
  533. pass
  534. except Exception:
  535. if uploaded:
  536. with suppress(Exception):
  537. self.client.remove_object(self.bucket, key)
  538. raise
  539. return dict(artifact)
  540. def write_path(
  541. self,
  542. path: str,
  543. correlation_id: str,
  544. ttl_seconds: int,
  545. *,
  546. schema_fields: list[dict[str, Any]],
  547. limits: dict[str, int] | None = None,
  548. ) -> dict[str, Any]:
  549. """Prepare and upload a non-cataloged compatibility artifact."""
  550. artifact = self.prepare_path(
  551. path,
  552. correlation_id,
  553. ttl_seconds,
  554. schema_fields=schema_fields,
  555. limits=limits,
  556. )
  557. return self.upload_path(path, artifact, limits=limits)
  558. def describe(self, ref: str) -> dict[str, Any]:
  559. """Return validated object metadata without exposing MinIO credentials."""
  560. key = self._parse_ref(ref)
  561. _stat, metadata = self._validated_stat(key)
  562. return {
  563. "artifact_ref": ref,
  564. "digest": metadata["sha256"],
  565. "row_count": int(metadata["row-count"]),
  566. "schema_hash": metadata["schema-sha256"],
  567. "expires_at": metadata["expires-at"],
  568. }
  569. def describe_optional(self, ref: str) -> dict[str, Any] | None:
  570. """Return None only for a confirmed missing object."""
  571. try:
  572. return self.describe(ref)
  573. except KeyError:
  574. return None
  575. except S3Error as exc:
  576. if exc.code in {"NoSuchKey", "NoSuchObject", "NotFound"}:
  577. return None
  578. raise
  579. def read(
  580. self,
  581. ref: str,
  582. expected_digest: str,
  583. *,
  584. expected_schema_fields: list[dict[str, Any]] | None = None,
  585. limits: dict[str, int] | None = None,
  586. ) -> pl.LazyFrame:
  587. with self.stage(
  588. ref,
  589. expected_digest,
  590. expected_schema_fields=expected_schema_fields,
  591. limits=limits,
  592. ) as path:
  593. effective = self._limits(limits)
  594. try:
  595. frame = pl.read_parquet(
  596. path,
  597. n_rows=effective["max_rows"] + 1,
  598. memory_map=False,
  599. )
  600. except Exception as exc:
  601. raise ValueError("artifact is not valid Parquet") from exc
  602. if frame.estimated_size() > effective["memory_limit_bytes"]:
  603. raise ValueError("artifact frame exceeds the configured memory limit")
  604. _validate_frame_schema(
  605. frame, _normalized_schema_fields(expected_schema_fields)
  606. )
  607. return frame.lazy()
  608. @contextmanager
  609. def stage(
  610. self,
  611. ref: str,
  612. expected_digest: str,
  613. *,
  614. expected_schema_fields: list[dict[str, Any]] | None = None,
  615. limits: dict[str, int] | None = None,
  616. ):
  617. effective = self._limits(limits)
  618. if _DIGEST.fullmatch(str(expected_digest or "")) is None:
  619. raise ValueError("expected artifact digest is invalid")
  620. key = self._parse_ref(ref)
  621. _stat, metadata = self._validated_stat(
  622. key,
  623. expected_digest=expected_digest,
  624. limits=effective,
  625. )
  626. if expected_schema_fields is None:
  627. raise ValueError("expected artifact schema fields are required")
  628. fields = _normalized_schema_fields(expected_schema_fields)
  629. if canonical_schema_hash(fields) != metadata["schema-sha256"]:
  630. raise ValueError("artifact schema contract is not expected")
  631. response = self.client.get_object(self.bucket, key)
  632. digest = hashlib.sha256()
  633. path = None
  634. size = 0
  635. try:
  636. try:
  637. with tempfile.NamedTemporaryFile(
  638. prefix="dataops-rule-stage-",
  639. suffix=".parquet",
  640. delete=False,
  641. ) as handle:
  642. path = handle.name
  643. while chunk := response.read(1024 * 1024):
  644. size += len(chunk)
  645. if size > effective["max_artifact_bytes"]:
  646. raise ValueError(
  647. "artifact size exceeds the configured limit"
  648. )
  649. digest.update(chunk)
  650. handle.write(chunk)
  651. finally:
  652. response.close()
  653. release = getattr(response, "release_conn", None)
  654. if callable(release):
  655. release()
  656. if digest.hexdigest() != expected_digest:
  657. raise ValueError("artifact digest does not match content")
  658. footer_rows, uncompressed = _parquet_footer_bounds(path)
  659. if footer_rows != int(metadata["row-count"]):
  660. raise ValueError("artifact row count does not match metadata")
  661. if footer_rows > effective["max_rows"]:
  662. raise ValueError(
  663. "artifact row count exceeds the configured limit"
  664. )
  665. if uncompressed > effective["memory_limit_bytes"]:
  666. raise ValueError(
  667. "Parquet footer uncompressed size exceeds the memory limit"
  668. )
  669. lazy = pl.scan_parquet(path)
  670. _validate_frame_schema(lazy, fields)
  671. yield path
  672. finally:
  673. if path is not None:
  674. with suppress(FileNotFoundError):
  675. os.unlink(path)
  676. def cleanup_expired(self, correlation_id: str) -> int:
  677. correlation = _uid(correlation_id, "correlation_id")
  678. prefix = f"rules/{correlation}/"
  679. removed = 0
  680. for item in self.client.list_objects(
  681. self.bucket,
  682. prefix=prefix,
  683. recursive=True,
  684. ):
  685. key = str(getattr(item, "object_name", ""))
  686. if not key.startswith(prefix):
  687. continue
  688. try:
  689. self._parse_ref(f"minio://{self.bucket}/{key}")
  690. stat = self.client.stat_object(self.bucket, key)
  691. metadata = _metadata(getattr(stat, "metadata", None))
  692. expired = _parse_timestamp(
  693. metadata["expires-at"]
  694. ) <= _now_utc(self.clock)
  695. except ValueError:
  696. continue
  697. if expired:
  698. self.client.remove_object(self.bucket, key)
  699. removed += 1
  700. return removed
  701. def delete(self, ref: str) -> None:
  702. """Delete one exact store-owned artifact after validating its key."""
  703. key = self._parse_ref(ref)
  704. self.client.remove_object(self.bucket, key)
  705. class PostgresArtifactResolver:
  706. """Resolve a canonical artifact binding without accepting caller paths."""
  707. def __init__(self, engine, artifact_store: ArtifactStore):
  708. self.engine = engine
  709. self.artifact_store = artifact_store
  710. def resolve(
  711. self,
  712. *,
  713. binding_id: str,
  714. correlation_id: str,
  715. kind: str,
  716. ) -> dict[str, Any]:
  717. binding = _uid(binding_id, "artifact binding id")
  718. correlation = _uid(correlation_id, "artifact correlation id")
  719. if kind not in {"input", "lookup", "output"}:
  720. raise ValueError("artifact kind is invalid")
  721. statement = text(
  722. """
  723. SELECT
  724. a.artifact_ref,
  725. a.artifact_digest,
  726. a.row_count,
  727. a.schema_hash,
  728. a.schema_fields,
  729. a.expires_at,
  730. a.binding_hash AS catalog_binding_hash,
  731. b.binding_hash AS current_binding_hash
  732. FROM public.rule_run_artifacts a
  733. JOIN public.dataflow_dataset_bindings b
  734. ON b.id = a.binding_id
  735. WHERE a.binding_id = CAST(:binding_id AS uuid)
  736. AND a.correlation_id = CAST(:correlation_id AS uuid)
  737. AND a.artifact_kind = :artifact_kind
  738. AND a.handoff_status = 'ready'
  739. AND a.expires_at > CURRENT_TIMESTAMP
  740. AND a.binding_hash = b.binding_hash
  741. AND b.object_kind = 'parquet_artifact'
  742. AND b.access_mode IN ('read', 'read_write')
  743. ORDER BY a.created_at DESC
  744. LIMIT 1
  745. """
  746. )
  747. with self.engine.connect() as connection:
  748. row = connection.execute(
  749. statement,
  750. {
  751. "binding_id": binding,
  752. "correlation_id": correlation,
  753. "artifact_kind": kind,
  754. },
  755. ).mappings().one_or_none()
  756. if row is None:
  757. raise ValueError("canonical artifact binding was not found")
  758. artifact_ref = str(row["artifact_ref"])
  759. key = self.artifact_store._parse_ref(artifact_ref)
  760. if not key.startswith(f"rules/{correlation}/"):
  761. raise ValueError(
  762. "catalog artifact does not match the execution correlation"
  763. )
  764. described = self.artifact_store.describe(artifact_ref)
  765. row_fields = row["schema_fields"]
  766. if isinstance(row_fields, str):
  767. row_fields = json.loads(row_fields)
  768. if (
  769. described["digest"] != str(row["artifact_digest"])
  770. or described["row_count"] != int(row["row_count"])
  771. or described["schema_hash"] != str(row["schema_hash"])
  772. ):
  773. raise ValueError("catalog artifact metadata does not match storage")
  774. return {
  775. **described,
  776. "schema_fields": _normalized_schema_fields(row_fields),
  777. "binding_hash": str(row["catalog_binding_hash"]),
  778. }
  779. def attest_binding(
  780. self,
  781. *,
  782. binding_id: str,
  783. binding_hash: str,
  784. access_mode: str,
  785. ) -> dict[str, str]:
  786. binding = _uid(binding_id, "artifact binding id")
  787. if _DIGEST.fullmatch(str(binding_hash or "")) is None:
  788. raise ValueError("artifact binding hash is invalid")
  789. allowed = {
  790. "read": {"read", "read_write"},
  791. "write": {"write", "read_write"},
  792. }.get(access_mode)
  793. if allowed is None:
  794. raise ValueError("artifact access mode is invalid")
  795. with self.engine.connect() as connection:
  796. row = connection.execute(
  797. text(
  798. """
  799. SELECT binding_hash, access_mode, object_kind
  800. FROM public.dataflow_dataset_bindings
  801. WHERE id = CAST(:binding_id AS uuid)
  802. """
  803. ),
  804. {"binding_id": binding},
  805. ).mappings().one_or_none()
  806. if (
  807. row is None
  808. or row["object_kind"] != "parquet_artifact"
  809. or row["access_mode"] not in allowed
  810. or str(row["binding_hash"]) != binding_hash
  811. ):
  812. raise ValueError("canonical artifact binding no longer matches")
  813. return {"binding_hash": str(row["binding_hash"])}
  814. @staticmethod
  815. def _catalog_artifact(row: Mapping[str, Any]) -> dict[str, Any]:
  816. fields = row["schema_fields"]
  817. if isinstance(fields, str):
  818. fields = json.loads(fields)
  819. expires_at = row["expires_at"]
  820. return {
  821. "artifact_ref": str(row["artifact_ref"]),
  822. "digest": str(row["artifact_digest"]),
  823. "row_count": int(row["row_count"]),
  824. "schema_hash": str(row["schema_hash"]),
  825. "schema_fields": _normalized_schema_fields(fields),
  826. "expires_at": (
  827. _timestamp(expires_at)
  828. if isinstance(expires_at, datetime)
  829. else str(expires_at)
  830. ),
  831. }
  832. @staticmethod
  833. def _attest_binding_locked(
  834. connection,
  835. *,
  836. binding_id: str,
  837. binding_hash: str,
  838. kind: str,
  839. ) -> None:
  840. row = connection.execute(
  841. text(
  842. """
  843. SELECT binding_hash, access_mode, object_kind
  844. FROM public.dataflow_dataset_bindings
  845. WHERE id = CAST(:binding_id AS uuid)
  846. FOR SHARE
  847. """
  848. ),
  849. {"binding_id": binding_id},
  850. ).mappings().one_or_none()
  851. allowed = (
  852. {"write", "read_write"}
  853. if kind == "output"
  854. else {"read", "read_write"}
  855. )
  856. if (
  857. row is None
  858. or row["object_kind"] != "parquet_artifact"
  859. or row["access_mode"] not in allowed
  860. or str(row["binding_hash"]) != binding_hash
  861. ):
  862. raise ValueError("canonical artifact binding no longer matches")
  863. def _lookup_handoff(
  864. self,
  865. *,
  866. correlation_id: str,
  867. binding_id: str,
  868. kind: str,
  869. ) -> dict[str, Any] | None:
  870. with self.engine.connect() as connection:
  871. row = connection.execute(
  872. text(
  873. """
  874. SELECT id::text AS id, correlation_id::text,
  875. binding_id::text, artifact_ref, artifact_digest,
  876. row_count, schema_hash, schema_fields,
  877. artifact_kind, binding_hash, expires_at,
  878. handoff_status
  879. FROM public.rule_run_artifacts
  880. WHERE correlation_id = CAST(:correlation_id AS uuid)
  881. AND binding_id = CAST(:binding_id AS uuid)
  882. AND artifact_kind = :artifact_kind
  883. """
  884. ),
  885. {
  886. "correlation_id": correlation_id,
  887. "binding_id": binding_id,
  888. "artifact_kind": kind,
  889. },
  890. ).mappings().one_or_none()
  891. return dict(row) if row is not None else None
  892. def reserve(
  893. self,
  894. *,
  895. binding_id: str,
  896. correlation_id: str,
  897. artifact: dict[str, Any],
  898. kind: str,
  899. binding_hash: str,
  900. ) -> dict[str, Any]:
  901. """Atomically attest the binding and reserve one pending handoff."""
  902. binding = _uid(binding_id, "artifact binding id")
  903. correlation = _uid(correlation_id, "artifact correlation id")
  904. if kind not in {"input", "lookup", "output"}:
  905. raise ValueError("artifact kind is invalid")
  906. if _DIGEST.fullmatch(str(binding_hash or "")) is None:
  907. raise ValueError("artifact binding hash is invalid")
  908. if not isinstance(artifact, dict):
  909. raise ValueError("artifact metadata is invalid")
  910. artifact_ref = artifact.get("artifact_ref")
  911. key = self.artifact_store._parse_ref(artifact_ref)
  912. if not key.startswith(f"rules/{correlation}/"):
  913. raise ValueError(
  914. "artifact does not match the execution correlation"
  915. )
  916. fields = _normalized_schema_fields(artifact.get("schema_fields"))
  917. if canonical_schema_hash(fields) != artifact.get("schema_hash"):
  918. raise ValueError("artifact schema contract does not match")
  919. if _DIGEST.fullmatch(str(artifact.get("digest") or "")) is None:
  920. raise ValueError("artifact digest is invalid")
  921. reservation_id = new_governance_uid()
  922. parameters = {
  923. "id": reservation_id,
  924. "correlation_id": correlation,
  925. "binding_id": binding,
  926. "artifact_ref": artifact_ref,
  927. "artifact_digest": artifact["digest"],
  928. "row_count": int(artifact["row_count"]),
  929. "schema_hash": artifact["schema_hash"],
  930. "schema_fields": json.dumps(
  931. fields,
  932. sort_keys=True,
  933. separators=(",", ":"),
  934. ),
  935. "artifact_kind": kind,
  936. "binding_hash": binding_hash,
  937. "expires_at": artifact["expires_at"],
  938. }
  939. selected = None
  940. inserted = False
  941. try:
  942. with self.engine.begin() as connection:
  943. self._attest_binding_locked(
  944. connection,
  945. binding_id=binding,
  946. binding_hash=binding_hash,
  947. kind=kind,
  948. )
  949. selected = connection.execute(
  950. text(
  951. """
  952. INSERT INTO public.rule_run_artifacts (
  953. id, correlation_id, binding_id, artifact_ref,
  954. artifact_digest, row_count, schema_hash,
  955. schema_fields, artifact_kind, binding_hash,
  956. handoff_status, expires_at
  957. ) VALUES (
  958. CAST(:id AS uuid),
  959. CAST(:correlation_id AS uuid),
  960. CAST(:binding_id AS uuid), :artifact_ref,
  961. :artifact_digest, :row_count, :schema_hash,
  962. CAST(:schema_fields AS jsonb), :artifact_kind,
  963. :binding_hash, 'pending',
  964. CAST(:expires_at AS timestamptz)
  965. )
  966. ON CONFLICT (
  967. correlation_id, binding_id, artifact_kind
  968. ) DO NOTHING
  969. RETURNING id::text AS id, correlation_id::text,
  970. binding_id::text, artifact_ref,
  971. artifact_digest, row_count, schema_hash,
  972. schema_fields, artifact_kind, binding_hash,
  973. expires_at, handoff_status
  974. """
  975. ),
  976. parameters,
  977. ).mappings().one_or_none()
  978. inserted = selected is not None
  979. if selected is None:
  980. selected = connection.execute(
  981. text(
  982. """
  983. SELECT id::text AS id, correlation_id::text,
  984. binding_id::text, artifact_ref,
  985. artifact_digest, row_count, schema_hash,
  986. schema_fields, artifact_kind, binding_hash,
  987. expires_at, handoff_status
  988. FROM public.rule_run_artifacts
  989. WHERE correlation_id =
  990. CAST(:correlation_id AS uuid)
  991. AND binding_id = CAST(:binding_id AS uuid)
  992. AND artifact_kind = :artifact_kind
  993. FOR UPDATE
  994. """
  995. ),
  996. parameters,
  997. ).mappings().one_or_none()
  998. except ValueError:
  999. raise
  1000. except Exception as exc:
  1001. try:
  1002. selected = self._lookup_handoff(
  1003. correlation_id=correlation,
  1004. binding_id=binding,
  1005. kind=kind,
  1006. )
  1007. except Exception as recheck_exc:
  1008. raise ArtifactCommitUnknown(
  1009. "artifact reservation commit outcome is unknown"
  1010. ) from recheck_exc
  1011. if (
  1012. selected is None
  1013. or str(selected["artifact_ref"]) != artifact_ref
  1014. or str(selected["artifact_digest"]) != artifact["digest"]
  1015. or str(selected["binding_hash"]) != binding_hash
  1016. ):
  1017. raise ArtifactCommitUnknown(
  1018. "artifact reservation commit outcome is unknown"
  1019. ) from exc
  1020. inserted = True
  1021. if selected is None:
  1022. raise ArtifactCommitUnknown(
  1023. "artifact reservation commit outcome is unknown"
  1024. )
  1025. row = dict(selected)
  1026. if str(row["binding_hash"]) != binding_hash:
  1027. raise ValueError("artifact reservation binding hash conflicts")
  1028. if str(row["artifact_digest"]) != artifact["digest"]:
  1029. raise ValueError(
  1030. "immutable artifact catalog digest conflicts with retry"
  1031. )
  1032. status = str(row["handoff_status"])
  1033. if not inserted:
  1034. if status == "ready":
  1035. return {
  1036. **self._catalog_artifact(row),
  1037. "correlation_id": correlation,
  1038. "reservation_id": str(row["id"]),
  1039. "handoff_status": "ready",
  1040. "upload_required": False,
  1041. }
  1042. if status == "pending":
  1043. raise ArtifactHandoffPending(
  1044. "artifact handoff is already pending"
  1045. )
  1046. raise ValueError("artifact handoff has failed")
  1047. return {
  1048. **self._catalog_artifact(row),
  1049. "correlation_id": correlation,
  1050. "reservation_id": str(row["id"]),
  1051. "handoff_status": status,
  1052. "upload_required": status == "pending",
  1053. }
  1054. def _abort_pending(self, reservation_id: str) -> None:
  1055. with self.engine.begin() as connection:
  1056. connection.execute(
  1057. text(
  1058. """
  1059. DELETE FROM public.rule_run_artifacts
  1060. WHERE id = CAST(:id AS uuid)
  1061. AND handoff_status = 'pending'
  1062. """
  1063. ),
  1064. {"id": reservation_id},
  1065. )
  1066. def finalize(
  1067. self,
  1068. *,
  1069. reservation: dict[str, Any],
  1070. binding_id: str,
  1071. binding_hash: str,
  1072. kind: str,
  1073. ) -> dict[str, Any]:
  1074. reservation_id = _uid(
  1075. reservation.get("reservation_id"), "artifact reservation id"
  1076. )
  1077. binding = _uid(binding_id, "artifact binding id")
  1078. selected = None
  1079. try:
  1080. with self.engine.begin() as connection:
  1081. self._attest_binding_locked(
  1082. connection,
  1083. binding_id=binding,
  1084. binding_hash=binding_hash,
  1085. kind=kind,
  1086. )
  1087. selected = connection.execute(
  1088. text(
  1089. """
  1090. UPDATE public.rule_run_artifacts
  1091. SET handoff_status = 'ready',
  1092. ready_at = CURRENT_TIMESTAMP,
  1093. updated_at = CURRENT_TIMESTAMP,
  1094. failure_code = NULL,
  1095. failed_at = NULL
  1096. WHERE id = CAST(:id AS uuid)
  1097. AND binding_id = CAST(:binding_id AS uuid)
  1098. AND binding_hash = :binding_hash
  1099. AND artifact_digest = :artifact_digest
  1100. AND handoff_status = 'pending'
  1101. RETURNING id::text AS id, correlation_id::text,
  1102. binding_id::text, artifact_ref,
  1103. artifact_digest, row_count, schema_hash,
  1104. schema_fields, artifact_kind, binding_hash,
  1105. expires_at, handoff_status
  1106. """
  1107. ),
  1108. {
  1109. "id": reservation_id,
  1110. "binding_id": binding,
  1111. "binding_hash": binding_hash,
  1112. "artifact_digest": reservation["digest"],
  1113. },
  1114. ).mappings().one_or_none()
  1115. if selected is None:
  1116. raise ValueError(
  1117. "pending artifact handoff no longer matches"
  1118. )
  1119. except ValueError:
  1120. raise
  1121. except Exception as exc:
  1122. try:
  1123. selected = self._lookup_handoff(
  1124. correlation_id=_uid(
  1125. reservation["correlation_id"],
  1126. "artifact correlation id",
  1127. ),
  1128. binding_id=binding,
  1129. kind=kind,
  1130. )
  1131. except Exception as recheck_exc:
  1132. raise ArtifactCommitUnknown(
  1133. "artifact finalize commit outcome is unknown"
  1134. ) from recheck_exc
  1135. if (
  1136. selected is None
  1137. or str(selected["id"]) != reservation_id
  1138. or str(selected["artifact_digest"])
  1139. != reservation["digest"]
  1140. or str(selected["binding_hash"]) != binding_hash
  1141. or str(selected["handoff_status"]) != "ready"
  1142. ):
  1143. raise ArtifactCommitUnknown(
  1144. "artifact finalize commit outcome is unknown"
  1145. ) from exc
  1146. return self._catalog_artifact(selected)
  1147. def publish_path(
  1148. self,
  1149. path: str,
  1150. *,
  1151. binding_id: str,
  1152. binding_hash: str,
  1153. correlation_id: str,
  1154. kind: str,
  1155. ttl_seconds: int,
  1156. schema_fields: list[dict[str, Any]],
  1157. limits: dict[str, int] | None = None,
  1158. ) -> dict[str, Any]:
  1159. """Reserve, upload, and finalize one durable artifact handoff."""
  1160. prepared = self.artifact_store.prepare_path(
  1161. path,
  1162. correlation_id,
  1163. ttl_seconds,
  1164. schema_fields=schema_fields,
  1165. limits=limits,
  1166. )
  1167. reservation = self.reserve(
  1168. binding_id=binding_id,
  1169. correlation_id=correlation_id,
  1170. artifact=prepared,
  1171. kind=kind,
  1172. binding_hash=binding_hash,
  1173. )
  1174. if not reservation["upload_required"]:
  1175. stored = self.artifact_store.describe(
  1176. reservation["artifact_ref"]
  1177. )
  1178. if stored["digest"] != reservation["digest"]:
  1179. raise ValueError(
  1180. "ready artifact catalog does not match storage"
  1181. )
  1182. return {
  1183. key: reservation[key]
  1184. for key in (
  1185. "artifact_ref",
  1186. "digest",
  1187. "row_count",
  1188. "schema_hash",
  1189. "schema_fields",
  1190. "expires_at",
  1191. )
  1192. }
  1193. reserved_artifact = {
  1194. key: reservation[key]
  1195. for key in (
  1196. "artifact_ref",
  1197. "digest",
  1198. "row_count",
  1199. "schema_hash",
  1200. "schema_fields",
  1201. "expires_at",
  1202. )
  1203. }
  1204. try:
  1205. self.artifact_store.upload_path(
  1206. path,
  1207. reserved_artifact,
  1208. limits=limits,
  1209. )
  1210. except Exception:
  1211. with suppress(Exception):
  1212. self.artifact_store.delete(
  1213. reserved_artifact["artifact_ref"]
  1214. )
  1215. with suppress(Exception):
  1216. self._abort_pending(reservation["reservation_id"])
  1217. raise
  1218. return self.finalize(
  1219. reservation=reservation,
  1220. binding_id=binding_id,
  1221. binding_hash=binding_hash,
  1222. kind=kind,
  1223. )
  1224. def _mark_failed(
  1225. self,
  1226. *,
  1227. row_id: str,
  1228. failure_code: str,
  1229. ) -> None:
  1230. with self.engine.begin() as connection:
  1231. connection.execute(
  1232. text(
  1233. """
  1234. UPDATE public.rule_run_artifacts
  1235. SET handoff_status = 'failed',
  1236. failed_at = CURRENT_TIMESTAMP,
  1237. updated_at = CURRENT_TIMESTAMP,
  1238. failure_code = :failure_code
  1239. WHERE id = CAST(:id AS uuid)
  1240. AND handoff_status IN ('pending','ready')
  1241. """
  1242. ),
  1243. {"id": row_id, "failure_code": failure_code},
  1244. )
  1245. def reconcile(
  1246. self,
  1247. *,
  1248. limit: int = 100,
  1249. grace_seconds: int = 300,
  1250. ) -> dict[str, int]:
  1251. """Repair bounded catalog/store drift after the grace period."""
  1252. if (
  1253. isinstance(limit, bool)
  1254. or not isinstance(limit, int)
  1255. or limit < 1
  1256. or limit > 1_000
  1257. ):
  1258. raise ValueError("artifact reconciliation limit is invalid")
  1259. if (
  1260. isinstance(grace_seconds, bool)
  1261. or not isinstance(grace_seconds, int)
  1262. or grace_seconds < 30
  1263. or grace_seconds > 86_400
  1264. ):
  1265. raise ValueError("artifact reconciliation grace is invalid")
  1266. result = {
  1267. "pending_finalized": 0,
  1268. "pending_deleted": 0,
  1269. "ready_failed": 0,
  1270. "orphans_deleted": 0,
  1271. }
  1272. with self.engine.connect() as connection:
  1273. rows = connection.execute(
  1274. text(
  1275. """
  1276. SELECT id::text AS id, correlation_id::text,
  1277. binding_id::text, artifact_ref, artifact_digest,
  1278. row_count, schema_hash, schema_fields,
  1279. artifact_kind, binding_hash, expires_at,
  1280. handoff_status
  1281. FROM public.rule_run_artifacts
  1282. WHERE handoff_status IN ('pending','ready')
  1283. AND updated_at <= CURRENT_TIMESTAMP
  1284. - make_interval(secs => :grace_seconds)
  1285. ORDER BY updated_at, id
  1286. LIMIT :limit
  1287. """
  1288. ),
  1289. {
  1290. "grace_seconds": grace_seconds,
  1291. "limit": limit,
  1292. },
  1293. ).mappings().all()
  1294. for raw_row in rows:
  1295. row = dict(raw_row)
  1296. row_id = str(row["id"])
  1297. status = str(row["handoff_status"])
  1298. invalid_object = False
  1299. try:
  1300. self.artifact_store._parse_ref(row["artifact_ref"])
  1301. stored = self.artifact_store.describe_optional(
  1302. row["artifact_ref"]
  1303. )
  1304. except Exception:
  1305. invalid_object = True
  1306. stored = None
  1307. if invalid_object:
  1308. if status == "pending":
  1309. with suppress(Exception):
  1310. self.artifact_store.delete(row["artifact_ref"])
  1311. self._mark_failed(
  1312. row_id=row_id,
  1313. failure_code="pending_object_invalid",
  1314. )
  1315. else:
  1316. self._mark_failed(
  1317. row_id=row_id,
  1318. failure_code="ready_object_invalid",
  1319. )
  1320. result["ready_failed"] += 1
  1321. continue
  1322. if status == "ready":
  1323. if stored is None:
  1324. self._mark_failed(
  1325. row_id=row_id,
  1326. failure_code="ready_object_missing",
  1327. )
  1328. result["ready_failed"] += 1
  1329. continue
  1330. if stored is None:
  1331. with self.engine.begin() as connection:
  1332. deleted = connection.execute(
  1333. text(
  1334. """
  1335. DELETE FROM public.rule_run_artifacts
  1336. WHERE id = CAST(:id AS uuid)
  1337. AND handoff_status = 'pending'
  1338. """
  1339. ),
  1340. {"id": row_id},
  1341. )
  1342. if int(deleted.rowcount or 0) == 1:
  1343. result["pending_deleted"] += 1
  1344. continue
  1345. if any(
  1346. (
  1347. stored["digest"] != str(row["artifact_digest"]),
  1348. stored["row_count"] != int(row["row_count"]),
  1349. stored["schema_hash"] != str(row["schema_hash"]),
  1350. )
  1351. ):
  1352. with suppress(Exception):
  1353. self.artifact_store.delete(row["artifact_ref"])
  1354. self._mark_failed(
  1355. row_id=row_id,
  1356. failure_code="pending_object_invalid",
  1357. )
  1358. continue
  1359. with self.engine.begin() as connection:
  1360. finalized = connection.execute(
  1361. text(
  1362. """
  1363. UPDATE public.rule_run_artifacts a
  1364. SET handoff_status = 'ready',
  1365. ready_at = CURRENT_TIMESTAMP,
  1366. updated_at = CURRENT_TIMESTAMP,
  1367. failure_code = NULL,
  1368. failed_at = NULL
  1369. WHERE a.id = CAST(:id AS uuid)
  1370. AND a.handoff_status = 'pending'
  1371. AND EXISTS (
  1372. SELECT 1
  1373. FROM public.dataflow_dataset_bindings b
  1374. WHERE b.id = a.binding_id
  1375. AND b.binding_hash = a.binding_hash
  1376. AND b.object_kind = 'parquet_artifact'
  1377. AND b.access_mode IN (
  1378. 'read','write','read_write'
  1379. )
  1380. )
  1381. RETURNING a.id
  1382. """
  1383. ),
  1384. {"id": row_id},
  1385. )
  1386. if int(finalized.rowcount or 0) == 1:
  1387. result["pending_finalized"] += 1
  1388. else:
  1389. self._mark_failed(
  1390. row_id=row_id,
  1391. failure_code="pending_binding_changed",
  1392. )
  1393. remaining = limit - len(rows)
  1394. if remaining <= 0:
  1395. return result
  1396. now = _now_utc(self.artifact_store.clock)
  1397. candidates = []
  1398. scanned = 0
  1399. for item in self.artifact_store.client.list_objects(
  1400. self.artifact_store.bucket,
  1401. prefix="rules/",
  1402. recursive=True,
  1403. ):
  1404. scanned += 1
  1405. if scanned > limit * 10 or len(candidates) >= remaining:
  1406. break
  1407. key = str(getattr(item, "object_name", ""))
  1408. ref = f"minio://{self.artifact_store.bucket}/{key}"
  1409. try:
  1410. self.artifact_store._parse_ref(ref)
  1411. except ValueError:
  1412. continue
  1413. modified = getattr(item, "last_modified", None)
  1414. if not isinstance(modified, datetime):
  1415. continue
  1416. if modified.tzinfo is None:
  1417. modified = modified.replace(tzinfo=UTC)
  1418. if modified.astimezone(UTC) > now - timedelta(
  1419. seconds=grace_seconds
  1420. ):
  1421. continue
  1422. candidates.append(ref)
  1423. if not candidates:
  1424. return result
  1425. with self.engine.connect() as connection:
  1426. referenced = {
  1427. str(row["artifact_ref"])
  1428. for row in connection.execute(
  1429. text(
  1430. """
  1431. SELECT artifact_ref
  1432. FROM public.rule_run_artifacts
  1433. WHERE artifact_ref =
  1434. ANY(CAST(:artifact_refs AS text[]))
  1435. """
  1436. ),
  1437. {"artifact_refs": candidates},
  1438. ).mappings().all()
  1439. }
  1440. for ref in candidates:
  1441. if ref in referenced:
  1442. continue
  1443. self.artifact_store.delete(ref)
  1444. result["orphans_deleted"] += 1
  1445. return result
  1446. def cleanup_expired(self, *, limit: int = 100) -> int:
  1447. if (
  1448. isinstance(limit, bool)
  1449. or not isinstance(limit, int)
  1450. or limit < 1
  1451. or limit > 1_000
  1452. ):
  1453. raise ValueError("artifact cleanup limit is invalid")
  1454. removed = 0
  1455. with self.engine.begin() as connection:
  1456. rows = connection.execute(
  1457. text(
  1458. """
  1459. SELECT id::text AS id, artifact_ref
  1460. FROM public.rule_run_artifacts
  1461. WHERE expires_at <= CURRENT_TIMESTAMP
  1462. ORDER BY expires_at, id
  1463. LIMIT :limit
  1464. FOR UPDATE SKIP LOCKED
  1465. """
  1466. ),
  1467. {"limit": limit},
  1468. ).mappings().all()
  1469. for row in rows:
  1470. self.artifact_store.delete(str(row["artifact_ref"]))
  1471. connection.execute(
  1472. text(
  1473. """
  1474. DELETE FROM public.rule_run_artifacts
  1475. WHERE id = CAST(:id AS uuid)
  1476. """
  1477. ),
  1478. {"id": str(row["id"])},
  1479. )
  1480. removed += 1
  1481. return removed