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.
Files changed (117) hide show
  1. umf_access/__init__.py +109 -0
  2. umf_access/adoption.py +41 -0
  3. umf_access/build/__init__.py +2 -0
  4. umf_access/build/approximate.py +34 -0
  5. umf_access/build/catalog.py +1626 -0
  6. umf_access/build/commands.py +394 -0
  7. umf_access/build/pg_privileges.py +1544 -0
  8. umf_access/build/privileges.py +134 -0
  9. umf_access/build/search.py +365 -0
  10. umf_access/build/unity_search.py +104 -0
  11. umf_access/bulk.py +227 -0
  12. umf_access/canonical.py +23 -0
  13. umf_access/capture.py +410 -0
  14. umf_access/catalog.py +325 -0
  15. umf_access/codec_support.py +427 -0
  16. umf_access/commands.py +93 -0
  17. umf_access/delta_read.py +758 -0
  18. umf_access/dsl/__init__.py +148 -0
  19. umf_access/dsl/_context.py +36 -0
  20. umf_access/dsl/_expressions.py +625 -0
  21. umf_access/dsl/_joined.py +4 -0
  22. umf_access/dsl/_nodes.py +207 -0
  23. umf_access/dsl/_query.py +5559 -0
  24. umf_access/dsl/_selection.py +143 -0
  25. umf_access/dsl/navigation.py +302 -0
  26. umf_access/dsl/render.py +516 -0
  27. umf_access/dsl/search.py +343 -0
  28. umf_access/engine_catalog.py +563 -0
  29. umf_access/generated_core.py +5 -0
  30. umf_access/lifecycle/__init__.py +46 -0
  31. umf_access/lifecycle/_darwin_process_observer.c +306 -0
  32. umf_access/lifecycle/approval.py +366 -0
  33. umf_access/lifecycle/backfills.py +79 -0
  34. umf_access/lifecycle/catalog.py +289 -0
  35. umf_access/lifecycle/cli.py +231 -0
  36. umf_access/lifecycle/concurrent.py +196 -0
  37. umf_access/lifecycle/conversion_policy.py +188 -0
  38. umf_access/lifecycle/correspondence.py +203 -0
  39. umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
  40. umf_access/lifecycle/generation_authority_session.py +125 -0
  41. umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
  42. umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
  43. umf_access/lifecycle/generation_ingress.py +185 -0
  44. umf_access/lifecycle/generation_root_registry.py +138 -0
  45. umf_access/lifecycle/head.py +250 -0
  46. umf_access/lifecycle/head_view.py +81 -0
  47. umf_access/lifecycle/host.py +1183 -0
  48. umf_access/lifecycle/ingress_custody.py +750 -0
  49. umf_access/lifecycle/ingress_local_postgres.py +7990 -0
  50. umf_access/lifecycle/ingress_store.py +1488 -0
  51. umf_access/lifecycle/ledger.py +276 -0
  52. umf_access/lifecycle/ledger_schema.py +116 -0
  53. umf_access/lifecycle/mixed.py +593 -0
  54. umf_access/lifecycle/outcome_schema.py +136 -0
  55. umf_access/lifecycle/owner_approval_core.py +1810 -0
  56. umf_access/lifecycle/owner_authority.py +472 -0
  57. umf_access/lifecycle/owner_bootstrap.py +2077 -0
  58. umf_access/lifecycle/owner_wire.py +161 -0
  59. umf_access/lifecycle/phase_fence.py +52 -0
  60. umf_access/lifecycle/phase_policy.py +422 -0
  61. umf_access/lifecycle/privileges.py +145 -0
  62. umf_access/lifecycle/probe.py +39 -0
  63. umf_access/lifecycle/progress.py +497 -0
  64. umf_access/lifecycle/roles.py +96 -0
  65. umf_access/lifecycle/row_originals.py +1712 -0
  66. umf_access/lifecycle/row_originals_creation.py +759 -0
  67. umf_access/lifecycle/row_originals_receipt.py +413 -0
  68. umf_access/lifecycle/seeds.py +99 -0
  69. umf_access/lifecycle/sql_containment.py +358 -0
  70. umf_access/lifecycle/sql_containment_cli.py +33 -0
  71. umf_access/lifecycle/sql_containment_parser.py +20 -0
  72. umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
  73. umf_access/lifecycle/table_boundary.py +22 -0
  74. umf_access/lifecycle/target_custody_codec.py +788 -0
  75. umf_access/lifecycle/witness.py +72 -0
  76. umf_access/managed_actions.py +271 -0
  77. umf_access/managed_bulk.py +353 -0
  78. umf_access/managed_delta.py +150 -0
  79. umf_access/managed_support.py +166 -0
  80. umf_access/manifest_commands.py +278 -0
  81. umf_access/native_actions.py +1007 -0
  82. umf_access/native_program.py +570 -0
  83. umf_access/pages.py +125 -0
  84. umf_access/postgres_bulk.py +509 -0
  85. umf_access/postgres_read.py +1230 -0
  86. umf_access/postgres_search.py +639 -0
  87. umf_access/protocols.py +665 -0
  88. umf_access/py.typed +0 -0
  89. umf_access/related_keys.py +233 -0
  90. umf_access/reviewed.py +706 -0
  91. umf_access/search_catalog.py +122 -0
  92. umf_access/targets.py +312 -0
  93. umf_access/types.py +220 -0
  94. umf_access/unified/__init__.py +187 -0
  95. umf_access/unified/_binding.py +654 -0
  96. umf_access/unified/head_session.py +144 -0
  97. umf_access/unified/native_binding.py +143 -0
  98. umf_access/unified/operation_values.py +173 -0
  99. umf_access/unified/outcome_values.py +76 -0
  100. umf_access/unified/session_async.py +161 -0
  101. umf_access/unified/session_binding.py +108 -0
  102. umf_access/unified/session_policy.py +152 -0
  103. umf_access/unified/session_psycopg2.py +70 -0
  104. umf_access/unified/session_sqlalchemy.py +161 -0
  105. umf_access/unified/session_sync.py +148 -0
  106. umf_access/unified/table_reads.py +314 -0
  107. umf_access/unified/table_writes.py +193 -0
  108. umf_access/unity_search.py +312 -0
  109. umf_access/values.py +280 -0
  110. umf_access/verification.py +64 -0
  111. umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
  112. umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
  113. umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
  114. umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
  115. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
  116. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
  117. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
