artifacts.py 60 KB

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