umf-access 0.1.0.dev8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- umf_access/__init__.py +109 -0
- umf_access/adoption.py +41 -0
- umf_access/build/__init__.py +2 -0
- umf_access/build/approximate.py +34 -0
- umf_access/build/catalog.py +1626 -0
- umf_access/build/commands.py +394 -0
- umf_access/build/pg_privileges.py +1544 -0
- umf_access/build/privileges.py +134 -0
- umf_access/build/search.py +365 -0
- umf_access/build/unity_search.py +104 -0
- umf_access/bulk.py +227 -0
- umf_access/canonical.py +23 -0
- umf_access/capture.py +410 -0
- umf_access/catalog.py +325 -0
- umf_access/codec_support.py +427 -0
- umf_access/commands.py +93 -0
- umf_access/delta_read.py +758 -0
- umf_access/dsl/__init__.py +148 -0
- umf_access/dsl/_context.py +36 -0
- umf_access/dsl/_expressions.py +625 -0
- umf_access/dsl/_joined.py +4 -0
- umf_access/dsl/_nodes.py +207 -0
- umf_access/dsl/_query.py +5559 -0
- umf_access/dsl/_selection.py +143 -0
- umf_access/dsl/navigation.py +302 -0
- umf_access/dsl/render.py +516 -0
- umf_access/dsl/search.py +343 -0
- umf_access/engine_catalog.py +563 -0
- umf_access/generated_core.py +5 -0
- umf_access/lifecycle/__init__.py +46 -0
- umf_access/lifecycle/_darwin_process_observer.c +306 -0
- umf_access/lifecycle/approval.py +366 -0
- umf_access/lifecycle/backfills.py +79 -0
- umf_access/lifecycle/catalog.py +289 -0
- umf_access/lifecycle/cli.py +231 -0
- umf_access/lifecycle/concurrent.py +196 -0
- umf_access/lifecycle/conversion_policy.py +188 -0
- umf_access/lifecycle/correspondence.py +203 -0
- umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
- umf_access/lifecycle/generation_authority_session.py +125 -0
- umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
- umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
- umf_access/lifecycle/generation_ingress.py +185 -0
- umf_access/lifecycle/generation_root_registry.py +138 -0
- umf_access/lifecycle/head.py +250 -0
- umf_access/lifecycle/head_view.py +81 -0
- umf_access/lifecycle/host.py +1183 -0
- umf_access/lifecycle/ingress_custody.py +750 -0
- umf_access/lifecycle/ingress_local_postgres.py +7990 -0
- umf_access/lifecycle/ingress_store.py +1488 -0
- umf_access/lifecycle/ledger.py +276 -0
- umf_access/lifecycle/ledger_schema.py +116 -0
- umf_access/lifecycle/mixed.py +593 -0
- umf_access/lifecycle/outcome_schema.py +136 -0
- umf_access/lifecycle/owner_approval_core.py +1810 -0
- umf_access/lifecycle/owner_authority.py +472 -0
- umf_access/lifecycle/owner_bootstrap.py +2077 -0
- umf_access/lifecycle/owner_wire.py +161 -0
- umf_access/lifecycle/phase_fence.py +52 -0
- umf_access/lifecycle/phase_policy.py +422 -0
- umf_access/lifecycle/privileges.py +145 -0
- umf_access/lifecycle/probe.py +39 -0
- umf_access/lifecycle/progress.py +497 -0
- umf_access/lifecycle/roles.py +96 -0
- umf_access/lifecycle/row_originals.py +1712 -0
- umf_access/lifecycle/row_originals_creation.py +759 -0
- umf_access/lifecycle/row_originals_receipt.py +413 -0
- umf_access/lifecycle/seeds.py +99 -0
- umf_access/lifecycle/sql_containment.py +358 -0
- umf_access/lifecycle/sql_containment_cli.py +33 -0
- umf_access/lifecycle/sql_containment_parser.py +20 -0
- umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
- umf_access/lifecycle/table_boundary.py +22 -0
- umf_access/lifecycle/target_custody_codec.py +788 -0
- umf_access/lifecycle/witness.py +72 -0
- umf_access/managed_actions.py +271 -0
- umf_access/managed_bulk.py +353 -0
- umf_access/managed_delta.py +150 -0
- umf_access/managed_support.py +166 -0
- umf_access/manifest_commands.py +278 -0
- umf_access/native_actions.py +1007 -0
- umf_access/native_program.py +570 -0
- umf_access/pages.py +125 -0
- umf_access/postgres_bulk.py +509 -0
- umf_access/postgres_read.py +1230 -0
- umf_access/postgres_search.py +639 -0
- umf_access/protocols.py +665 -0
- umf_access/py.typed +0 -0
- umf_access/related_keys.py +233 -0
- umf_access/reviewed.py +706 -0
- umf_access/search_catalog.py +122 -0
- umf_access/targets.py +312 -0
- umf_access/types.py +220 -0
- umf_access/unified/__init__.py +187 -0
- umf_access/unified/_binding.py +654 -0
- umf_access/unified/head_session.py +144 -0
- umf_access/unified/native_binding.py +143 -0
- umf_access/unified/operation_values.py +173 -0
- umf_access/unified/outcome_values.py +76 -0
- umf_access/unified/session_async.py +161 -0
- umf_access/unified/session_binding.py +108 -0
- umf_access/unified/session_policy.py +152 -0
- umf_access/unified/session_psycopg2.py +70 -0
- umf_access/unified/session_sqlalchemy.py +161 -0
- umf_access/unified/session_sync.py +148 -0
- umf_access/unified/table_reads.py +314 -0
- umf_access/unified/table_writes.py +193 -0
- umf_access/unity_search.py +312 -0
- umf_access/values.py +280 -0
- umf_access/verification.py +64 -0
- umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
- umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
- umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
- umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
umf_access/delta_read.py
ADDED
|
@@ -0,0 +1,758 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Explicit local Spark4/Delta4 snapshot reads of original Weft programs.
|
|
3
|
+
|
|
4
|
+
The host owns the Spark session and its single-tenant administrative deployment.
|
|
5
|
+
No managed Unity Catalog, temporal or mutation claim is implied.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
from collections.abc import Callable, Generator
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from datetime import timedelta
|
|
15
|
+
from decimal import Decimal
|
|
16
|
+
from threading import Event, Timer
|
|
17
|
+
from typing import Any, TypeVar
|
|
18
|
+
from uuid import uuid4
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel
|
|
21
|
+
|
|
22
|
+
from .adoption import TargetIdentity
|
|
23
|
+
from .pages import (
|
|
24
|
+
ReadContinuation,
|
|
25
|
+
ReadObligationUnmet,
|
|
26
|
+
ReadPage,
|
|
27
|
+
SnapshotVersions,
|
|
28
|
+
StaleContinuation,
|
|
29
|
+
StreamLimitReached,
|
|
30
|
+
stream_page_size,
|
|
31
|
+
)
|
|
32
|
+
from .postgres_read import TimedOut, _checked_sort_values
|
|
33
|
+
from .reviewed import CatalogRead, validate_list_parameters
|
|
34
|
+
from .targets import NotCompiledForTarget, TargetMismatch, _milliseconds, binding_digest
|
|
35
|
+
from .values import ValueRuleError, validate_decimal, validate_integer, validate_vector
|
|
36
|
+
|
|
37
|
+
P = TypeVar("P", bound=BaseModel)
|
|
38
|
+
R = TypeVar("R", bound=BaseModel)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class DeltaSnapshot:
|
|
43
|
+
table: str
|
|
44
|
+
table_uuid: str
|
|
45
|
+
version: int
|
|
46
|
+
|
|
47
|
+
def __post_init__(self) -> None:
|
|
48
|
+
if (
|
|
49
|
+
not self.table
|
|
50
|
+
or not self.table_uuid
|
|
51
|
+
or type(self.version) is not int
|
|
52
|
+
or self.version < 0
|
|
53
|
+
):
|
|
54
|
+
raise TargetMismatch("explicit original Delta UUID and version required")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True)
|
|
58
|
+
class SparkConfiguration:
|
|
59
|
+
schema: str
|
|
60
|
+
binding_sha256: str
|
|
61
|
+
snapshots: tuple[DeltaSnapshot, ...]
|
|
62
|
+
default_timeout: timedelta
|
|
63
|
+
administrative_single_tenant: bool
|
|
64
|
+
|
|
65
|
+
def __post_init__(self) -> None:
|
|
66
|
+
if (
|
|
67
|
+
self.administrative_single_tenant is not True
|
|
68
|
+
or not self.schema
|
|
69
|
+
or not self.snapshots
|
|
70
|
+
or len({s.table for s in self.snapshots}) != len(self.snapshots)
|
|
71
|
+
):
|
|
72
|
+
raise TargetMismatch(
|
|
73
|
+
"explicit single-tenant local snapshot profile required"
|
|
74
|
+
)
|
|
75
|
+
if len(self.binding_sha256) != 64 or any(
|
|
76
|
+
c not in "0123456789abcdef" for c in self.binding_sha256
|
|
77
|
+
):
|
|
78
|
+
raise TargetMismatch("binding digest required")
|
|
79
|
+
_milliseconds(self.default_timeout, self.default_timeout)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _ident(value: str) -> str:
|
|
83
|
+
if not value or "\0" in value:
|
|
84
|
+
raise TargetMismatch("native identifier required")
|
|
85
|
+
return "`" + value.replace("`", "``") + "`"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _numeric_token(value: object, carrier: str) -> str:
|
|
89
|
+
if carrier == "integer":
|
|
90
|
+
if type(value) is not int or value.bit_length() > 33220:
|
|
91
|
+
raise ValueError("bounded exact Integer parameter required")
|
|
92
|
+
number = Decimal(value)
|
|
93
|
+
else:
|
|
94
|
+
if type(value) is not Decimal or not value.is_finite():
|
|
95
|
+
raise ValueError("exact finite Decimal parameter required")
|
|
96
|
+
number = value
|
|
97
|
+
sign, digits, exponent = number.as_tuple()
|
|
98
|
+
assert type(exponent) is int
|
|
99
|
+
size = (len(digits) + exponent if exponent >= 0 else
|
|
100
|
+
len(digits) + 1 if len(digits) + exponent > 0 else 2 - exponent) + sign
|
|
101
|
+
if size > 10000:
|
|
102
|
+
raise ValueError("exact numeric parameter exceeds original token budget")
|
|
103
|
+
token = format(number, "f")
|
|
104
|
+
if len(token) > 10000:
|
|
105
|
+
raise ValueError("exact numeric parameter exceeds original token budget")
|
|
106
|
+
return token
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _numeric_parameters(artifact: dict[str, Any], values: dict[str, Any]) -> dict[str, Any]:
|
|
110
|
+
"""Execute only the original compiler's closed exact numeric text codec."""
|
|
111
|
+
descriptor = artifact["obligations"].get("numericPredicateParameters")
|
|
112
|
+
if descriptor is None:
|
|
113
|
+
return values
|
|
114
|
+
expected = [
|
|
115
|
+
{name: parameter[name] for name in ("name", "carrier", "nullable")}
|
|
116
|
+
for parameter in artifact["parameters"]
|
|
117
|
+
if parameter["carrier"] in ("integer", "decimal") and parameter.get("container") is None
|
|
118
|
+
]
|
|
119
|
+
if descriptor != {"version": "weft.spark-exact-numeric-text/0.1", "parameters": expected,
|
|
120
|
+
"maximumTokenBytes": 10000, "format": "finite-plain-base-ten"} or not expected:
|
|
121
|
+
raise TargetMismatch("original exact Spark numeric parameter profile required")
|
|
122
|
+
encoded = dict(values)
|
|
123
|
+
for parameter in expected:
|
|
124
|
+
value = values[parameter["name"]]
|
|
125
|
+
if value is None:
|
|
126
|
+
if parameter["nullable"] is not True:
|
|
127
|
+
raise ValueError("forbidden NULL numeric parameter")
|
|
128
|
+
continue
|
|
129
|
+
encoded[parameter["name"]] = _numeric_token(value, parameter["carrier"])
|
|
130
|
+
return encoded
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _list_descriptor(artifact: dict[str, Any]) -> list[dict[str, Any]]:
|
|
134
|
+
descriptor = artifact["obligations"].get("listPredicateParameters")
|
|
135
|
+
parameters = [parameter for parameter in artifact["parameters"] if parameter.get("container") == "list"]
|
|
136
|
+
if descriptor is None:
|
|
137
|
+
if parameters:
|
|
138
|
+
raise TargetMismatch("original Spark list parameter transport descriptor required")
|
|
139
|
+
return []
|
|
140
|
+
if any(set(parameter) != {"name", "carrier", "nullable", "container", "elementNullable", "maxItems"}
|
|
141
|
+
or type(parameter["name"]) is not str or parameter["carrier"] not in ("string", "boolean", "integer", "decimal")
|
|
142
|
+
or parameter["nullable"] is not False or type(parameter["elementNullable"]) is not bool
|
|
143
|
+
or type(parameter["maxItems"]) is not int or not 1 <= parameter["maxItems"] <= 1000 for parameter in parameters):
|
|
144
|
+
raise TargetMismatch("original Spark list facets differ")
|
|
145
|
+
expected = [{name: parameter[name] for name in ("name", "carrier", "nullable", "elementNullable", "maxItems")}
|
|
146
|
+
for parameter in parameters]
|
|
147
|
+
if not expected or descriptor != {"version": "weft.spark-list-json/0.1", "parameters": expected,
|
|
148
|
+
"maximumElementBytes": 10000, "maximumEncodedBytes": 1000000,
|
|
149
|
+
"format": "typed-json-array"}:
|
|
150
|
+
raise TargetMismatch("original exact Spark list parameter profile required")
|
|
151
|
+
return parameters
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _parameter_values(artifact: dict[str, Any], values: dict[str, Any]) -> dict[str, Any]:
|
|
155
|
+
parameters = _list_descriptor(artifact)
|
|
156
|
+
validate_list_parameters(artifact["parameters"], values)
|
|
157
|
+
encoded = dict(values)
|
|
158
|
+
for parameter in parameters:
|
|
159
|
+
items = []
|
|
160
|
+
size = 2
|
|
161
|
+
for value in values[parameter["name"]]:
|
|
162
|
+
item = (_numeric_token(value, parameter["carrier"])
|
|
163
|
+
if value is not None and parameter["carrier"] in ("integer", "decimal") else value)
|
|
164
|
+
if isinstance(item, str) and len(item.encode("utf-8")) > 10000:
|
|
165
|
+
raise ValueError("exact list element exceeds original byte budget")
|
|
166
|
+
size += len(json.dumps(item, ensure_ascii=False, allow_nan=False).encode("utf-8")) + (1 if items else 0)
|
|
167
|
+
if size > 1000000:
|
|
168
|
+
raise ValueError("exact list exceeds original encoded byte budget")
|
|
169
|
+
items.append(item)
|
|
170
|
+
encoded[parameter["name"]] = json.dumps(items, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
|
|
171
|
+
return _numeric_parameters(artifact, encoded)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _runtime_obligations(artifact: dict[str, Any]) -> None:
|
|
175
|
+
known = {"transaction", "snapshot", "principal", "ansiEnabled", "sparkVersion", "deltaVersion",
|
|
176
|
+
"binaryStringCollation", "escapedStringLiterals", "rowCap", "timeout", "tableIdentity",
|
|
177
|
+
"streamPageSize", "numericPredicateParameters", "listPredicateParameters"}
|
|
178
|
+
obligations = artifact.get("obligations")
|
|
179
|
+
if type(obligations) is not dict or set(obligations) - known:
|
|
180
|
+
raise TargetMismatch("unrecognized original Spark runtime obligation")
|
|
181
|
+
_list_descriptor(artifact)
|
|
182
|
+
fixed = {"principal": "administrative-single-tenant", "ansiEnabled": True,
|
|
183
|
+
"sparkVersion": "4.0.1", "deltaVersion": "4.0.0", "binaryStringCollation": True,
|
|
184
|
+
"escapedStringLiterals": False}
|
|
185
|
+
if any(type(obligations.get(name)) is not type(value) or obligations[name] != value
|
|
186
|
+
for name, value in fixed.items()):
|
|
187
|
+
raise TargetMismatch("original Spark runtime profile differs")
|
|
188
|
+
snapshot = obligations.get("snapshot", True)
|
|
189
|
+
if (type(snapshot) is not bool
|
|
190
|
+
or obligations.get("transaction") != ("snapshot-read" if snapshot else "live-read")
|
|
191
|
+
or obligations.get("tableIdentity") != ("uuid-and-version" if snapshot else "uuid")
|
|
192
|
+
or obligations.get("timeout") not in ("one-call-deadline", "one-page-deadline")
|
|
193
|
+
or type(obligations.get("rowCap")) is not int or not 1 <= obligations["rowCap"] <= 1000):
|
|
194
|
+
raise TargetMismatch("original Spark snapshot or execution obligations differ")
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _native_projection(output: dict[str, Any], value: object) -> object:
|
|
198
|
+
if value is None:
|
|
199
|
+
if output.get("nullable") is not True:
|
|
200
|
+
raise ReadObligationUnmet("native projection returned forbidden NULL")
|
|
201
|
+
return None
|
|
202
|
+
carrier = output["carrier"]
|
|
203
|
+
if carrier == "binary":
|
|
204
|
+
if type(value) not in (bytes, bytearray):
|
|
205
|
+
raise ReadObligationUnmet("native Spark Binary carrier differs")
|
|
206
|
+
return bytes(value)
|
|
207
|
+
if carrier == "vector":
|
|
208
|
+
if output.get("nativeType") != "array<float>" or type(value) is not list:
|
|
209
|
+
raise ReadObligationUnmet("native Spark Vector carrier differs")
|
|
210
|
+
return validate_vector(tuple(value), dimensions=output["dimensions"])
|
|
211
|
+
if carrier == "integer" and "integerWidth" in output:
|
|
212
|
+
width = output["integerWidth"]
|
|
213
|
+
return validate_integer(value, bits=width["bits"], signed=width["signed"])
|
|
214
|
+
if carrier == "decimal" and "precision" in output:
|
|
215
|
+
return validate_decimal(
|
|
216
|
+
value, precision=output["precision"], scale=output["scale"]
|
|
217
|
+
)
|
|
218
|
+
return value
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _expired_snapshot_error(error: Exception) -> bool:
|
|
222
|
+
# Optional driver dependency: import only while handling a real Spark error.
|
|
223
|
+
# This exact native discriminator was witnessed after Delta4 VACUUM removed
|
|
224
|
+
# a pinned snapshot's files. Unknown driver errors retain their original type.
|
|
225
|
+
try:
|
|
226
|
+
from py4j.protocol import Py4JError, Py4JJavaError
|
|
227
|
+
except ModuleNotFoundError as missing:
|
|
228
|
+
if missing.name in ("py4j", "py4j.protocol"):
|
|
229
|
+
return False
|
|
230
|
+
raise
|
|
231
|
+
|
|
232
|
+
if not isinstance(error, Py4JJavaError):
|
|
233
|
+
return False
|
|
234
|
+
try:
|
|
235
|
+
native = error.java_exception
|
|
236
|
+
return (
|
|
237
|
+
native.getClass().getName() == "org.apache.spark.SparkException"
|
|
238
|
+
and native.getCondition() == "FAILED_READ_FILE.FILE_NOT_EXIST"
|
|
239
|
+
)
|
|
240
|
+
except Py4JError:
|
|
241
|
+
error.add_note(
|
|
242
|
+
"Native snapshot discriminator unavailable; original error retained"
|
|
243
|
+
)
|
|
244
|
+
return False
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class SparkDeltaTarget:
|
|
248
|
+
def __init__(
|
|
249
|
+
self,
|
|
250
|
+
session: Any,
|
|
251
|
+
configuration: SparkConfiguration,
|
|
252
|
+
entries: tuple[CatalogRead[Any, Any], ...] = (),
|
|
253
|
+
):
|
|
254
|
+
self.session, self.configuration, self.entries = session, configuration, entries
|
|
255
|
+
|
|
256
|
+
def identity(self) -> TargetIdentity:
|
|
257
|
+
if self.session.version != "4.0.1":
|
|
258
|
+
raise TargetMismatch("pinned native Spark4.0.1 required")
|
|
259
|
+
return TargetIdentity(
|
|
260
|
+
"spark-delta",
|
|
261
|
+
"weft-databricks",
|
|
262
|
+
"raw-read/0.1",
|
|
263
|
+
"weft.raw-read/0.1",
|
|
264
|
+
self.configuration.binding_sha256,
|
|
265
|
+
(("spark", "4.0.1"), ("delta", "4.0.0")),
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
def _profile(self) -> None:
|
|
269
|
+
self.identity()
|
|
270
|
+
conf = self.session.conf
|
|
271
|
+
for name, value in [
|
|
272
|
+
("spark.sql.ansi.enabled", "true"),
|
|
273
|
+
("spark.sql.parser.escapedStringLiterals", "false"),
|
|
274
|
+
("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension"),
|
|
275
|
+
(
|
|
276
|
+
"spark.sql.catalog.spark_catalog",
|
|
277
|
+
"org.apache.spark.sql.delta.catalog.DeltaCatalog",
|
|
278
|
+
),
|
|
279
|
+
]:
|
|
280
|
+
if conf.get(name) != value:
|
|
281
|
+
raise TargetMismatch(
|
|
282
|
+
"native Spark settings differ from compiled profile"
|
|
283
|
+
)
|
|
284
|
+
# This public package manifest is observed on the driver JVM, rather
|
|
285
|
+
# than inferring Delta's version from a Python distribution label.
|
|
286
|
+
version = (
|
|
287
|
+
self.session._jvm.java.lang.Thread.currentThread()
|
|
288
|
+
.getContextClassLoader()
|
|
289
|
+
.loadClass("io.delta.tables.DeltaTable")
|
|
290
|
+
.getPackage()
|
|
291
|
+
.getImplementationVersion()
|
|
292
|
+
)
|
|
293
|
+
if version != "4.0.0":
|
|
294
|
+
raise TargetMismatch("native Delta4.0.0 class manifest required")
|
|
295
|
+
|
|
296
|
+
def _inventory(
|
|
297
|
+
self,
|
|
298
|
+
artifact: dict[str, Any],
|
|
299
|
+
*,
|
|
300
|
+
continuation: bool = False,
|
|
301
|
+
check_deadline: Callable[[], None] | None = None,
|
|
302
|
+
) -> SnapshotVersions:
|
|
303
|
+
_runtime_obligations(artifact)
|
|
304
|
+
if check_deadline is not None:
|
|
305
|
+
check_deadline()
|
|
306
|
+
error = StaleContinuation if continuation else TargetMismatch
|
|
307
|
+
if (
|
|
308
|
+
binding_digest(artifact["binding"]) != self.configuration.binding_sha256
|
|
309
|
+
or artifact["binding"]["schema"] != self.configuration.schema
|
|
310
|
+
):
|
|
311
|
+
raise error("binding differs from original target")
|
|
312
|
+
selected = {s.table: s for s in self.configuration.snapshots}
|
|
313
|
+
references = artifact["referencedTables"]
|
|
314
|
+
names = [item["native"] for item in references]
|
|
315
|
+
if not names or len(set(names)) != len(names):
|
|
316
|
+
raise error("complete original native table inventory required")
|
|
317
|
+
versions = {
|
|
318
|
+
item["table"]: item["version"] for item in artifact["snapshotTables"]
|
|
319
|
+
}
|
|
320
|
+
snapshot = artifact["obligations"].get("snapshot", True)
|
|
321
|
+
if snapshot and (
|
|
322
|
+
set(versions) != set(names)
|
|
323
|
+
or len(versions) != len(artifact["snapshotTables"])
|
|
324
|
+
):
|
|
325
|
+
raise error("complete original snapshot inventory required")
|
|
326
|
+
vector = []
|
|
327
|
+
for native in references:
|
|
328
|
+
snapshot_config = selected.get(native["native"])
|
|
329
|
+
if (
|
|
330
|
+
snapshot_config is None
|
|
331
|
+
or snapshot
|
|
332
|
+
and snapshot_config.version != versions[native["native"]]
|
|
333
|
+
):
|
|
334
|
+
raise error("original compiled snapshot differs")
|
|
335
|
+
table = (
|
|
336
|
+
_ident(self.configuration.schema) + "." + _ident(snapshot_config.table)
|
|
337
|
+
)
|
|
338
|
+
if check_deadline is not None:
|
|
339
|
+
check_deadline()
|
|
340
|
+
detail = self.session.sql("DESCRIBE DETAIL " + table).collect()
|
|
341
|
+
if check_deadline is not None:
|
|
342
|
+
check_deadline()
|
|
343
|
+
if (
|
|
344
|
+
len(detail) != 1
|
|
345
|
+
or detail[0]["format"] != "delta"
|
|
346
|
+
or detail[0]["id"] != snapshot_config.table_uuid
|
|
347
|
+
):
|
|
348
|
+
raise error("Delta table identity changed")
|
|
349
|
+
fields = {f.name: f for f in self.session.table(table).schema.fields}
|
|
350
|
+
if check_deadline is not None:
|
|
351
|
+
check_deadline()
|
|
352
|
+
for column in native["columns"]:
|
|
353
|
+
field = fields.get(column["native"])
|
|
354
|
+
expected = column.get("nativeType") or {
|
|
355
|
+
"string": "string",
|
|
356
|
+
"boolean": "boolean",
|
|
357
|
+
}.get(column["carrier"])
|
|
358
|
+
if (
|
|
359
|
+
field is None
|
|
360
|
+
or field.dataType.simpleString() != expected
|
|
361
|
+
or field.nullable != column["nullable"]
|
|
362
|
+
or expected == "string"
|
|
363
|
+
and field.dataType.collation != "UTF8_BINARY"
|
|
364
|
+
):
|
|
365
|
+
raise error("Delta column shape changed")
|
|
366
|
+
if snapshot:
|
|
367
|
+
vector.append(
|
|
368
|
+
(
|
|
369
|
+
snapshot_config.table,
|
|
370
|
+
snapshot_config.table_uuid,
|
|
371
|
+
versions[snapshot_config.table],
|
|
372
|
+
)
|
|
373
|
+
)
|
|
374
|
+
return tuple(sorted(vector))
|
|
375
|
+
|
|
376
|
+
def _snapshots(self, artifact: dict[str, Any]) -> dict[str, int]:
|
|
377
|
+
if not artifact.get("snapshotTables"):
|
|
378
|
+
raise TargetMismatch(
|
|
379
|
+
"original compiler snapshot parameter inventory required"
|
|
380
|
+
)
|
|
381
|
+
self._inventory(artifact)
|
|
382
|
+
return {}
|
|
383
|
+
|
|
384
|
+
def verify(self) -> None:
|
|
385
|
+
self._profile()
|
|
386
|
+
if not self.entries:
|
|
387
|
+
raise TargetMismatch(
|
|
388
|
+
"explicit catalog entries required for eager verification"
|
|
389
|
+
)
|
|
390
|
+
for entry in self.entries:
|
|
391
|
+
self._inventory(entry.artifact())
|
|
392
|
+
|
|
393
|
+
def read(
|
|
394
|
+
self,
|
|
395
|
+
entry: CatalogRead[P, R],
|
|
396
|
+
parameters: P,
|
|
397
|
+
*,
|
|
398
|
+
timeout: timedelta | None = None,
|
|
399
|
+
) -> list[R]:
|
|
400
|
+
artifact = entry.artifact()
|
|
401
|
+
if artifact["target"] != "spark-delta4":
|
|
402
|
+
raise NotCompiledForTarget("original Spark program required")
|
|
403
|
+
_runtime_obligations(artifact)
|
|
404
|
+
milliseconds = _milliseconds(timeout, self.configuration.default_timeout)
|
|
405
|
+
checked = entry.parameters.model_validate(
|
|
406
|
+
{n: getattr(parameters, n) for n in entry.parameters.model_fields},
|
|
407
|
+
strict=True,
|
|
408
|
+
)
|
|
409
|
+
parameter_values = _parameter_values(artifact, {
|
|
410
|
+
name: getattr(checked, name) for name in entry.parameters.model_fields
|
|
411
|
+
})
|
|
412
|
+
group = "umf-access-" + uuid4().hex
|
|
413
|
+
expired = Event()
|
|
414
|
+
context = self.session.sparkContext
|
|
415
|
+
previous = [
|
|
416
|
+
context.getLocalProperty(n)
|
|
417
|
+
for n in (
|
|
418
|
+
"spark.jobGroup.id",
|
|
419
|
+
"spark.job.description",
|
|
420
|
+
"spark.job.interruptOnCancel",
|
|
421
|
+
)
|
|
422
|
+
]
|
|
423
|
+
|
|
424
|
+
def expire() -> None:
|
|
425
|
+
expired.set()
|
|
426
|
+
context.cancelJobGroup(group)
|
|
427
|
+
|
|
428
|
+
timer = Timer(milliseconds / 1000, expire)
|
|
429
|
+
timer.daemon = True
|
|
430
|
+
context.setJobGroup(
|
|
431
|
+
group, "UMF precompiled snapshot read", interruptOnCancel=True
|
|
432
|
+
)
|
|
433
|
+
timer.start()
|
|
434
|
+
try:
|
|
435
|
+
self._profile()
|
|
436
|
+
bound = self._snapshots(artifact)
|
|
437
|
+
for ordinal, name in enumerate(artifact["parameterOrder"], 1):
|
|
438
|
+
bound["p" + str(ordinal)] = parameter_values[name]
|
|
439
|
+
for check in artifact["nativeChecks"]:
|
|
440
|
+
if expired.is_set():
|
|
441
|
+
raise TimedOut("Spark read deadline expired")
|
|
442
|
+
observed = self.session.sql(check["sql"]).collect()
|
|
443
|
+
if len(observed) != 1 or observed[0].asDict() != {
|
|
444
|
+
"violations": check["expected"]
|
|
445
|
+
}:
|
|
446
|
+
raise TargetMismatch("native complete Key integrity refused")
|
|
447
|
+
if expired.is_set():
|
|
448
|
+
raise TimedOut("Spark read deadline expired")
|
|
449
|
+
rows = self.session.sql(artifact["sql"], args=bound).collect()
|
|
450
|
+
if len(rows) > artifact["obligations"]["rowCap"]:
|
|
451
|
+
raise TargetMismatch("native row cap exceeded")
|
|
452
|
+
expected = [c["name"] for c in artifact["outputs"]]
|
|
453
|
+
result = []
|
|
454
|
+
for row in rows:
|
|
455
|
+
if row.__fields__ != expected:
|
|
456
|
+
raise TargetMismatch("native result descriptors differ")
|
|
457
|
+
data = row.asDict()
|
|
458
|
+
result.append(
|
|
459
|
+
entry.result.model_validate(
|
|
460
|
+
{
|
|
461
|
+
output["name"]: _native_projection(
|
|
462
|
+
output, data[output["name"]]
|
|
463
|
+
)
|
|
464
|
+
for output in artifact["outputs"]
|
|
465
|
+
},
|
|
466
|
+
strict=True,
|
|
467
|
+
)
|
|
468
|
+
)
|
|
469
|
+
self._snapshots(artifact)
|
|
470
|
+
if expired.is_set():
|
|
471
|
+
raise TimedOut("Spark read deadline expired")
|
|
472
|
+
return result
|
|
473
|
+
except Exception:
|
|
474
|
+
if expired.is_set():
|
|
475
|
+
raise TimedOut("Spark read deadline expired") from None
|
|
476
|
+
raise
|
|
477
|
+
finally:
|
|
478
|
+
timer.cancel()
|
|
479
|
+
for name, value in zip(
|
|
480
|
+
(
|
|
481
|
+
"spark.jobGroup.id",
|
|
482
|
+
"spark.job.description",
|
|
483
|
+
"spark.job.interruptOnCancel",
|
|
484
|
+
),
|
|
485
|
+
previous,
|
|
486
|
+
strict=True,
|
|
487
|
+
):
|
|
488
|
+
context.setLocalProperty(name, value)
|
|
489
|
+
|
|
490
|
+
def _page(
|
|
491
|
+
self,
|
|
492
|
+
entry: CatalogRead[P, R],
|
|
493
|
+
parameters: P,
|
|
494
|
+
*,
|
|
495
|
+
after: ReadContinuation | None,
|
|
496
|
+
timeout: timedelta | None,
|
|
497
|
+
snapshot_stream: bool,
|
|
498
|
+
page_size: int | None = None,
|
|
499
|
+
) -> ReadPage[R]:
|
|
500
|
+
artifact = entry.artifact()
|
|
501
|
+
if artifact["target"] != "spark-delta4" or not artifact.get("cursorOutputs"):
|
|
502
|
+
raise NotCompiledForTarget("original Spark keyset program required")
|
|
503
|
+
if snapshot_stream and not artifact["obligations"].get("snapshot"):
|
|
504
|
+
child = artifact.get("snapshotProgram")
|
|
505
|
+
if not isinstance(child, dict):
|
|
506
|
+
raise NotCompiledForTarget("original snapshot stream program absent")
|
|
507
|
+
artifact = child
|
|
508
|
+
if snapshot_stream and artifact["obligations"].get("snapshot") is not True:
|
|
509
|
+
raise NotCompiledForTarget("original snapshot stream program required")
|
|
510
|
+
_runtime_obligations(artifact)
|
|
511
|
+
effective_page_size = stream_page_size(artifact, page_size)
|
|
512
|
+
if after is not None and (
|
|
513
|
+
type(after) is not ReadContinuation or after.owner_cursor is not None
|
|
514
|
+
):
|
|
515
|
+
raise StaleContinuation("original raw Spark continuation required")
|
|
516
|
+
checked = entry.parameters.model_validate(
|
|
517
|
+
{name: getattr(parameters, name) for name in entry.parameters.model_fields},
|
|
518
|
+
strict=True,
|
|
519
|
+
)
|
|
520
|
+
values = {name: getattr(checked, name) for name in entry.parameters.model_fields}
|
|
521
|
+
native_values = _parameter_values(artifact, values)
|
|
522
|
+
milliseconds = _milliseconds(timeout, self.configuration.default_timeout)
|
|
523
|
+
group = "umf-access-" + uuid4().hex
|
|
524
|
+
expired = Event()
|
|
525
|
+
context = self.session.sparkContext
|
|
526
|
+
properties = (
|
|
527
|
+
"spark.jobGroup.id",
|
|
528
|
+
"spark.job.description",
|
|
529
|
+
"spark.job.interruptOnCancel",
|
|
530
|
+
)
|
|
531
|
+
previous = [context.getLocalProperty(name) for name in properties]
|
|
532
|
+
|
|
533
|
+
def expire() -> None:
|
|
534
|
+
expired.set()
|
|
535
|
+
context.cancelJobGroup(group)
|
|
536
|
+
|
|
537
|
+
def check_deadline() -> None:
|
|
538
|
+
if expired.is_set():
|
|
539
|
+
raise TimedOut("Spark page deadline expired")
|
|
540
|
+
|
|
541
|
+
timer = Timer(milliseconds / 1000, expire)
|
|
542
|
+
timer.daemon = True
|
|
543
|
+
context.setJobGroup(group, "UMF original keyset page", interruptOnCancel=True)
|
|
544
|
+
timer.start()
|
|
545
|
+
try:
|
|
546
|
+
self._profile()
|
|
547
|
+
vector = self._inventory(
|
|
548
|
+
artifact, continuation=after is not None, check_deadline=check_deadline
|
|
549
|
+
)
|
|
550
|
+
# Live continuations still bind every configured native UUID. Versions
|
|
551
|
+
# are included only for compiler-owned snapshot programs.
|
|
552
|
+
identities = [
|
|
553
|
+
(
|
|
554
|
+
item["native"],
|
|
555
|
+
next(
|
|
556
|
+
s.table_uuid
|
|
557
|
+
for s in self.configuration.snapshots
|
|
558
|
+
if s.table == item["native"]
|
|
559
|
+
),
|
|
560
|
+
)
|
|
561
|
+
for item in artifact["referencedTables"]
|
|
562
|
+
]
|
|
563
|
+
values = {
|
|
564
|
+
name: getattr(checked, name) for name in entry.parameters.model_fields
|
|
565
|
+
}
|
|
566
|
+
identity = hashlib.sha256(
|
|
567
|
+
json.dumps(
|
|
568
|
+
[
|
|
569
|
+
entry.artifact_json,
|
|
570
|
+
entry.context_json,
|
|
571
|
+
artifact["structuralDigest"],
|
|
572
|
+
self.configuration.schema,
|
|
573
|
+
self.configuration.binding_sha256,
|
|
574
|
+
[
|
|
575
|
+
(name, type(value).__name__, native_values[name]
|
|
576
|
+
if (artifact["obligations"].get("numericPredicateParameters") is not None
|
|
577
|
+
and type(value) in (int, Decimal))
|
|
578
|
+
or any(parameter["name"] == name for parameter in _list_descriptor(artifact)) else str(value))
|
|
579
|
+
for name, value in values.items()
|
|
580
|
+
],
|
|
581
|
+
identities,
|
|
582
|
+
vector,
|
|
583
|
+
],
|
|
584
|
+
separators=(",", ":"),
|
|
585
|
+
).encode()
|
|
586
|
+
).hexdigest()
|
|
587
|
+
fields = artifact["cursorOutputs"]
|
|
588
|
+
if after is not None and (
|
|
589
|
+
after.identity_digest != identity or after.snapshot_versions != vector
|
|
590
|
+
):
|
|
591
|
+
raise StaleContinuation(
|
|
592
|
+
"continuation program, parameters, native identity or version vector differs"
|
|
593
|
+
)
|
|
594
|
+
cursor_values = (
|
|
595
|
+
(None,) * len(fields)
|
|
596
|
+
if after is None
|
|
597
|
+
else _checked_sort_values(fields, after.values)
|
|
598
|
+
)
|
|
599
|
+
if after is not None:
|
|
600
|
+
try:
|
|
601
|
+
cursor_values = tuple(
|
|
602
|
+
_native_projection(field, value)
|
|
603
|
+
for field, value in zip(fields, cursor_values, strict=True)
|
|
604
|
+
)
|
|
605
|
+
except ValueRuleError as error:
|
|
606
|
+
raise StaleContinuation(
|
|
607
|
+
"continuation outside original Spark numeric shape"
|
|
608
|
+
) from error
|
|
609
|
+
if effective_page_size is not None:
|
|
610
|
+
values["__umf_page_size"] = effective_page_size
|
|
611
|
+
values["__umf_has_after"] = after is not None
|
|
612
|
+
values.update(
|
|
613
|
+
{
|
|
614
|
+
f"__umf_after_{index}": value
|
|
615
|
+
for index, value in enumerate(cursor_values)
|
|
616
|
+
}
|
|
617
|
+
)
|
|
618
|
+
# Reserved cursor values keep their separately admitted physical
|
|
619
|
+
# codec; only original user numeric parameters use text transport.
|
|
620
|
+
native_values.update({name: value for name, value in values.items() if name.startswith("__umf_")})
|
|
621
|
+
bound = {
|
|
622
|
+
"p" + str(ordinal): native_values[name]
|
|
623
|
+
for ordinal, name in enumerate(artifact["parameterOrder"], 1)
|
|
624
|
+
}
|
|
625
|
+
for check in artifact["nativeChecks"]:
|
|
626
|
+
if expired.is_set():
|
|
627
|
+
raise TimedOut("Spark read deadline expired")
|
|
628
|
+
observed = self.session.sql(check["sql"]).collect()
|
|
629
|
+
if len(observed) != 1 or observed[0].asDict() != {
|
|
630
|
+
"violations": check["expected"]
|
|
631
|
+
}:
|
|
632
|
+
raise ReadObligationUnmet("native complete Key integrity refused")
|
|
633
|
+
cap = (
|
|
634
|
+
effective_page_size
|
|
635
|
+
if effective_page_size is not None
|
|
636
|
+
else artifact["obligations"]["rowCap"]
|
|
637
|
+
)
|
|
638
|
+
if type(cap) is not int or not 1 <= cap <= 1000:
|
|
639
|
+
raise ReadObligationUnmet("bounded original page cap differs")
|
|
640
|
+
if expired.is_set():
|
|
641
|
+
raise TimedOut("Spark read deadline expired")
|
|
642
|
+
rows = self.session.sql(artifact["sql"], args=bound).collect()
|
|
643
|
+
if len(rows) > cap:
|
|
644
|
+
raise ReadObligationUnmet("bounded original page cap exceeded")
|
|
645
|
+
names = [item["name"] for item in artifact["outputs"]]
|
|
646
|
+
hidden = [item["name"] for item in fields]
|
|
647
|
+
result = []
|
|
648
|
+
last = None
|
|
649
|
+
for row in rows:
|
|
650
|
+
if row.__fields__ != names + hidden:
|
|
651
|
+
raise ReadObligationUnmet("native page result descriptors differ")
|
|
652
|
+
data = row.asDict()
|
|
653
|
+
result.append(
|
|
654
|
+
entry.result.model_validate(
|
|
655
|
+
{
|
|
656
|
+
output["name"]: _native_projection(
|
|
657
|
+
output, data[output["name"]]
|
|
658
|
+
)
|
|
659
|
+
for output in artifact["outputs"]
|
|
660
|
+
},
|
|
661
|
+
strict=True,
|
|
662
|
+
)
|
|
663
|
+
)
|
|
664
|
+
last = tuple(
|
|
665
|
+
_native_projection(field, value)
|
|
666
|
+
for field, value in zip(
|
|
667
|
+
fields,
|
|
668
|
+
_checked_sort_values(fields, [data[name] for name in hidden]),
|
|
669
|
+
strict=True,
|
|
670
|
+
)
|
|
671
|
+
)
|
|
672
|
+
self._inventory(
|
|
673
|
+
artifact, continuation=after is not None, check_deadline=check_deadline
|
|
674
|
+
)
|
|
675
|
+
if expired.is_set():
|
|
676
|
+
raise TimedOut("Spark page deadline expired")
|
|
677
|
+
continuation = (
|
|
678
|
+
ReadContinuation(last, identity, snapshot_versions=vector)
|
|
679
|
+
if len(rows) == cap and last is not None
|
|
680
|
+
else None
|
|
681
|
+
)
|
|
682
|
+
return ReadPage(tuple(result), continuation)
|
|
683
|
+
except Exception as error:
|
|
684
|
+
if expired.is_set():
|
|
685
|
+
raise TimedOut("Spark page deadline expired") from None
|
|
686
|
+
if artifact["obligations"].get(
|
|
687
|
+
"snapshot"
|
|
688
|
+
) is True and _expired_snapshot_error(error):
|
|
689
|
+
raise StaleContinuation(
|
|
690
|
+
"Original Delta snapshot files are no longer readable"
|
|
691
|
+
) from error
|
|
692
|
+
raise
|
|
693
|
+
finally:
|
|
694
|
+
timer.cancel()
|
|
695
|
+
for name, value in zip(properties, previous, strict=True):
|
|
696
|
+
context.setLocalProperty(name, value)
|
|
697
|
+
|
|
698
|
+
def page(
|
|
699
|
+
self,
|
|
700
|
+
entry: CatalogRead[P, R],
|
|
701
|
+
parameters: P,
|
|
702
|
+
*,
|
|
703
|
+
after: ReadContinuation | None = None,
|
|
704
|
+
timeout: timedelta | None = None,
|
|
705
|
+
) -> ReadPage[R]:
|
|
706
|
+
return self._page(
|
|
707
|
+
entry, parameters, after=after, timeout=timeout, snapshot_stream=False
|
|
708
|
+
)
|
|
709
|
+
|
|
710
|
+
def stream(
|
|
711
|
+
self,
|
|
712
|
+
entry: CatalogRead[P, R],
|
|
713
|
+
parameters: P,
|
|
714
|
+
*,
|
|
715
|
+
max_rows: int,
|
|
716
|
+
page_size: int | None = None,
|
|
717
|
+
timeout: timedelta | None = None,
|
|
718
|
+
) -> Generator[R, None, None]:
|
|
719
|
+
if type(max_rows) is not int or max_rows < 1:
|
|
720
|
+
raise ValueError("max_rows must be a positive integer")
|
|
721
|
+
_milliseconds(timeout, self.configuration.default_timeout)
|
|
722
|
+
stream_page_size(entry.artifact(), page_size)
|
|
723
|
+
return self._stream(
|
|
724
|
+
entry, parameters, max_rows=max_rows, page_size=page_size, timeout=timeout
|
|
725
|
+
)
|
|
726
|
+
|
|
727
|
+
def _stream(
|
|
728
|
+
self,
|
|
729
|
+
entry: CatalogRead[P, R],
|
|
730
|
+
parameters: P,
|
|
731
|
+
*,
|
|
732
|
+
max_rows: int,
|
|
733
|
+
page_size: int | None,
|
|
734
|
+
timeout: timedelta | None,
|
|
735
|
+
) -> Generator[R, None, None]:
|
|
736
|
+
emitted = 0
|
|
737
|
+
after = None
|
|
738
|
+
while emitted < max_rows:
|
|
739
|
+
page = self._page(
|
|
740
|
+
entry,
|
|
741
|
+
parameters,
|
|
742
|
+
after=after,
|
|
743
|
+
timeout=timeout,
|
|
744
|
+
snapshot_stream=True,
|
|
745
|
+
page_size=page_size,
|
|
746
|
+
)
|
|
747
|
+
if not page.items and page.next_after is not None:
|
|
748
|
+
raise ReadObligationUnmet("native stream made no continuation progress")
|
|
749
|
+
for item in page.items:
|
|
750
|
+
if emitted == max_rows:
|
|
751
|
+
raise StreamLimitReached(max_rows, truncated=True)
|
|
752
|
+
emitted += 1
|
|
753
|
+
yield item
|
|
754
|
+
if page.next_after is None:
|
|
755
|
+
return
|
|
756
|
+
if emitted == max_rows:
|
|
757
|
+
raise StreamLimitReached(max_rows, truncated=None)
|
|
758
|
+
after = page.next_after
|