@@ -0,0 +1,312 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Bounded separate-index search over original Unity Catalog owner programs.
3
+
4
+ The host transport owns authenticated native operations and their closing
5
+ admission. This module never constructs SQL, refills dropped hits, or treats a
6
+ native denial as an absent row.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import math
13
+ import time
14
+ from collections.abc import Mapping
15
+ from dataclasses import dataclass
16
+ from datetime import timedelta
17
+ from decimal import Decimal
18
+ from typing import Any, Protocol
19
+
20
+ from .adoption import TargetIdentity
21
+ from .codec_support import checked_row, validate_graph
22
+ from .dsl import Score, Scored, SearchResult
23
+ from .native_program import program_json
24
+ from .search_catalog import SearchEntry, SearchVariant
25
+ from .targets import TargetMismatch
26
+ from .values import validate_vector
27
+
28
+
29
+ class UnitySearchError(ValueError):
30
+ pass
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class NativeHydration:
35
+ columns: tuple[str, ...]
36
+ rows: tuple[tuple[object, ...], ...]
37
+ table_id_before: str
38
+ table_id_after: str
39
+ principal_before: str
40
+ principal_after: str
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class NativeSearchVerification:
45
+ table_id_before: str
46
+ table_id_after: str
47
+ principal_before: str
48
+ principal_after: str
49
+
50
+
51
+ class UnitySearchTransport(Protocol):
52
+ """Owner-native ports, supplied explicitly; no default authority provider.
53
+
54
+ read_current must execute the exact supplied statement under current native
55
+ permissions, retaining the real table UUID and authenticated SQL principal
56
+ before and after it. Every operation shares the supplied absolute deadline.
57
+ """
58
+
59
+ def principal(self, *, deadline: float) -> str: ...
60
+ def platform(self, *, deadline: float) -> tuple[tuple[str, str], ...]: ...
61
+ def verify_current(self, table: Mapping[str, Any], *, deadline: float) -> NativeSearchVerification: ...
62
+ def index_metadata(self, name: str, *, deadline: float) -> Mapping[str, Any]: ...
63
+ def query_index(self, method: str, path: str, body: Mapping[str, object], *, deadline: float) -> Mapping[str, Any]: ...
64
+ def read_current(self, table: Mapping[str, Any], statement: str, parameters: Mapping[str, object], *, deadline: float) -> NativeHydration: ...
65
+
66
+
67
+ def _index_identity(metadata: Mapping[str, Any], expected: Mapping[str, Any]) -> tuple[object, ...]:
68
+ spec = metadata.get("direct_access_index_spec")
69
+ if (
70
+ metadata.get("name") != expected["name"]
71
+ or not isinstance(metadata.get("status"), dict)
72
+ or metadata["status"].get("ready") is not True
73
+ or metadata.get("endpoint_name") != expected["endpointName"]
74
+ or metadata.get("index_type") != "DIRECT_ACCESS"
75
+ or metadata.get("primary_key") != expected["primaryKey"]
76
+ or not isinstance(spec, dict)
77
+ or spec.get("embedding_vector_columns") != [{"name": expected["vectorColumn"], "embedding_dimension": expected["dimensions"]}]
78
+ ):
79
+ raise UnitySearchError("native vector index differs from compiled source")
80
+ schema = program_json(spec.get("schema_json", ""))
81
+ if not isinstance(schema, dict) or schema.get(expected["primaryKey"]) != "string" or schema.get(expected["vectorColumn"]) != "array<float>":
82
+ raise UnitySearchError("native vector index schema differs")
83
+ if "stringColumns" in expected and sorted(name for name, carrier in schema.items() if carrier == "string") != expected["stringColumns"]:
84
+ raise UnitySearchError("native HYBRID string inventory differs from authored keyword source")
85
+ return (metadata["name"], metadata["endpoint_name"], metadata["index_type"], metadata["primary_key"], json.dumps(spec, sort_keys=True), metadata.get("creation_timestamp"))
86
+
87
+
88
+ def _candidates(response: Mapping[str, Any], key_name: str, cap: int) -> tuple[tuple[str, Score | None], ...]:
89
+ manifest, result = response.get("manifest"), response.get("result")
90
+ if not isinstance(manifest, dict) or not isinstance(result, dict) or response.get("next_page_token") or result.get("next_page_token"):
91
+ raise UnitySearchError("complete bounded native candidate response required")
92
+ columns = manifest.get("columns")
93
+ if not isinstance(columns, list) or any(not isinstance(column, dict) or type(column.get("name")) is not str for column in columns):
94
+ raise UnitySearchError("native candidate column inventory required")
95
+ names = [column["name"] for column in columns]
96
+ if names not in ([key_name], [key_name, "score"]) or type(manifest.get("column_count")) is not int or manifest["column_count"] != len(names):
97
+ raise UnitySearchError("native candidate column inventory differs")
98
+ rows = result.get("data_array")
99
+ count = result.get("row_count")
100
+ if not isinstance(rows, list) or type(count) is not int or count != len(rows) or not 0 <= count <= cap:
101
+ raise UnitySearchError("native candidate row inventory exceeds original bound")
102
+ seen = set()
103
+ candidates = []
104
+ for row in rows:
105
+ if not isinstance(row, list) or len(row) != len(names) or type(row[0]) is not str or row[0] in seen:
106
+ raise UnitySearchError("native candidate complete Key differs or repeats")
107
+ seen.add(row[0])
108
+ score = None
109
+ if len(row) == 2 and row[1] is not None:
110
+ if type(row[1]) not in (int, float) or not math.isfinite(row[1]):
111
+ raise UnitySearchError("native score is not finite numeric")
112
+ score = Score(float(row[1]), "implementation-defined")
113
+ candidates.append((row[0], score))
114
+ return tuple(candidates)
115
+
116
+
117
+ def _native_value(output: Mapping[str, Any], value: object) -> object:
118
+ if value is None:
119
+ if output.get("nullable") is not True:
120
+ raise UnitySearchError("native projection returned forbidden NULL")
121
+ return value
122
+ carrier = output["carrier"]
123
+ if carrier == "integer" and type(value) is not int or carrier == "decimal" and type(value) is not Decimal:
124
+ raise UnitySearchError("native exact numeric projection carrier differs")
125
+ if carrier == "binary":
126
+ if type(value) not in (bytes, bytearray):
127
+ raise UnitySearchError("native binary projection carrier differs")
128
+ return bytes(value)
129
+ if carrier != "vector":
130
+ return value
131
+ if output.get("nativeType") != "array<float>" or type(value) not in (list, tuple):
132
+ raise UnitySearchError("native vector projection carrier differs")
133
+ return validate_vector(tuple(value), dimensions=output["dimensions"])
134
+
135
+
136
+ class UnityCatalogSearchTarget:
137
+ def __init__(self, transport: UnitySearchTransport, identity: TargetIdentity, *, embedders: Mapping[str, Any] | None = None, timeout: timedelta = timedelta(seconds=30), catalog_variants: tuple[SearchVariant, ...] = ()):
138
+ if identity.kind != "unity-catalog":
139
+ raise UnitySearchError("explicit Unity Catalog target identity required")
140
+ self.transport, self._identity = transport, identity
141
+ self.embedders, self.timeout = dict(embedders or {}), timeout
142
+ self.catalog_variants = tuple(catalog_variants)
143
+ self._seconds(timeout)
144
+
145
+ @staticmethod
146
+ def _seconds(timeout: timedelta, *, call: bool = False) -> float:
147
+ if type(timeout) is not timedelta:
148
+ raise ValueError("finite search timedelta required")
149
+ seconds = timeout.total_seconds()
150
+ if call and seconds == 0:
151
+ raise TimeoutError("Unity Catalog search deadline already expired")
152
+ if not math.isfinite(seconds) or not 0 < seconds <= 120:
153
+ raise ValueError("finite search timeout within 120 seconds required")
154
+ return seconds
155
+
156
+ def _platform(self, deadline: float) -> None:
157
+ observed = self.transport.platform(deadline=deadline)
158
+ if (
159
+ type(observed) is not tuple or not observed
160
+ or any(type(item) is not tuple or len(item) != 2
161
+ or any(type(value) is not str or not value for value in item) for item in observed)
162
+ or len(dict(observed)) != len(observed)
163
+ or not self._identity.platform
164
+ or not {"databricks-sql", "databricks-runtime"}.intersection(dict(self._identity.platform))
165
+ or len(dict(self._identity.platform)) != len(self._identity.platform)
166
+ or any(dict(observed).get(name) != version for name, version in self._identity.platform)
167
+ ):
168
+ raise UnitySearchError("native platform differs from qualified target versions")
169
+ if time.monotonic() >= deadline:
170
+ raise TimeoutError("native target verification exceeded whole-call deadline")
171
+
172
+ def identity(self) -> TargetIdentity:
173
+ try:
174
+ self._platform(time.monotonic() + self._seconds(self.timeout))
175
+ except UnitySearchError as error:
176
+ raise TargetMismatch(str(error)) from error
177
+ return self._identity
178
+
179
+ def _verify_table(self, obligations: Mapping[str, Any], principal: str, deadline: float) -> None:
180
+ native = self.transport.verify_current(obligations["currentTable"], deadline=deadline)
181
+ if (
182
+ not isinstance(native, NativeSearchVerification)
183
+ or native.table_id_before != obligations["currentTableId"]
184
+ or native.table_id_after != native.table_id_before
185
+ or native.principal_before != principal or native.principal_after != principal
186
+ ):
187
+ raise UnitySearchError("native table verification differs from original target")
188
+
189
+ def verify(self) -> None:
190
+ try:
191
+ self._verify_owned()
192
+ except UnitySearchError as error:
193
+ raise TargetMismatch(str(error)) from error
194
+
195
+ def _verify_owned(self) -> None:
196
+ if not self.catalog_variants:
197
+ raise UnitySearchError("explicit catalog search variants required for eager verification")
198
+ deadline = time.monotonic() + self._seconds(self.timeout)
199
+ self._platform(deadline)
200
+ for variant in self.catalog_variants:
201
+ if not variant.pin.matches(self._identity) or len(variant.entries) != 1:
202
+ raise UnitySearchError("one original native search program for this target required")
203
+ program = variant.entries[0].artifact()
204
+ if program.get("version") != "weft.unity-search/0.1":
205
+ raise UnitySearchError("foreign search owner program")
206
+ obligations = program["obligations"]
207
+ principal = self.transport.principal(deadline=deadline)
208
+ if type(principal) is not str or not principal:
209
+ raise UnitySearchError("native authenticated principal required")
210
+ expected = obligations["nativeIndex"]
211
+ before = _index_identity(self.transport.index_metadata(expected["name"], deadline=deadline), expected)
212
+ self._verify_table(obligations, principal, deadline)
213
+ if (
214
+ _index_identity(self.transport.index_metadata(expected["name"], deadline=deadline), expected) != before
215
+ or self.transport.principal(deadline=deadline) != principal
216
+ ):
217
+ raise UnitySearchError("native target verification changed before release")
218
+ self._platform(deadline)
219
+
220
+ def search(self, variant: SearchVariant, parameters: Mapping[str, object], *, timeout: timedelta | None = None) -> SearchResult[Any]:
221
+ seconds = self._seconds(self.timeout if timeout is None else timeout, call=True)
222
+ deadline = time.monotonic() + seconds
223
+ self._platform(deadline)
224
+
225
+ def check() -> None:
226
+ if time.monotonic() >= deadline:
227
+ raise TimeoutError("Unity Catalog search exceeded its whole-call deadline")
228
+
229
+ if not variant.pin.matches(self._identity) or len(variant.entries) != 1:
230
+ raise UnitySearchError("one original native search program for this target required")
231
+ entry: SearchEntry = variant.entries[0]
232
+ program = entry.artifact()
233
+ if program["version"] != "weft.unity-search/0.1":
234
+ raise UnitySearchError("foreign search owner program")
235
+ obligations = program["obligations"]
236
+ if any(obligations.get(name) is not value for name, value in (("allowPartial", True), ("preserveNativeOrdinal", True), ("refill", False), ("nativeAdmissionEachOperation", True), ("principalRequired", True))) or obligations.get("metric") != "l2" or obligations.get("scoreKind") != "implementation-defined" or obligations.get("atMostKReads") != variant.top_k:
237
+ raise UnitySearchError("unsupported search admission or hydration obligation")
238
+ principal = self.transport.principal(deadline=deadline)
239
+ if type(principal) is not str or not principal:
240
+ raise UnitySearchError("native authenticated principal required")
241
+ expected_index = obligations["nativeIndex"]
242
+ before = _index_identity(self.transport.index_metadata(expected_index["name"], deadline=deadline), expected_index)
243
+ self._verify_table(obligations, principal, deadline)
244
+ values = dict(parameters)
245
+ for destination, source in entry.parameter_aliases:
246
+ if destination in values or source not in values:
247
+ raise UnitySearchError("original search parameter alias differs")
248
+ values[destination] = values[source]
249
+ query = values[entry.query_argument]
250
+ vector = program["index"]["vector"]
251
+ if entry.embed:
252
+ embedder = self.embedders.get(program["index"]["id"])
253
+ if embedder is None or embedder.identity() != {"model": vector["model"]["id"], "version": vector["model"]["version"], "dimensions": vector["dimensions"]} or type(query) is not str:
254
+ raise UnitySearchError("embedder identity or query carrier differs")
255
+ check()
256
+ embedded = embedder.embed([query])
257
+ if not isinstance(embedded, list) or len(embedded) != 1:
258
+ raise UnitySearchError("embedder output inventory differs")
259
+ query = embedded[0]
260
+ query = validate_vector(query, dimensions=vector["dimensions"])
261
+ values[program["request"]["queryParameter"]] = query
262
+ body = dict(program["query"]["body"])
263
+ for parameter in program["query"]["parameters"]:
264
+ source = parameter["source"]
265
+ if set(source) != {"parameter"} or parameter["destination"] in body:
266
+ raise UnitySearchError("unknown original native query parameter")
267
+ value = values[source["parameter"]]
268
+ if parameter["carrier"] == "vector":
269
+ value = list(validate_vector(value, dimensions=vector["dimensions"]))
270
+ elif parameter["carrier"] != "string" or type(value) is not str:
271
+ raise UnitySearchError("native search query carrier differs")
272
+ body[parameter["destination"]] = value
273
+ check()
274
+ candidates = _candidates(self.transport.query_index(program["query"]["method"], program["query"]["path"], body, deadline=deadline), expected_index["primaryKey"], variant.top_k)
275
+ hydration = program["hydration"]
276
+ outputs, hidden = hydration["outputs"], hydration["hiddenKey"]
277
+ if len(hidden) != 1 or len(entry.key_model.UMF_FIELDS) != 1:
278
+ raise UnitySearchError("single complete string Key profile required")
279
+ names = tuple(output["name"] for output in outputs + hidden)
280
+ items, stale = [], 0
281
+ for rank, (key, score) in enumerate(candidates, 1):
282
+ check()
283
+ entry.key_model.model_validate({entry.key_model.UMF_FIELDS[0][2]: key}, strict=True)
284
+ bindings = {}
285
+ for parameter in hydration["statement"]["parameters"]:
286
+ source = parameter["source"]
287
+ if source == {"candidateKey": 0}:
288
+ value = key
289
+ elif set(source) == {"parameter"}:
290
+ value = values[source["parameter"]]
291
+ else:
292
+ raise UnitySearchError("unknown original hydration parameter")
293
+ bindings[parameter["name"]] = value
294
+ native = self.transport.read_current(obligations["currentTable"], hydration["statement"]["sql"], bindings, deadline=deadline)
295
+ if native.table_id_before != obligations["currentTableId"] or native.table_id_after != native.table_id_before or native.principal_before != principal or native.principal_after != principal or native.columns != names or len(native.rows) > 1:
296
+ raise UnitySearchError("native hydration source, principal or complete Key differs")
297
+ if not native.rows:
298
+ stale += 1
299
+ continue
300
+ row = checked_row(names, native.columns, native.rows[0])
301
+ if row[hidden[0]["name"]] != key:
302
+ raise UnitySearchError("native hydration returned a different complete Key")
303
+ decoded = validate_graph(entry.result, {output["name"]: _native_value(output, row[output["name"]]) for output in outputs})
304
+ item = tuple(getattr(decoded, name) for name in entry.tuple_fields) if entry.tuple_fields else decoded
305
+ items.append(Scored(item, rank, score))
306
+ check()
307
+ self._verify_table(obligations, principal, deadline)
308
+ if _index_identity(self.transport.index_metadata(expected_index["name"], deadline=deadline), expected_index) != before or self.transport.principal(deadline=deadline) != principal:
309
+ raise UnitySearchError("native search identity changed before release")
310
+ check()
311
+ self._platform(deadline)
312
+ return SearchResult(tuple(items), stale, True, True)
umf_access/values.py ADDED
@@ -0,0 +1,280 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Strict Python carriers and explicit, resolved constraint helpers.
3
+
4
+ No native transport is guessed here. temporal_token implements only the selected
5
+ CONTRACT-075 oracle serialization, not a backend or permissive token parser.
6
+ """
7
+
8
+ from datetime import UTC, date, datetime, timezone
9
+ from decimal import Decimal
10
+ from math import isfinite
11
+ from struct import pack, unpack
12
+ from typing import Literal, TypeVar, cast
13
+
14
+ from .types import ValueRuleError, Vector
15
+
16
+ T = TypeVar("T")
17
+ N = TypeVar("N", int, Decimal)
18
+
19
+
20
+ def validate_boolean(value: object) -> bool:
21
+ if type(value) is not bool:
22
+ raise ValueRuleError("boolean carrier required")
23
+ return value
24
+
25
+
26
+ def validate_integer(
27
+ value: object, *, bits: int | None = None, signed: bool = True
28
+ ) -> int:
29
+ if type(value) is not int:
30
+ raise ValueRuleError("integer carrier required; boolean excluded")
31
+ if (
32
+ type(signed) is not bool
33
+ or bits is not None
34
+ and (type(bits) is not int or bits < 1)
35
+ ):
36
+ raise ValueRuleError("invalid authored integer width")
37
+ if bits is not None:
38
+ magnitude = abs(value)
39
+ width = magnitude.bit_length()
40
+ fits = (
41
+ (
42
+ width < bits
43
+ or value < 0
44
+ and width == bits
45
+ and magnitude & (magnitude - 1) == 0
46
+ )
47
+ if signed
48
+ else value >= 0 and width <= bits
49
+ )
50
+ if not fits:
51
+ raise ValueRuleError("integer outside authored width")
52
+ return value
53
+
54
+
55
+ def validate_decimal(
56
+ value: object, *, precision: int | None = None, scale: int | None = None
57
+ ) -> Decimal:
58
+ if not isinstance(value, Decimal) or not value.is_finite():
59
+ raise ValueRuleError("finite Decimal carrier required")
60
+ if (
61
+ (precision is not None and (type(precision) is not int or precision < 1))
62
+ or (scale is not None and (type(scale) is not int or scale < 0))
63
+ or (precision is not None and scale is not None and scale > precision)
64
+ ):
65
+ raise ValueRuleError("invalid authored decimal precision or scale")
66
+ _, digits, exponent = value.as_tuple()
67
+ # is_finite above makes the exponent an int. Never expand huge exponents.
68
+ assert isinstance(exponent, int)
69
+ if not any(digits):
70
+ return value
71
+ if scale is not None:
72
+ shift = exponent + scale
73
+ length = len(digits) + shift
74
+ if shift < 0:
75
+ cut = -shift
76
+ if cut > len(digits) or any(digits[len(digits) - cut :]):
77
+ raise ValueRuleError("decimal requires rounding at authored scale")
78
+ if precision is not None and length > precision:
79
+ raise ValueRuleError("decimal outside authored precision")
80
+ elif precision is not None:
81
+ # No target scale is invented. Count significant coefficient digits.
82
+ if len(digits) > precision:
83
+ raise ValueRuleError("decimal outside authored precision")
84
+ return value
85
+
86
+
87
+ def validate_string(value: object) -> str:
88
+ if not isinstance(value, str):
89
+ raise ValueRuleError("string carrier required")
90
+ if any(0xD800 <= ord(char) <= 0xDFFF for char in value):
91
+ raise ValueRuleError("string contains unpaired surrogate")
92
+ return value
93
+
94
+
95
+ def validate_binary(value: object) -> bytes:
96
+ if type(value) is not bytes:
97
+ raise ValueRuleError("bytes carrier required")
98
+ return value
99
+
100
+
101
+ def validate_date(value: object) -> date:
102
+ if type(value) is not date:
103
+ raise ValueRuleError("date carrier required; datetime excluded")
104
+ return value
105
+
106
+
107
+ def validate_instant(value: object) -> datetime:
108
+ if (
109
+ type(value) is not datetime
110
+ or type(value.tzinfo) is not timezone
111
+ or value.fold != 0
112
+ ):
113
+ raise ValueRuleError("instant requires fixed-offset datetime with default fold")
114
+ try:
115
+ value.astimezone(UTC)
116
+ except (OverflowError, ValueError):
117
+ raise ValueRuleError(
118
+ "instant UTC normalization outside supported years"
119
+ ) from None
120
+ return value
121
+
122
+
123
+ def validate_local(value: object) -> datetime:
124
+ if type(value) is not datetime or value.tzinfo is not None or value.fold != 0:
125
+ raise ValueRuleError("local requires naive datetime with default fold")
126
+ return value
127
+
128
+
129
+ def temporal_token(kind: Literal["date", "instant", "local"], value: object) -> str:
130
+ """Serialize an admitted carrier canonically for umf-access-temporal/0.1.0."""
131
+ if kind == "date":
132
+ day = validate_date(value)
133
+ return f"{day.year:04d}-{day.month:02d}-{day.day:02d}"
134
+ if kind == "instant":
135
+ instant = validate_instant(value)
136
+ try:
137
+ stamp = instant.astimezone(UTC)
138
+ except (OverflowError, ValueError):
139
+ raise ValueRuleError(
140
+ "instant UTC normalization outside supported years"
141
+ ) from None
142
+ elif kind == "local":
143
+ stamp = validate_local(value)
144
+ else:
145
+ raise ValueRuleError("unsupported temporal kind")
146
+ return (
147
+ f"{stamp.year:04d}-{stamp.month:02d}-{stamp.day:02d}T"
148
+ f"{stamp.hour:02d}:{stamp.minute:02d}:{stamp.second:02d}."
149
+ f"{stamp.microsecond:06d}" + ("Z" if kind == "instant" else "")
150
+ )
151
+
152
+
153
+ def validate_length(
154
+ value: T, *, minimum: int | None = None, maximum: int | None = None
155
+ ) -> T:
156
+ """Length for resolved string/bytes/array/map constraints; no coercion."""
157
+ if type(value) not in (str, bytes, tuple, list, dict):
158
+ raise ValueRuleError("length requires a supported carrier")
159
+ size = len(
160
+ cast(
161
+ str | bytes | tuple[object, ...] | list[object] | dict[object, object],
162
+ value,
163
+ )
164
+ )
165
+ if (minimum is not None and size < minimum) or (
166
+ maximum is not None and size > maximum
167
+ ):
168
+ raise ValueRuleError("length outside authored bounds")
169
+ return value
170
+
171
+
172
+ def validate_range(
173
+ value: N,
174
+ *,
175
+ minimum: N | None = None,
176
+ maximum: N | None = None,
177
+ min_inclusive: bool = True,
178
+ max_inclusive: bool = True,
179
+ ) -> N:
180
+ if type(value) not in (int, Decimal):
181
+ raise ValueRuleError("range requires an exact numeric carrier")
182
+ if isinstance(value, Decimal):
183
+ validate_decimal(value)
184
+ for bound in (minimum, maximum):
185
+ if bound is not None and type(bound) is not type(value):
186
+ raise ValueRuleError("range bound carrier mismatch")
187
+ if isinstance(bound, Decimal):
188
+ validate_decimal(bound)
189
+ if (
190
+ minimum is not None
191
+ and (value < minimum or value == minimum and not min_inclusive)
192
+ or maximum is not None
193
+ and (value > maximum or value == maximum and not max_inclusive)
194
+ ):
195
+ raise ValueRuleError("value outside authored range")
196
+ return value
197
+
198
+
199
+ def validate_allowed(value: T, allowed: tuple[T, ...]) -> T:
200
+ if not any(
201
+ type(candidate) is type(value) and candidate == value for candidate in allowed
202
+ ):
203
+ raise ValueRuleError("value outside authored allowed values")
204
+ return value
205
+
206
+
207
+ def validate_vector(value: object, *, dimensions: int) -> Vector:
208
+ if type(dimensions) is not int or dimensions < 1 or type(value) is not tuple:
209
+ raise ValueRuleError("vector dimension or carrier mismatch")
210
+ items = value
211
+ if len(items) != dimensions:
212
+ raise ValueRuleError("vector dimension or carrier mismatch")
213
+ for item in items:
214
+ if type(item) is not float or not isfinite(item):
215
+ raise ValueRuleError("vector requires finite float32 values")
216
+ try:
217
+ exact = unpack("!f", pack("!f", item))[0]
218
+ except OverflowError:
219
+ raise ValueRuleError("vector value outside float32") from None
220
+ if exact != item:
221
+ raise ValueRuleError("vector value requires float32 rounding")
222
+ return cast(Vector, value)
223
+
224
+
225
+ # Generated packages carry instances of this metadata-driven callable, not
226
+ # private copies of validation algorithms.
227
+ from dataclasses import dataclass
228
+ from typing import Any
229
+
230
+ from pydantic import TypeAdapter
231
+
232
+
233
+ @dataclass(frozen=True)
234
+ class FieldValidator:
235
+ kind: str
236
+ dimensions: int | None = None
237
+ bits: int | None = None
238
+ signed: bool = True
239
+ precision: int | None = None
240
+ scale: int | None = None
241
+ adapter: TypeAdapter[Any] | None = None
242
+ minimum: int | None = None
243
+ maximum: int | None = None
244
+ range_min: int | Decimal | None = None
245
+ range_max: int | Decimal | None = None
246
+ min_inclusive: bool = True
247
+ max_inclusive: bool = True
248
+ allowed: tuple[object, ...] | None = None
249
+
250
+ def __call__(self, value: object) -> object:
251
+ if self.adapter is not None:
252
+ checked = self.adapter.validate_python(value, strict=True)
253
+ elif self.kind == "vector":
254
+ if self.dimensions is None:
255
+ raise ValueRuleError("vector dimension metadata required")
256
+ checked = validate_vector(value, dimensions=self.dimensions)
257
+ elif self.kind == "float32":
258
+ checked = validate_float32(value)
259
+ elif self.kind == "integer":
260
+ checked = validate_integer(value, bits=self.bits, signed=self.signed)
261
+ elif self.kind == "decimal":
262
+ checked = validate_decimal(value, precision=self.precision, scale=self.scale)
263
+ else:
264
+ validators = {"boolean": validate_boolean, "binary": validate_binary,
265
+ "string": validate_string, "date": validate_date,
266
+ "instant": validate_instant, "local": validate_local}
267
+ validator = validators.get(self.kind)
268
+ if validator is None:
269
+ raise ValueRuleError("unsupported generated carrier metadata")
270
+ checked = validator(value)
271
+ if self.minimum is not None or self.maximum is not None:
272
+ checked = validate_length(checked, minimum=self.minimum, maximum=self.maximum)
273
+ if self.range_min is not None or self.range_max is not None:
274
+ checked = validate_range(checked, minimum=self.range_min, maximum=self.range_max,
275
+ min_inclusive=self.min_inclusive, max_inclusive=self.max_inclusive)
276
+ if self.allowed is not None:
277
+ checked = validate_allowed(checked, self.allowed)
278
+ return checked
279
+ def validate_float32(value: object) -> float:
280
+ return validate_vector((value,), dimensions=1)[0]
@@ -0,0 +1,64 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Bounded process cache for already validated native shape fingerprints.
3
+
4
+ Callers must observe the complete native fingerprint afresh under the owned
5
+ read interval. This stores no role, grant, action or transaction authority.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ import threading
12
+ import time
13
+ from collections import OrderedDict
14
+ from datetime import timedelta
15
+
16
+
17
+ class PostgresVerificationCache:
18
+ def __init__(self, *, max_entries: int = 256, lifetime: timedelta | None = None):
19
+ if type(max_entries) is not int or not 1 <= max_entries <= 4096:
20
+ raise ValueError("bounded verification cache size required")
21
+ if lifetime is not None and (
22
+ type(lifetime) is not timedelta or not math.isfinite(lifetime.total_seconds())
23
+ or lifetime.total_seconds() <= 0
24
+ ):
25
+ raise ValueError("positive finite cache lifetime required")
26
+ self.max_entries = max_entries
27
+ self.lifetime = None if lifetime is None else lifetime.total_seconds()
28
+ self._entries: OrderedDict[str, tuple[str, float]] = OrderedDict()
29
+ self._lock = threading.Lock()
30
+
31
+ def matches(self, key: str, fingerprint: str) -> bool:
32
+ with self._lock:
33
+ previous = self._entries.pop(key, None)
34
+ if previous is None:
35
+ return False
36
+ saved, created = previous
37
+ if saved != fingerprint or self.lifetime is not None and time.monotonic() - created >= self.lifetime:
38
+ return False
39
+ self._entries[key] = previous
40
+ return True
41
+
42
+ def remember(self, key: str, fingerprint: str) -> None:
43
+ with self._lock:
44
+ self._entries.pop(key, None)
45
+ self._entries[key] = (fingerprint, time.monotonic())
46
+ while len(self._entries) > self.max_entries:
47
+ self._entries.popitem(last=False)
48
+
49
+ def clear(self) -> None:
50
+ with self._lock:
51
+ self._entries.clear()
52
+
53
+
54
+ _process_cache = PostgresVerificationCache()
55
+
56
+
57
+ def configure_postgres_verification_cache(*, max_entries: int = 256, lifetime: timedelta | None = None) -> None:
58
+ """Configure and clear process-local shape reuse; native proofs stay required."""
59
+ global _process_cache
60
+ _process_cache = PostgresVerificationCache(max_entries=max_entries, lifetime=lifetime)
61
+
62
+
63
+ def postgres_verification_cache() -> PostgresVerificationCache:
64
+ return _process_cache
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: umf_access
3
+ Version: 0.1.0.dev8
4
+ Summary: Local prerelease typed access runtime; target qualification pending
5
+ License-Expression: MIT OR Apache-2.0
6
+ License-File: LICENSE-APACHE
7
+ License-File: LICENSE-MIT
8
+ License-File: LICENSE.md
9
+ Requires-Python: <3.15,>=3.11
10
+ Requires-Dist: pydantic<3,>=2.13
11
+ Requires-Dist: typing-extensions<5,>=4.16
12
+ Provides-Extra: owner-authority
13
+ Requires-Dist: cryptography==50.0.2; extra == 'owner-authority'
14
+ Provides-Extra: sql-containment
15
+ Requires-Dist: pglast==7.20; extra == 'sql-containment'