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,654 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Host binding for the generated UMF access transport.
3
+
4
+ This module is deliberately an adapter boundary: generated clients send inert
5
+ UMF requests, Weft compiles admitted reads, and the caller executes the returned
6
+ compiler artifact. It never opens a connection or interprets action effects.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import hashlib
13
+ import hmac
14
+ import json
15
+ import re
16
+ import secrets
17
+ from collections.abc import Mapping
18
+ from decimal import Decimal, InvalidOperation
19
+
20
+ from ..dsl import (
21
+ FieldRef,
22
+ Node,
23
+ Ordering,
24
+ RecordRef,
25
+ Related,
26
+ render_logical,
27
+ render_related_logical,
28
+ )
29
+ from ..generated_core import CURRENT_CORE_VERSION
30
+
31
+
32
+ class UnifiedAccessError(RuntimeError):
33
+ """Stable, instance-data-free error returned to a generated client."""
34
+
35
+ def __init__(self, code: str, message: str, *, field: str | None = None) -> None:
36
+ self.code = code
37
+ self.field = field
38
+ super().__init__(message)
39
+
40
+ def as_response(self, schema: str) -> dict[str, object]:
41
+ error: dict[str, object] = {"code": self.code, "message": str(self)}
42
+ if self.field is not None:
43
+ error["field"] = self.field
44
+ return {"schema": schema, "error": error}
45
+
46
+
47
+ _WEFT_SCALAR_CARRIERS = frozenset({"string", "boolean", "integer", "decimal", "uuid", "bits128", "binary", "date", "timestamp"})
48
+
49
+
50
+ def _weft_scalar_availability(field: Mapping[str, object], *, purpose: str) -> tuple[str, bool]:
51
+ """Admit only the scalar shape and availability this original Weft profile can represent."""
52
+ scalar = field.get("scalarType")
53
+ cardinality = field.get("cardinality")
54
+ nullability = field.get("nullability")
55
+ extensions = field.get("extensions", {})
56
+ presentation_only = (type(extensions) is dict
57
+ and set(extensions) <= {"hohfeld.view"}
58
+ and ("hohfeld.view" not in extensions
59
+ or type(extensions["hohfeld.view"]) is dict))
60
+ if (type(scalar) is not str or scalar not in _WEFT_SCALAR_CARRIERS
61
+ or cardinality != "one" or nullability not in ("required", "absent-allowed")
62
+ or not presentation_only):
63
+ raise UnifiedAccessError("UNSUPPORTED", f"{purpose} requires an admitted scalar carrier, cardinality one, explicit nullability, and only retained presentation annotations")
64
+ return scalar, nullability == "absent-allowed"
65
+
66
+
67
+ def _canonical(value: object) -> str:
68
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
69
+
70
+
71
+ class _Variant:
72
+ def __init__(self, node: Node) -> None:
73
+ self.node = node
74
+
75
+
76
+ def _source_index(model: Mapping[str, object]) -> tuple[dict[tuple[str, str], dict[str, object]], dict[tuple[str, str], dict[str, object]]]:
77
+ records: dict[tuple[str, str], dict[str, object]] = {}
78
+ fields: dict[tuple[str, str], dict[str, object]] = {}
79
+ modules = model.get("modules")
80
+ if type(modules) is not list:
81
+ raise ValueError("WEFT_SOURCE_INVALID: model modules are required")
82
+ for module in modules:
83
+ if not isinstance(module, Mapping) or type(module.get("id")) is not str:
84
+ continue
85
+ mid = str(module["id"])
86
+ for element in module.get("elements", ()) if type(module.get("elements", ())) is list else ():
87
+ if not isinstance(element, Mapping) or type(element.get("id")) is not str:
88
+ continue
89
+ key = (mid, str(element["id"]))
90
+ if element.get("kind") == "record":
91
+ records[key] = dict(element) | {"_namespace": module.get("namespace", mid)}
92
+ elif element.get("kind") == "field":
93
+ fields[key] = dict(element)
94
+ return records, fields
95
+
96
+
97
+ def _wire_value(value: object, scalar: str) -> object:
98
+ """Decode only the documented exact wire carriers; never coerce by guess."""
99
+ if value is None:
100
+ return None
101
+ if scalar == "integer":
102
+ if not isinstance(value, Mapping) or set(value) != {"integerToken"} or type(value["integerToken"]) is not str:
103
+ raise UnifiedAccessError("INVALID", "integer requires integerToken")
104
+ token = value["integerToken"]
105
+ if re.fullmatch(r"-?(?:0|[1-9][0-9]*)", token) is None:
106
+ raise UnifiedAccessError("INVALID", "invalid integer token")
107
+ try:
108
+ return int(token)
109
+ except ValueError:
110
+ raise UnifiedAccessError("INVALID", "integer token exceeds host capacity") from None
111
+ if scalar == "decimal":
112
+ if not isinstance(value, Mapping) or set(value) != {"decimalToken"} or type(value["decimalToken"]) is not str:
113
+ raise UnifiedAccessError("INVALID", "decimal requires decimalToken")
114
+ if re.fullmatch(r"-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", value["decimalToken"]) is None:
115
+ raise UnifiedAccessError("INVALID", "invalid decimal token")
116
+ try:
117
+ parsed = Decimal(value["decimalToken"])
118
+ except InvalidOperation:
119
+ raise UnifiedAccessError("INVALID", "invalid decimal token") from None
120
+ if not parsed.is_finite():
121
+ raise UnifiedAccessError("INVALID", "decimal must be finite")
122
+ return parsed
123
+ if scalar == "uuid":
124
+ if not isinstance(value, Mapping) or set(value) != {"uuid"} or type(value["uuid"]) is not str:
125
+ raise UnifiedAccessError("INVALID", "UUID requires uuid text")
126
+ import uuid
127
+ try:
128
+ parsed = uuid.UUID(value["uuid"])
129
+ except ValueError:
130
+ raise UnifiedAccessError("INVALID", "invalid UUID text") from None
131
+ if str(parsed) != value["uuid"]:
132
+ raise UnifiedAccessError("INVALID", "UUID text must be canonical")
133
+ return parsed
134
+ if scalar == "bits128":
135
+ if not isinstance(value, Mapping) or set(value) != {"bits128Hex"} or type(value["bits128Hex"]) is not str:
136
+ raise UnifiedAccessError("INVALID", "128-bit value requires bits128Hex")
137
+ try:
138
+ token = value["bits128Hex"]
139
+ if len(token) != 32 or any(c not in "0123456789abcdef" for c in token):
140
+ raise ValueError
141
+ decoded = bytes.fromhex(token)
142
+ if len(decoded) != 16:
143
+ raise ValueError
144
+ return decoded
145
+ except ValueError:
146
+ raise UnifiedAccessError("INVALID", "invalid 128-bit hex") from None
147
+ if scalar == "binary":
148
+ if not isinstance(value, Mapping) or set(value) != {"binaryHex"} or type(value["binaryHex"]) is not str:
149
+ raise UnifiedAccessError("INVALID", "binary requires binaryHex")
150
+ try:
151
+ token = value["binaryHex"]
152
+ if len(token) % 2 or any(c not in "0123456789abcdefABCDEF" for c in token):
153
+ raise ValueError
154
+ return bytes.fromhex(token)
155
+ except ValueError:
156
+ raise UnifiedAccessError("INVALID", "invalid binary hex") from None
157
+ if scalar == "timestamp":
158
+ if not isinstance(value, Mapping) or set(value) != {"timestamp"} or type(value["timestamp"]) is not str:
159
+ raise UnifiedAccessError("INVALID", "timestamp requires exact timestamp text")
160
+ return value["timestamp"]
161
+ if scalar == "date":
162
+ if not isinstance(value, Mapping) or set(value) != {"date"} or type(value["date"]) is not str:
163
+ raise UnifiedAccessError("INVALID", "date requires exact date text")
164
+ return value["date"]
165
+ if scalar == "string" and type(value) is str or scalar == "boolean" and type(value) is bool:
166
+ return value
167
+ raise UnifiedAccessError("INVALID", "value does not match the declared scalar carrier")
168
+
169
+
170
+ def _digest_source(binding: Mapping[str, object]) -> tuple[str, dict[str, object]]:
171
+ raw = binding.get("modelJson")
172
+ expected = binding.get("modelSha256")
173
+ if type(raw) is not str or type(expected) is not str:
174
+ raise ValueError("WEFT_SOURCE_INVALID: original modelJson and modelSha256 are required")
175
+ actual = hashlib.sha256(raw.encode("utf-8")).hexdigest()
176
+ if actual != expected:
177
+ raise ValueError("WEFT_SOURCE_INVALID: model digest differs from original source")
178
+ try:
179
+ model = json.loads(raw)
180
+ except (ValueError, TypeError):
181
+ raise ValueError("WEFT_SOURCE_INVALID: original model JSON is invalid") from None
182
+ if type(model) is not dict or model.get("umf") != CURRENT_CORE_VERSION:
183
+ raise ValueError("WEFT_SOURCE_INVALID: current UMF source is required")
184
+ return actual, model
185
+
186
+
187
+ class _TableBinding:
188
+ """Shared pure compilation, wire validation and cursor implementation."""
189
+
190
+ def __init__(
191
+ self,
192
+ binding: Mapping[str, object],
193
+ compiler: object,
194
+ *,
195
+ target: str,
196
+ page_size: int = 100,
197
+ cursor_secret: bytes | None = None,
198
+ ) -> None:
199
+ if type(page_size) is not int or not 1 <= page_size <= 100:
200
+ raise ValueError("page size must be 1..100")
201
+ if not isinstance(binding, Mapping):
202
+ raise TypeError("original Weft binding mapping required")
203
+ self.binding = dict(binding)
204
+ self.schema, self.model = _digest_source(self.binding)
205
+ self.records, self.fields = _source_index(self.model)
206
+ if binding.get("version") != "umf.raw-read-binding/0.1":
207
+ raise ValueError("WEFT_SOURCE_INVALID: unsupported original binding version")
208
+ self.compiler = compiler
209
+ self.page_size = page_size
210
+ if target not in ("postgresql18", "lakebase18"):
211
+ raise ValueError("target must be an admitted Weft PostgreSQL 18 profile")
212
+ self.target = target
213
+ if cursor_secret is not None and (type(cursor_secret) is not bytes or len(cursor_secret) < 32):
214
+ raise ValueError("cursor secret must contain at least 256 bits")
215
+ self._cursor_secret = cursor_secret or secrets.token_bytes(32)
216
+
217
+ def _record(self, name: object) -> tuple[RecordRef, dict[str, object], dict[str, FieldRef], dict[str, object]]:
218
+ if type(name) is not str:
219
+ raise UnifiedAccessError("INVALID", "record identity must be module.Record")
220
+ matches = [(module_id, record_id, raw) for (module_id, record_id), raw in self.records.items()
221
+ if name == module_id + "." + record_id]
222
+ if len(matches) != 1:
223
+ raise UnifiedAccessError("INVALID", "record is absent from bound source")
224
+ module_id, record_id, raw = matches[0]
225
+ namespace = raw.get("_namespace")
226
+ if type(namespace) is not str:
227
+ raise UnifiedAccessError("UNSUPPORTED", "record has no logical namespace")
228
+ members = raw.get("members")
229
+ keys = raw.get("keys")
230
+ if type(members) is not list or type(keys) is not list:
231
+ raise UnifiedAccessError("UNSUPPORTED", "record members and keys are required")
232
+ primary = [key for key in keys if isinstance(key, Mapping) and key.get("primary") is True]
233
+ if len(primary) == 1:
234
+ selected_key = primary[0]
235
+ elif len(keys) == 1 and isinstance(keys[0], Mapping):
236
+ selected_key = keys[0]
237
+ else:
238
+ raise UnifiedAccessError("UNSUPPORTED", "record requires one unambiguous declared key")
239
+ if type(selected_key.get("fields")) is not list:
240
+ raise UnifiedAccessError("UNSUPPORTED", "record key fields are malformed")
241
+ table = next((t for t in self.binding.get("tables", ()) if isinstance(t, Mapping) and t.get("logical") == [namespace, record_id]), None)
242
+ if not isinstance(table, Mapping) or type(table.get("columns")) is not list:
243
+ raise UnifiedAccessError("UNSUPPORTED", "record has no original Weft table binding")
244
+ columns = {c.get("logical"): c for c in table["columns"] if isinstance(c, Mapping) and type(c.get("logical")) is str}
245
+ mapped: dict[str, FieldRef] = {}
246
+ source_fields: dict[str, object] = {}
247
+ for member in members:
248
+ if not isinstance(member, Mapping):
249
+ raise UnifiedAccessError("UNSUPPORTED", "record member reference is malformed")
250
+ fid = (member.get("module"), member.get("element"))
251
+ field = self.fields.get((str(fid[0]), str(fid[1])))
252
+ if field is None:
253
+ raise UnifiedAccessError("UNSUPPORTED", "record member field is absent")
254
+ logical_name = field.get("name", field.get("id"))
255
+ if type(logical_name) is not str or logical_name not in columns:
256
+ raise UnifiedAccessError("UNSUPPORTED", "field identity has no exact logical column mapping")
257
+ scalar, nullable = _weft_scalar_availability(field, purpose="field")
258
+ column = columns[logical_name]
259
+ if (column.get("carrier") != scalar
260
+ or column.get("nullable") is not nullable):
261
+ raise UnifiedAccessError("UNSUPPORTED", "logical column carrier differs from the exact source field")
262
+ mapped[str(fid[1])] = FieldRef(module_id, record_id, str(fid[1]), logical_name=logical_name)
263
+ source_fields[str(fid[1])] = field
264
+ key_fields: list[FieldRef] = []
265
+ for ref in selected_key["fields"]:
266
+ if not isinstance(ref, Mapping) or ref.get("module") != module_id or ref.get("element") not in mapped:
267
+ raise UnifiedAccessError("UNSUPPORTED", "primary key field mapping is incomplete")
268
+ key_fields.append(mapped[str(ref["element"])])
269
+ rec = RecordRef(module_id, record_id, tuple(key_fields), namespace, str(raw.get("name", record_id)), key_id=str(selected_key.get("id", "key")))
270
+ return rec, raw, mapped, {"table": table, "fields": source_fields, "columns": columns}
271
+
272
+ def _predicate(self, item: object, fields: Mapping[str, FieldRef], source_fields: Mapping[str, object], params: list[dict[str, object]], values: dict[str, object]) -> Node:
273
+ if not isinstance(item, Mapping) or type(item.get("op")) is not str:
274
+ raise UnifiedAccessError("INVALID", "filter expression is malformed")
275
+ op = str(item["op"])
276
+ if op in ("and", "or"):
277
+ args = item.get("args")
278
+ if type(args) is not list or not args:
279
+ raise UnifiedAccessError("INVALID", "boolean filter requires arguments")
280
+ return Node(op, tuple(self._predicate(arg, fields, source_fields, params, values) for arg in args))
281
+ if op == "not":
282
+ args = item.get("args")
283
+ if type(args) is not list or len(args) != 1:
284
+ raise UnifiedAccessError("INVALID", "not filter requires exactly one argument")
285
+ return Node("not", (self._predicate(args[0], fields, source_fields, params, values),))
286
+ field_id = item.get("field")
287
+ if type(field_id) is not str or field_id not in fields:
288
+ raise UnifiedAccessError("INVALID", "filter field is absent from this record", field=str(field_id) if field_id is not None else None)
289
+ ref = fields[field_id]
290
+ field = source_fields[field_id]
291
+ sql_ops = {"eq": "=", "ne": "<>", "lt": "<", "le": "<=", "gt": ">", "ge": ">=", "starts_with": "STARTS_WITH", "is_null": "IS NULL"}
292
+ if op == "is_null":
293
+ return Node("IS NULL", (Node("column", (ref,)),))
294
+ if op not in sql_ops:
295
+ raise UnifiedAccessError("UNSUPPORTED", "filter operator is outside the current subset", field=field_id)
296
+ pname = f"p{len(params)}"
297
+ scalar = field.get("scalarType")
298
+ value = _wire_value(item.get("value"), str(scalar))
299
+ if value is None:
300
+ raise UnifiedAccessError("INVALID", "null comparison requires the explicit is_null operator", field=field_id)
301
+ if op == "starts_with" and scalar != "string":
302
+ raise UnifiedAccessError("UNSUPPORTED", "starts_with requires a string field", field=field_id)
303
+ params.append({"name": pname, "carrier": scalar, "nullable": value is None})
304
+ values[pname] = value
305
+ return Node(sql_ops[op], (Node("column", (ref,)), Node("param", (pname,))))
306
+
307
+ def _compile_request(self, query: Mapping[str, object], size: int) -> tuple[dict[str, object], dict[str, object]]:
308
+ rec, _raw, refs, info = self._record(query.get("record"))
309
+ params: list[dict[str, object]] = []
310
+ values: dict[str, object] = {}
311
+ steps: list[Node] = []
312
+ filters = query.get("filters", [])
313
+ if type(filters) is not list:
314
+ raise UnifiedAccessError("INVALID", "filters must be a list")
315
+ predicates = [self._predicate(x, refs, info["fields"], params, values) for x in filters]
316
+ key = query.get("key")
317
+ if key is not None:
318
+ if not isinstance(key, Mapping) or set(key) != {field.field for field in rec.key}:
319
+ raise UnifiedAccessError("INVALID", "key must contain exactly the declared primary-key fields")
320
+ for field_ref in rec.key:
321
+ pname = f"p{len(params)}"
322
+ source_field = info["fields"][field_ref.field]
323
+ carrier = source_field.get("scalarType")
324
+ value = _wire_value(key[field_ref.field], str(carrier))
325
+ params.append({"name": pname, "carrier": carrier, "nullable": False})
326
+ values[pname] = value
327
+ predicates.append(Node("=", (Node("column", (field_ref,)), Node("param", (pname,)))))
328
+ order_items = query.get("order", [])
329
+ if type(order_items) is not list:
330
+ raise UnifiedAccessError("INVALID", "order must be a list")
331
+ order: list[Ordering[object]] = []
332
+ for item in order_items:
333
+ if not isinstance(item, Mapping) or item.get("field") not in refs or item.get("direction") not in ("asc", "desc"):
334
+ raise UnifiedAccessError("INVALID", "ordering must name a source field and direction")
335
+ order_field = info["fields"][str(item["field"])]
336
+ if order_field.get("nullability") != "required":
337
+ raise UnifiedAccessError("UNSUPPORTED", "nullable ordering is outside the stable cursor subset", field=str(item["field"]))
338
+ if any(existing.field == refs[str(item["field"])].field for existing in order):
339
+ raise UnifiedAccessError("INVALID", "ordering fields must be unique")
340
+ order.append(Ordering(refs[str(item["field"])], str(item["direction"]).upper()))
341
+ if not order:
342
+ order = [Ordering(ref, "ASC") for ref in rec.key]
343
+ ordered = [item.field for item in order]
344
+ for key_field in rec.key:
345
+ if key_field not in ordered:
346
+ order.append(Ordering(key_field, "ASC"))
347
+ ordered.append(key_field)
348
+ steps.append(Node("order", tuple(order)))
349
+ # A cursor carries the exact final ordering tuple, including key
350
+ # tie-breakers. Render the lexicographic predicate as inert DSL nodes.
351
+ position = query.get("_after_position")
352
+ if position is not None:
353
+ if not isinstance(position, Mapping):
354
+ raise UnifiedAccessError("INVALID_CURSOR", "cursor ordering position is malformed")
355
+ disjuncts: list[Node] = []
356
+ equal_prefix: list[Node] = []
357
+ for ordering in order:
358
+ ref = ordering.field
359
+ if not isinstance(ref, FieldRef) or ref.field not in position:
360
+ raise UnifiedAccessError("INVALID_CURSOR", "cursor lacks an ordering value")
361
+ source_field = info["fields"][ref.field]
362
+ pname = f"p{len(params)}"
363
+ wire_value = position[ref.field]
364
+ value = _wire_value(wire_value, str(source_field.get("scalarType")))
365
+ nullable = source_field.get("nullability") != "required"
366
+ if value is None and not nullable:
367
+ raise UnifiedAccessError("INVALID_CURSOR", "cursor nulls a required ordering field")
368
+ if value is None:
369
+ equal_prefix.append(Node("IS NULL", (Node("column", (ref,)),)))
370
+ continue
371
+ params.append({"name": pname, "carrier": source_field.get("scalarType"), "nullable": False})
372
+ values[pname] = value
373
+ greater = ">" if ordering.direction == "ASC" else "<"
374
+ term = Node(greater, (Node("column", (ref,)), Node("param", (pname,))))
375
+ if nullable:
376
+ term = Node("or", (term, Node("IS NULL", (Node("column", (ref,)),))))
377
+ disjuncts.append(Node("and", (*equal_prefix, term)) if equal_prefix else term)
378
+ equal_prefix.append(Node("=", (Node("column", (ref,)), Node("param", (pname,)))))
379
+ predicates.append(Node("or", tuple(disjuncts)))
380
+ if predicates:
381
+ steps.append(Node("filter", tuple(predicates)))
382
+ steps.extend((Node("select", tuple(refs.values())), Node("limit", (size,))))
383
+ related = query.get("relationship")
384
+ related_sql = None
385
+ relationship = None
386
+ if related is not None:
387
+ if not isinstance(related, Mapping) or related.get("direction") not in ("forward", "inverse") or type(related.get("id")) is not str or type(related.get("module")) is not str:
388
+ raise UnifiedAccessError("INVALID", "relationship identity is malformed")
389
+ rel_decl = next((r for m in self.model.get("modules", ()) if isinstance(m, Mapping) and m.get("id") == related["module"] for r in (m.get("relationships", ()) if type(m.get("relationships", ())) is list else ()) if isinstance(r, Mapping) and r.get("id") == related["id"]), None)
390
+ if rel_decl is None:
391
+ raise UnifiedAccessError("INVALID", "relationship is absent from bound source")
392
+ source_query = query.get("source")
393
+ if not isinstance(source_query, Mapping):
394
+ raise UnifiedAccessError("INVALID", "relationship traversal requires its original source query")
395
+ source_rec, _source_raw, source_refs, source_info = self._record(source_query.get("record"))
396
+ source_end = rel_decl.get("source")
397
+ target_end = rel_decl.get("target")
398
+ if (type(source_end) is not list or len(source_end) != 1 or not isinstance(source_end[0], Mapping)
399
+ or type(target_end) is not list or len(target_end) != 1 or not isinstance(target_end[0], Mapping)):
400
+ raise UnifiedAccessError("UNSUPPORTED", "only singular declared relationship endpoints are supported")
401
+ forward = related["direction"] == "forward"
402
+ expected_source, expected_target = (source_end[0], target_end[0]) if forward else (target_end[0], source_end[0])
403
+ if ((expected_source.get("module"), expected_source.get("element")) != (source_rec.module, source_rec.element)
404
+ or (expected_target.get("module"), expected_target.get("element")) != (rec.module, rec.element)):
405
+ raise UnifiedAccessError("INVALID", "relationship endpoints differ from the selected records")
406
+ if not any(isinstance(r, Mapping) and r.get("id") == related["id"] and r.get("toOne") is True
407
+ for r in self.binding.get("relationships", ())):
408
+ raise UnifiedAccessError("UNSUPPORTED", "original Weft binding has no admitted to-one relationship")
409
+ rel_field = FieldRef(str(related["module"]), source_rec.element, str(related["id"]), field_module=str(related["module"]), logical_name=str(rel_decl.get("name", related["id"])))
410
+ source_filters = source_query.get("filters", [])
411
+ if type(source_filters) is not list:
412
+ raise UnifiedAccessError("INVALID", "relationship source filters must be a list")
413
+ source_predicates = [self._predicate(x, source_refs, source_info["fields"], params, values) for x in source_filters]
414
+ source_key = source_query.get("key")
415
+ if source_key is not None:
416
+ if not isinstance(source_key, Mapping) or set(source_key) != {field.field for field in source_rec.key}:
417
+ raise UnifiedAccessError("INVALID", "relationship source key differs from its declared Key")
418
+ for key_field in source_rec.key:
419
+ pname = f"p{len(params)}"
420
+ key_type = source_info["fields"][key_field.field].get("scalarType")
421
+ key_value = _wire_value(source_key[key_field.field], str(key_type))
422
+ params.append({"name": pname, "carrier": key_type, "nullable": False})
423
+ values[pname] = key_value
424
+ source_predicates.append(Node("=", (Node("column", (key_field,)), Node("param", (pname,)))))
425
+ source_steps = (Node("filter", tuple(source_predicates)),) if source_predicates else ()
426
+ rel_node = Node("related", (source_rec, source_steps, Related(rel_field, direction=str(related["direction"])), str(related["direction"])))
427
+ variant = _Variant(Node("all", (rec, (rel_node, *steps))))
428
+ logical = render_related_logical(variant, binding=self.binding)
429
+ if logical is None:
430
+ raise UnifiedAccessError("UNSUPPORTED", "relationship did not produce an original related query")
431
+ sql = logical.target_sql
432
+ related_sql = logical.source_sql
433
+ relationship = dict(logical.relationship)
434
+ else:
435
+ sql = render_logical(_Variant(Node("all", (rec, tuple(steps)))), binding=self.binding)
436
+ req: dict[str, object] = {"version": "weft.raw-read/0.1", "target": self.target,
437
+ "sql": sql, "binding": self.binding, "parameters": params,
438
+ "rowCap": size, "keyset": False}
439
+ # Source-exact checking is meaningful only when the original binding
440
+ # carries the native ColumnSet documents that establish those facts.
441
+ # Do not invent them from logical/native table mappings.
442
+ native_columns = self.binding.get("nativeColumns")
443
+ native_sets = native_columns.get("sets") if isinstance(native_columns, Mapping) else None
444
+ if (self.target in ("postgresql18", "lakebase18")
445
+ and type(native_sets) is list and len(native_sets) == len(self.binding.get("tables", ()))
446
+ and bool(native_sets)):
447
+ req["verificationProfile"] = "source-exact/0.1"
448
+ if related_sql is not None:
449
+ src = dict(req)
450
+ src["sql"] = related_sql
451
+ # Weft's related-read contract requires the same original
452
+ # parameter inventory on both endpoint queries. Each SQL statement
453
+ # uses only its own markers; the shared inventory retains custody.
454
+ return ({"version": "weft.related-read/0.1", "source": src, "target": req,
455
+ "relationship": relationship or {}}, values)
456
+ return req, values
457
+
458
+ def _check_request(self, request: Mapping[str, object]) -> str:
459
+ if request.get("contract") != "umf.access/1":
460
+ raise UnifiedAccessError("INVALID", "unsupported access contract")
461
+ if request.get("schema") != self.schema:
462
+ raise UnifiedAccessError("SCHEMA_MISMATCH", "client and host schemas differ")
463
+ kind = request.get("kind")
464
+ if kind not in ("read", "apply"):
465
+ raise UnifiedAccessError("INVALID", "unsupported request kind")
466
+ return str(kind)
467
+
468
+ def _prepare_read(self, request: Mapping[str, object]) -> tuple[Mapping[str, object], dict[str, object], Mapping[str, object], int, dict[str, object]]:
469
+ query = request.get("query")
470
+ if not isinstance(query, Mapping):
471
+ raise UnifiedAccessError("INVALID", "read query object required")
472
+ freshness = request.get("at_least")
473
+ size = request.get("size")
474
+ if type(size) is not int or not 1 <= size <= self.page_size:
475
+ raise UnifiedAccessError("INVALID", "page size exceeds host limit")
476
+ cursor_scope: dict[str, object] = {"query": dict(query), "size": size, "at_least": freshness, "target": self.target}
477
+ page_query = dict(query)
478
+ after = request.get("after")
479
+ if after is not None:
480
+ if type(after) is not str:
481
+ raise UnifiedAccessError("INVALID_CURSOR", "cursor must be text")
482
+ page_query["_after_position"] = self.decode_cursor(after, cursor_scope)
483
+ try:
484
+ compiler_request, parameter_values = self._compile_request(page_query, size + 1)
485
+ except UnifiedAccessError:
486
+ raise
487
+ except Exception: # noqa: BLE001 -- sanitize failures from the logical compiler boundary
488
+ raise UnifiedAccessError("UNSUPPORTED", "read query is outside the current logical compiler subset") from None
489
+ compiler_name = "compile_related_read_json" if compiler_request.get("version") == "weft.related-read/0.1" else "compile_raw_read_json"
490
+ method = getattr(self.compiler, compiler_name, None)
491
+ if not callable(method):
492
+ raise UnifiedAccessError("UNSUPPORTED", "installed Weft compiler lacks the required read entry point")
493
+ try:
494
+ raw = method(_canonical(compiler_request))
495
+ except Exception: # noqa: BLE001 -- native compiler bindings may raise arbitrary exceptions
496
+ raise UnifiedAccessError("UNSUPPORTED", "Weft read compilation failed") from None
497
+ if isinstance(raw, str):
498
+ try:
499
+ artifact = json.loads(raw)
500
+ except ValueError:
501
+ raise UnifiedAccessError("UNSUPPORTED", "Weft returned an invalid artifact") from None
502
+ else:
503
+ artifact = raw
504
+ if not isinstance(artifact, Mapping) or artifact.get("status") != "compiled":
505
+ raise UnifiedAccessError("UNSUPPORTED", "Weft refused the requested read")
506
+ target_request = compiler_request.get("target") if compiler_request.get("version") == "weft.related-read/0.1" else compiler_request
507
+ if not isinstance(target_request, Mapping):
508
+ raise UnifiedAccessError("UNSUPPORTED", "Weft target request is malformed")
509
+ if (artifact.get("target") != self.target or artifact.get("binding") != self.binding
510
+ or artifact.get("sourceSql") != target_request.get("sql")):
511
+ raise UnifiedAccessError("UNSUPPORTED", "compiled artifact differs from the original request")
512
+ if compiler_request.get("version") == "weft.related-read/0.1" and artifact.get("relatedRequest") != compiler_request:
513
+ raise UnifiedAccessError("UNSUPPORTED", "compiled related source differs from the original request")
514
+ host_request = dict(request)
515
+ host_request["parameters"] = parameter_values
516
+ return artifact, host_request, query, size, cursor_scope
517
+
518
+ def _finish_read(self, response: Mapping[str, object], query: Mapping[str, object], size: int, cursor_scope: Mapping[str, object]) -> Mapping[str, object]:
519
+ if not isinstance(response, Mapping):
520
+ raise UnifiedAccessError("BUSY", "host executor returned an invalid response")
521
+ if response.get("schema") != self.schema:
522
+ raise UnifiedAccessError("SCHEMA_MISMATCH", "executor response schema differs")
523
+ rows = response.get("rows")
524
+ if type(rows) is not list or len(rows) > size + 1:
525
+ raise UnifiedAccessError("INVALID", "executor returned an invalid row page")
526
+ _rec, _record_decl, expected_fields, row_info = self._record(query.get("record"))
527
+ for row in rows:
528
+ if not isinstance(row, Mapping) or set(row) - set(expected_fields):
529
+ raise UnifiedAccessError("INVALID", "executor row field identities differ from the generated Record")
530
+ for field_id, field in row_info["fields"].items():
531
+ if field.get("nullability") == "required" and field_id not in row:
532
+ raise UnifiedAccessError("INVALID", "executor omitted a required field")
533
+ if field_id in row:
534
+ if field.get("nullability") == "required" and row[field_id] is None:
535
+ raise UnifiedAccessError("INVALID", "executor returned null for a required field")
536
+ _wire_value(row[field_id], str(field.get("scalarType")))
537
+ result = dict(response)
538
+ if len(rows) == size + 1:
539
+ visible = rows[:size]
540
+ last = visible[-1]
541
+ if not isinstance(last, Mapping):
542
+ raise UnifiedAccessError("INVALID", "rows must preserve field identities")
543
+ rec, _raw, _refs, _info = self._record(query.get("record"))
544
+ order_items = query.get("order", [])
545
+ order_ids = [str(x["field"]) for x in order_items if isinstance(x, Mapping)] if type(order_items) is list else []
546
+ for key_field in rec.key:
547
+ if key_field.field not in order_ids:
548
+ order_ids.append(key_field.field)
549
+ if any(field_id not in last for field_id in order_ids):
550
+ raise UnifiedAccessError("INVALID", "last row omits an ordering or key field")
551
+ result["rows"] = visible
552
+ result["cursor"] = self.encode_cursor(cursor_scope, {field_id: last[field_id] for field_id in order_ids})
553
+ else:
554
+ result["cursor"] = None
555
+ return result
556
+
557
+ def _prepare_action(self, request: Mapping[str, object]) -> tuple[str, dict[str, object], str | None]:
558
+ action = request.get("action")
559
+ inputs = request.get("inputs")
560
+ key = request.get("idempotency_key")
561
+ if type(action) is not str or not action or not isinstance(inputs, Mapping):
562
+ raise UnifiedAccessError("INVALID", "action identity and input object required")
563
+ matches: list[Mapping[str, object]] = []
564
+ modules = self.model.get("modules", ())
565
+ for module in modules if type(modules) is list else ():
566
+ if not isinstance(module, Mapping) or type(module.get("id")) is not str:
567
+ continue
568
+ extensions = module.get("extensions")
569
+ action_ext = extensions.get("umf.actions") if isinstance(extensions, Mapping) else None
570
+ declarations = action_ext.get("actions") if isinstance(action_ext, Mapping) else None
571
+ for candidate in declarations if type(declarations) is list else ():
572
+ if (isinstance(candidate, Mapping) and type(candidate.get("id")) is str
573
+ and f"{module['id']}.{candidate['id']}" == action):
574
+ matches.append(candidate)
575
+ if len(matches) != 1:
576
+ raise UnifiedAccessError("INVALID", "action is absent from bound source")
577
+ declaration = matches[0]
578
+ parameters = declaration.get("parameters")
579
+ if type(parameters) is not list:
580
+ raise UnifiedAccessError("UNSUPPORTED", "action parameter declarations are malformed")
581
+ parameter_by_id = {p.get("id"): p for p in parameters if isinstance(p, Mapping) and type(p.get("id")) is str}
582
+ parameter_ids = set(parameter_by_id)
583
+ required = {p.get("id") for p in parameters if isinstance(p, Mapping) and p.get("required") is True}
584
+ if set(inputs) - parameter_ids or required - set(inputs):
585
+ raise UnifiedAccessError("INVALID", "action inputs differ from declared parameters")
586
+ typed_inputs: dict[str, object] = {}
587
+ for parameter_id, parameter_value in inputs.items():
588
+ parameter = parameter_by_id[parameter_id]
589
+ if parameter.get("kind") == "entity":
590
+ target = parameter.get("target")
591
+ if not isinstance(target, Mapping) or type(target.get("module")) is not str or type(target.get("element")) is not str:
592
+ raise UnifiedAccessError("UNSUPPORTED", "action entity target is malformed")
593
+ target_rec, _target_decl, _refs, target_info = self._record(f"{target['module']}.{target['element']}")
594
+ if target.get("key") != target_rec.key_id:
595
+ raise UnifiedAccessError("UNSUPPORTED", "action entity key is outside the primary-key subset")
596
+ if not isinstance(parameter_value, Mapping) or set(parameter_value) != {f.field for f in target_rec.key}:
597
+ raise UnifiedAccessError("INVALID", "action entity input must contain exactly its declared key")
598
+ key_value: dict[str, object] = {}
599
+ for field_ref in target_rec.key:
600
+ field = target_info["fields"][field_ref.field]
601
+ key_value[field_ref.field] = _wire_value(parameter_value[field_ref.field], str(field.get("scalarType")))
602
+ typed_inputs[parameter_id] = key_value
603
+ elif parameter.get("kind") == "value":
604
+ field_ref = parameter.get("field")
605
+ if (not isinstance(field_ref, Mapping) or type(field_ref.get("module")) is not str
606
+ or type(field_ref.get("element")) is not str):
607
+ raise UnifiedAccessError("UNSUPPORTED", "action value parameter has no source field reference")
608
+ field = self.fields.get((field_ref["module"], field_ref["element"]))
609
+ if field is None:
610
+ raise UnifiedAccessError("UNSUPPORTED", "action value field is absent from bound source")
611
+ scalar, nullable = _weft_scalar_availability(field, purpose="action value field")
612
+ if parameter_value is None and not nullable:
613
+ raise UnifiedAccessError("INVALID", "required action value cannot be null")
614
+ typed_inputs[parameter_id] = _wire_value(parameter_value, scalar)
615
+ else:
616
+ raise UnifiedAccessError("UNSUPPORTED", "action parameter shape is outside the current typed subset")
617
+ if key is not None and (type(key) is not str or not key):
618
+ raise UnifiedAccessError("INVALID", "invalid idempotency key")
619
+ return action, typed_inputs, key
620
+
621
+ def _finish_action(self, response: Mapping[str, object]) -> Mapping[str, object]:
622
+ if not isinstance(response, Mapping):
623
+ raise UnifiedAccessError("INVALID", "action executor returned an invalid response")
624
+ if response.get("schema") != self.schema:
625
+ raise UnifiedAccessError("SCHEMA_MISMATCH", "action response schema differs")
626
+ return dict(response)
627
+
628
+ def encode_cursor(self, query: Mapping[str, object], position: Mapping[str, object]) -> str:
629
+ """Create an authenticated schema/query-bound cursor from ordered field values."""
630
+ if not isinstance(position, Mapping) or not position:
631
+ raise ValueError("cursor position must contain ordering values")
632
+ payload = {"schema": self.schema, "query": hashlib.sha256(_canonical(query).encode()).hexdigest(), "position": dict(position)}
633
+ body = _canonical(payload).encode()
634
+ payload["signature"] = hmac.new(self._cursor_secret, body, hashlib.sha256).hexdigest()
635
+ return base64.urlsafe_b64encode(_canonical(payload).encode()).decode().rstrip("=")
636
+
637
+ def decode_cursor(self, token: str, query: Mapping[str, object]) -> Mapping[str, object]:
638
+ """Reject malformed, foreign-schema, and differently-scoped cursors."""
639
+ try:
640
+ raw = base64.urlsafe_b64decode(token + "=" * (-len(token) % 4))
641
+ payload = json.loads(raw)
642
+ except (ValueError, TypeError):
643
+ raise UnifiedAccessError("INVALID_CURSOR", "cursor is invalid") from None
644
+ expected = hashlib.sha256(_canonical(query).encode()).hexdigest()
645
+ signature = payload.get("signature") if isinstance(payload, dict) else None
646
+ unsigned = {k: v for k, v in payload.items() if k != "signature"} if isinstance(payload, dict) else {}
647
+ valid_signature = type(signature) is str and hmac.compare_digest(
648
+ signature, hmac.new(self._cursor_secret, _canonical(unsigned).encode(), hashlib.sha256).hexdigest())
649
+ if (not isinstance(payload, dict) or not valid_signature or payload.get("schema") != self.schema
650
+ or payload.get("query") != expected or not isinstance(payload.get("position"), dict)):
651
+ raise UnifiedAccessError("INVALID_CURSOR", "cursor belongs to another schema or query")
652
+ return payload["position"]
653
+
654
+