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,134 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Review-only target privilege inventory, never SQL parsing or grant execution."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Any
7
+
8
+ from .pg_privileges import postgres_runtime_advisory
9
+
10
+ _RUNTIME = {
11
+ "postgresql": (
12
+ "pg_catalog relation/type/typmod/null/generation/collation and complete-Key observations",
13
+ "native current_user/session_user, role membership and row-security admission",
14
+ "original compiler LOCK, search-path resolution and before/after metadata programs",
15
+ "pg_catalog.pg_control_system(), current_database(), current_schemas() and original relation resolution for explicit schemaBinding",
16
+ "read-only/serializable transaction, statement timeout and cancellation",
17
+ "action dependency closure, DDL fence and original writer-incarnation custody",
18
+ "transaction receipt and reconnect reconciliation observations",
19
+ "declared pgvector extension/schema/version and keyword-index analyzer admission",
20
+ ),
21
+ "spark-delta": (
22
+ "Spark runtime version and original Delta table UUID/schema/type/null/collation observations",
23
+ "DESCRIBE DETAIL/HISTORY and original versionAsOf snapshot programs",
24
+ "job-group cancellation, whole-call deadline and owned-session cleanup",
25
+ "native transaction conflict, dependency closure and writer lifecycle custody",
26
+ "exact ordered per-table commit receipt and reconnect reconciliation",
27
+ ),
28
+ "unity-catalog": (
29
+ "warehouse/runtime version and authenticated SQL/REST principal observations",
30
+ "Unity Catalog information_schema and DESCRIBE DETAIL/EXTENDED JSON table observations",
31
+ "native vector endpoint/index metadata and query API when search is selected",
32
+ "current SQL SELECT, row filters/masks and original table/index identity revalidation",
33
+ "native group/role admission, dependency closure and unchanged-closure DDL fence",
34
+ "catalog-commit transaction and exact ordered table-version receipt/reconciliation",
35
+ "original complete snapshot vector and retention admission for snapshot reads",
36
+ ),
37
+ "truss": (
38
+ "original Truss runtime/Scalar ABI and binding authority observations",
39
+ "original current-graph, current-policy and authenticated principal custody",
40
+ "original protected action/manifest/frame/dependency admission and writer incarnation",
41
+ "original transaction receipt, reconciliation and engine control custody",
42
+ ),
43
+ "ashlar": (
44
+ "original Ashlar publication/source/revision and runtime/binding observations",
45
+ "held publication snapshot and authenticated current-read admission",
46
+ "original publisher/writer authority and engine control custody for mutations",
47
+ "original native transaction/frame/receipt/reconciliation admission for mutations",
48
+ ),
49
+ }
50
+
51
+
52
+ def privilege_report(
53
+ targets: list[dict[str, Any]], entries: list[dict[str, Any]]
54
+ ) -> dict[str, Any]:
55
+ reports = []
56
+ for target in targets:
57
+ kind = target["kind"]
58
+ runtime = _RUNTIME.get("postgresql" if kind == "lakebase" else kind)
59
+ unresolved = []
60
+ operations = []
61
+ for entry in entries:
62
+ if entry["targetId"] != target["id"]:
63
+ continue
64
+ artifact = entry["artifact"]
65
+ owner = artifact.get("privilegeInventory")
66
+ complete = (
67
+ type(owner) is dict
68
+ and owner.get("version") == "weft.native-privileges/0.1"
69
+ and owner.get("complete") is True
70
+ and owner.get("unresolved") == []
71
+ )
72
+ if not complete:
73
+ unresolved.append(
74
+ {
75
+ "entry": entry["name"],
76
+ "requirement": "original owner exact used columns, operations, functions/operators, indexes and grant proposal",
77
+ }
78
+ )
79
+ operations.append(
80
+ {
81
+ "name": entry["name"],
82
+ "kind": entry["kind"],
83
+ "referencedTables": artifact.get("referencedTables"),
84
+ "referencedTablesScope": "conservative owner binding inventory; not exact least privilege",
85
+ "nativeObligations": artifact.get("obligations"),
86
+ "ownerInventory": owner,
87
+ }
88
+ )
89
+ if runtime is None:
90
+ unresolved.append(
91
+ {"requirement": "qualified target runtime metadata inventory"}
92
+ )
93
+ else:
94
+ unresolved.append(
95
+ {
96
+ "requirement": "exact target runtime metadata/control privileges and native function/operator identities; checklist alone is not an inventory"
97
+ }
98
+ )
99
+ advisory = (
100
+ postgres_runtime_advisory(
101
+ target,
102
+ [entry for entry in entries if entry["targetId"] == target["id"]],
103
+ )
104
+ if kind in ("postgresql", "lakebase")
105
+ else None
106
+ )
107
+ reports.append(
108
+ {
109
+ "id": target["id"],
110
+ "kind": kind,
111
+ "entries": operations,
112
+ "knownRuntimeSurface": list(runtime or ()),
113
+ "runtimeSurfaceScope": "profile review checklist; not a sufficient grant set",
114
+ **({"runtimeAdvisory": advisory} if advisory is not None else {}),
115
+ "hostOnlyObligations": [
116
+ "host applies and verifies native grants; SDK never executes grant proposals",
117
+ "independent native principal and least-privilege E2E",
118
+ "original native dependency/fence/restore/snapshot/control custody for each selected capability",
119
+ ],
120
+ "unresolved": unresolved,
121
+ "inventoryComplete": not unresolved,
122
+ "grantProposal": {
123
+ "status": "OWNER_INVENTORY_REQUIRED"
124
+ if unresolved
125
+ else "SEE_ORIGINAL_OWNER_INVENTORIES"
126
+ },
127
+ "qualification": {
128
+ "leastPrivilege": "UNQUALIFIED",
129
+ "sufficiencyClaim": False,
130
+ "reason": "native host proof is required; incomplete inventory refuses affected capability qualification",
131
+ },
132
+ }
133
+ )
134
+ return {"contract": "umf-access-privileges/0.1", "targets": reports}
@@ -0,0 +1,365 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Search capture -> original Weft owner programs. No execution or embedder calls."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import hashlib
7
+ import json
8
+ from dataclasses import replace
9
+ from typing import Any, cast
10
+
11
+ from ..capture import CapturedDeclaration, ProjectionRef
12
+ from ..dsl import FieldRef, Node, SearchLeg, render_logical
13
+ from ..generated_core import CURRENT_CORE_VERSION
14
+ from ..native_program import NativeProgram
15
+ from ..reviewed import parameter_signature
16
+ from ..types import StrictModel
17
+ from .unity_search import compile_unity_search
18
+
19
+
20
+ class SearchBuildError(ValueError):
21
+ pass
22
+
23
+
24
+ def emit_search(
25
+ compiler: Any,
26
+ declaration: CapturedDeclaration,
27
+ record: Any,
28
+ targets: list[dict[str, Any]],
29
+ manifest: dict[str, Any],
30
+ number: int,
31
+ name: str,
32
+ result_expr: str,
33
+ projection_fields: tuple[FieldRef, ...],
34
+ projection_names: tuple[str, ...],
35
+ tuple_fields: tuple[str, ...],
36
+ signature: list[str],
37
+ argument_code: list[str],
38
+ argument_names: list[str],
39
+ return_type: str,
40
+ key_models: dict[str, Any],
41
+ ) -> tuple[list[str], list[dict[str, Any]]]:
42
+ lines = []
43
+ entries = []
44
+ variants = []
45
+ key_fields = tuple(record.objects.ref.key)
46
+ candidates = [
47
+ k
48
+ for k in key_models.values()
49
+ if hasattr(k, "KEY_IDENTITY")
50
+ and (k.KEY_IDENTITY["module"], k.KEY_IDENTITY["element"])
51
+ == (record.objects.ref.module, record.objects.ref.element)
52
+ and tuple((m, f) for m, f, _ in k.UMF_FIELDS)
53
+ == tuple((f.field_module, f.field) for f in key_fields)
54
+ ]
55
+ # Same-component aliases have distinct source Key IDs; use the authored
56
+ # selectedKey from the original source view rather than a first-Key guess.
57
+ for _vi, variant in enumerate(declaration.variants):
58
+ leg = cast(SearchLeg[Any], variant.node.args[2])
59
+ top = cast(int, variant.node.args[3])
60
+ allow_partial = cast(bool, variant.node.args[4])
61
+ legs = leg.legs if leg.kind == "hybrid" else (leg,)
62
+ fusion = leg.fusion
63
+ if fusion is not None and fusion.kind not in ("rrf", "target-defined"):
64
+ raise SearchBuildError(
65
+ "SEARCH_UNSUPPORTED: target-defined fusion requires a separately qualified native program"
66
+ )
67
+ depth = (
68
+ (fusion.depth if fusion.depth is not None else min(1000, top * 2))
69
+ if fusion and fusion.kind == "rrf"
70
+ else top
71
+ )
72
+ params = {}
73
+ paths: list[tuple[str, str, str | None]] = []
74
+ from types import UnionType
75
+ from typing import Union, get_args, get_origin
76
+
77
+ from umf_access.types import MISSING
78
+
79
+ for parameter in declaration.parameters:
80
+ if parameter.optional and parameter.name not in variant.presence:
81
+ continue
82
+ members = (
83
+ get_args(parameter.carrier)
84
+ if get_origin(parameter.carrier) in (Union, UnionType)
85
+ else (parameter.carrier,)
86
+ )
87
+ remaining = [m for m in members if m is not MISSING]
88
+ annotation = remaining[0]
89
+ for member in remaining[1:]:
90
+ annotation = annotation | member
91
+ if parameter.key_components:
92
+ param_key = cast(
93
+ type[StrictModel],
94
+ next(
95
+ m
96
+ for m in remaining
97
+ if isinstance(m, type) and hasattr(m, "KEY_IDENTITY")
98
+ ),
99
+ )
100
+ for component in parameter.key_components:
101
+ flat = parameter.name + "__" + component
102
+ params[flat] = param_key.model_fields[component].annotation
103
+ paths.append((flat, parameter.name, component))
104
+ else:
105
+ params[parameter.name] = annotation
106
+ paths.append((parameter.name, parameter.name, None))
107
+ filters = tuple(
108
+ s for s in cast(tuple[Node, ...], variant.node.args[1]) if s.op == "filter"
109
+ )
110
+ if any(
111
+ s.op not in ("filter", "select", "into")
112
+ for s in cast(tuple[Node, ...], variant.node.args[1])
113
+ ):
114
+ raise SearchBuildError(
115
+ "SEARCH_UNSUPPORTED: search is bounded after pre-filters only"
116
+ )
117
+ used: set[str] = set()
118
+
119
+ def visit(value: Any, used: set[str] = used) -> None:
120
+ if isinstance(value, Node):
121
+ if value.op == "param":
122
+ used.add(cast(str, value.args[0]))
123
+ elif value.op == "key_param":
124
+ used.update(
125
+ cast(str, value.args[0]) + "__" + c
126
+ for c in cast(tuple[str, ...], value.args[1])
127
+ )
128
+ for child in value.args:
129
+ visit(child)
130
+ elif isinstance(value, tuple):
131
+ for child in value:
132
+ visit(child)
133
+
134
+ for f in filters:
135
+ visit(f)
136
+ projection = ProjectionRef(
137
+ "", "", key_fields, tuple(f.logical_name for f in key_fields)
138
+ )
139
+ selected = replace(
140
+ variant,
141
+ node=Node(
142
+ "all", (variant.node.args[0], filters + (Node("into", (projection,)),))
143
+ ),
144
+ )
145
+ native_parameters: list[dict[str, Any]] = []
146
+ for used_name in used:
147
+ native_parameters.append({"name": used_name, **parameter_signature(params[used_name])})
148
+ native_parameters.sort(key=lambda p: p["name"])
149
+ if any(p.get("container") == "list" or p.get("nullable") is True for p in native_parameters):
150
+ lines.extend([
151
+ "from umf_access.search_catalog import SEARCH_FILTER_PARAMETER_ABI",
152
+ "if SEARCH_FILTER_PARAMETER_ABI != 'umf.search-filter-parameters/0.1':",
153
+ " raise RuntimeError('SEARCH_FILTER_PARAMETER_ABI_MISMATCH')",
154
+ "",
155
+ ])
156
+ for target in targets:
157
+ if target["kind"] not in ("postgresql", "lakebase", "unity-catalog"):
158
+ raise SearchBuildError(
159
+ "SEARCH_UNSUPPORTED: target has no qualified search row"
160
+ )
161
+ original = json.loads(target["binding"]["modelJson"])
162
+ views = [
163
+ v
164
+ for module in original["modules"]
165
+ for v in module.get("extensions", {})
166
+ .get("umf.access", {})
167
+ .get("views", [])
168
+ if v["record"]
169
+ == {
170
+ "module": record.objects.ref.module,
171
+ "element": record.objects.ref.element,
172
+ }
173
+ ]
174
+ if len(views) != 1:
175
+ raise SearchBuildError("explicit original selectedKey required")
176
+ search_key = next(
177
+ (
178
+ k
179
+ for k in candidates
180
+ if k.KEY_IDENTITY["key"] == views[0]["selectedKey"]["key"]
181
+ ),
182
+ None,
183
+ )
184
+ if search_key is None:
185
+ raise SearchBuildError("selected search Key model absent")
186
+ compiled = []
187
+ if target["kind"] == "unity-catalog":
188
+ program, query_argument, embed, aliases = compile_unity_search(
189
+ compiler, legs=legs, fusion=fusion, target=target,
190
+ selection_sql=render_logical(selected, binding=target["binding"], owner_bound=True),
191
+ native_parameters=native_parameters, fields=projection_fields,
192
+ names=projection_names, top=top, allow_partial=allow_partial,
193
+ bundle_digest=manifest["inputDigest"],
194
+ )
195
+ compiled.append(
196
+ f"SearchEntry(NativeProgram({program.original_json!r}, {program.statements_json!r}, {program.bundle_input_digest!r}), {result_expr}, {search_key.__name__}, {query_argument!r}, {embed!r}, {tuple_fields!r}, {aliases!r})"
197
+ )
198
+ entries.append({"name": name, "kind": "search", "targetId": target["id"], "presence": variant.presence, "leg": 0, "artifact": program.checked(), "fusion": None if fusion is None else {"kind": fusion.kind}})
199
+ elif fusion is not None and fusion.kind != "rrf":
200
+ raise SearchBuildError("SEARCH_UNSUPPORTED: PostgreSQL/Lakebase require explicit qualified runtime fusion")
201
+ for li, item in enumerate(legs if target["kind"] != "unity-catalog" else ()):
202
+ if (
203
+ item.index_json is None
204
+ or item.value is None
205
+ or item.value.op != "param"
206
+ ):
207
+ raise SearchBuildError(
208
+ "source-bound search index and parameter required"
209
+ )
210
+ descriptor = json.loads(item.index_json)
211
+ index = descriptor["declaration"]
212
+ source = descriptor["source"]
213
+ if source["documentSha256"] != target["binding"]["modelSha256"]:
214
+ raise SearchBuildError("search source/binding differs")
215
+ if (item.kind == "keyword") != (index["kind"] == "keyword"):
216
+ raise SearchBuildError("search leg/index meaning differs")
217
+ if (
218
+ item.kind == "text-vector"
219
+ and index["vector"]["computedBy"] != "host"
220
+ ):
221
+ raise SearchBuildError(
222
+ "SEARCH_UNSUPPORTED: target-computed text embedding mechanism unavailable"
223
+ )
224
+ native = None
225
+ projected = [
226
+ {"module": f.field_module, "element": f.field}
227
+ for f in projection_fields
228
+ ]
229
+ matches = [
230
+ v
231
+ for v in target.get("vectorBindings", [])
232
+ if v["field"] == index.get("vector", {}).get("field")
233
+ or v["field"] in projected
234
+ ]
235
+ if len(matches) > 1 or index["kind"] == "vector" and len(matches) != 1:
236
+ raise SearchBuildError(
237
+ "SEARCH_UNSUPPORTED: unique explicit native vector column/version binding required"
238
+ )
239
+ if matches:
240
+ native = matches[0]
241
+ request = {
242
+ "version": "weft.search/0.1",
243
+ "source": {
244
+ "documentId": source["documentId"],
245
+ "coreVersion": CURRENT_CORE_VERSION,
246
+ "documentSha256": source["documentSha256"],
247
+ "module": source["module"],
248
+ "pointer": source["pointer"],
249
+ },
250
+ "selection": {
251
+ "version": "weft.raw-read/0.1",
252
+ "target": {
253
+ "postgresql": "postgresql18",
254
+ "lakebase": "lakebase18",
255
+ }[target["kind"]],
256
+ "sql": render_logical(
257
+ selected, binding=target["binding"], owner_bound=True
258
+ ),
259
+ "binding": target["binding"],
260
+ "parameters": native_parameters,
261
+ "rowCap": 1000,
262
+ },
263
+ "queryParameter": "__umf_search_query",
264
+ "topK": depth,
265
+ "projection": [
266
+ {
267
+ "field": {"module": f.field_module, "element": f.field},
268
+ "name": alias,
269
+ }
270
+ for f, alias in zip(
271
+ projection_fields, projection_names, strict=True
272
+ )
273
+ ],
274
+ "vectorBinding": native,
275
+ "allowPartial": allow_partial,
276
+ }
277
+ program = NativeProgram.build(
278
+ compiler, request, bundle_input_digest=manifest["inputDigest"]
279
+ )
280
+ artifact = program.checked()
281
+ if artifact["index"] != index:
282
+ raise SearchBuildError(
283
+ "captured index metadata differs from original source"
284
+ )
285
+ compiled.append(
286
+ f"SearchEntry(NativeProgram({program.original_json!r}, {program.statements_json!r}, {program.bundle_input_digest!r}), {result_expr}, {search_key.__name__}, {item.value.args[0]!r}, {item.kind == 'text-vector'!r}, {tuple_fields!r})"
287
+ )
288
+ entries.append(
289
+ {
290
+ "name": name,
291
+ "kind": "search",
292
+ "targetId": target["id"],
293
+ "presence": variant.presence,
294
+ "leg": li,
295
+ "artifact": artifact,
296
+ "fusion": None
297
+ if fusion is None
298
+ else {
299
+ "kind": fusion.kind,
300
+ "k": fusion.constant,
301
+ "depth": depth,
302
+ },
303
+ }
304
+ )
305
+ digest = hashlib.sha256(
306
+ json.dumps(
307
+ target["binding"],
308
+ ensure_ascii=False,
309
+ sort_keys=True,
310
+ separators=(",", ":"),
311
+ allow_nan=False,
312
+ ).encode()
313
+ ).hexdigest()
314
+ pin = (
315
+ target["kind"],
316
+ target["backendId"],
317
+ target["backendVersion"],
318
+ target["targetProfile"],
319
+ digest,
320
+ tuple(
321
+ (p["name"], tuple(str(v) for v in p["versions"]))
322
+ for p in target["platform"]
323
+ ),
324
+ )
325
+ fusion_code = (
326
+ "None"
327
+ if fusion is None
328
+ else f"Fusion({fusion.kind!r}, {fusion.constant!r}, {depth!r})"
329
+ )
330
+ variants.append(
331
+ f"SearchVariant({variant.presence!r}, TargetPin{pin!r}, ({', '.join(compiled)},), {tuple(paths)!r}, {top!r}, {fusion_code})"
332
+ )
333
+ plan = f"_S{number}"
334
+ lines.extend(
335
+ [
336
+ f"{plan} = SearchPlan({name!r}, ("
337
+ + ", ".join(argument_code)
338
+ + ("," if argument_code else "")
339
+ + "), ("
340
+ + ", ".join(variants)
341
+ + ",))",
342
+ "",
343
+ ]
344
+ )
345
+ ordered = [s for s in signature if " = MISSING" not in s] + [
346
+ s for s in signature if " = MISSING" in s
347
+ ]
348
+ tail = ", *, " + ", ".join(ordered + ["timeout: timedelta | None = None"])
349
+ for target_type, returned in [
350
+ ("SearchTarget", return_type),
351
+ ("AsyncSearchTarget", "Awaitable[" + return_type + "]"),
352
+ ]:
353
+ lines.extend(
354
+ ["@overload", f"def {name}(target: {target_type}{tail}) -> {returned}: ..."]
355
+ )
356
+ result = return_type + " | Awaitable[" + return_type + "]"
357
+ values = "{" + ", ".join(repr(n) + ": " + n for n in argument_names) + "}"
358
+ lines.extend(
359
+ [
360
+ f"def {name}(target: SearchTarget | AsyncSearchTarget{tail}) -> {result}:",
361
+ f" return cast({result}, {plan}.run(target, {values}, timeout=timeout))",
362
+ "",
363
+ ]
364
+ )
365
+ return lines, entries
@@ -0,0 +1,104 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Closed Unity Catalog search build bridge; original Weft programs own SQL."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ from collections.abc import Sequence
8
+ from typing import Any
9
+
10
+ from ..dsl import FieldRef, Fusion, SearchLeg
11
+ from ..native_program import NativeProgram
12
+
13
+
14
+ def compile_unity_search(
15
+ compiler: Any,
16
+ *,
17
+ legs: Sequence[SearchLeg[Any]],
18
+ fusion: Fusion | None,
19
+ target: dict[str, Any],
20
+ selection_sql: str,
21
+ native_parameters: list[dict[str, Any]],
22
+ fields: tuple[FieldRef, ...],
23
+ names: tuple[str, ...],
24
+ top: int,
25
+ allow_partial: bool,
26
+ bundle_digest: str,
27
+ ) -> tuple[NativeProgram, str, bool, tuple[tuple[str, str], ...]]:
28
+ vectors = [leg for leg in legs if leg.kind in ("vector", "text-vector")]
29
+ keywords = [leg for leg in legs if leg.kind == "keyword"]
30
+ if (
31
+ len(vectors) != 1
32
+ or len(vectors) + len(keywords) != len(legs)
33
+ or len(keywords) > 1
34
+ or bool(keywords) != (fusion is not None)
35
+ or fusion is not None and fusion.kind != "target-defined"
36
+ ):
37
+ raise ValueError("SEARCH_UNSUPPORTED: Unity Catalog requires ANN or native target-defined HYBRID")
38
+ if allow_partial is not True or not isinstance(target.get("unitySearch"), dict):
39
+ raise ValueError("SEARCH_FILTER: explicit asynchronous partial search and managed binding required")
40
+
41
+ def descriptor(leg: SearchLeg[Any]) -> tuple[dict[str, Any], dict[str, Any]]:
42
+ if leg.index_json is None or leg.value is None or leg.value.op != "param":
43
+ raise ValueError("source-bound search index and original parameter required")
44
+ value = json.loads(leg.index_json)
45
+ source, index = value["source"], value["declaration"]
46
+ if source["documentSha256"] != target["binding"]["modelSha256"]:
47
+ raise ValueError("search source/binding differs")
48
+ return source, index
49
+
50
+ vector = vectors[0]
51
+ source, index = descriptor(vector)
52
+ if index["kind"] != "vector" or (
53
+ vector.kind == "text-vector" and index["vector"]["computedBy"] != "host"
54
+ ):
55
+ raise ValueError("SEARCH_UNSUPPORTED: explicit host vector mechanism required")
56
+
57
+ def original_source(value: dict[str, Any]) -> dict[str, Any]:
58
+ return {name: value[name] for name in (
59
+ "documentId", "coreVersion", "documentSha256", "module", "pointer"
60
+ )} if "coreVersion" in value else {
61
+ **{name: value[name] for name in ("documentId", "documentSha256", "module", "pointer")},
62
+ "coreVersion": json.loads(target["binding"]["modelJson"])["umf"],
63
+ }
64
+
65
+ occupied = {parameter["name"] for parameter in native_parameters}
66
+ occupied.update(str(leg.value.args[0]) for leg in legs if leg.value is not None)
67
+
68
+ def internal(name: str) -> str:
69
+ while name in occupied:
70
+ name += "_"
71
+ occupied.add(name)
72
+ return name
73
+
74
+ request: dict[str, Any] = {
75
+ "version": "weft.unity-search/0.1",
76
+ "source": original_source(source),
77
+ "selection": {
78
+ "version": "weft.raw-read/0.1", "target": "unity-catalog-current",
79
+ "sql": selection_sql, "binding": target["binding"],
80
+ "parameters": native_parameters, "rowCap": 1000,
81
+ },
82
+ "queryParameter": internal("__umf_search_query"), "topK": top,
83
+ "projection": [
84
+ {"field": {"module": field.field_module, "element": field.field}, "name": name}
85
+ for field, name in zip(fields, names, strict=True)
86
+ ],
87
+ "allowPartial": True, "managed": target["unitySearch"],
88
+ }
89
+ aliases: tuple[tuple[str, str], ...] = ()
90
+ if keywords:
91
+ keyword_source, keyword_index = descriptor(keywords[0])
92
+ if keyword_index["kind"] != "keyword":
93
+ raise ValueError("search leg/index meaning differs")
94
+ request["keywordSource"] = original_source(keyword_source)
95
+ text_parameter = internal("__umf_search_text")
96
+ request["textQueryParameter"] = text_parameter
97
+ aliases = ((text_parameter, str(keywords[0].value.args[0])),)
98
+ request["fusion"] = {"kind": "target-defined"}
99
+ program = NativeProgram.build(compiler, request, bundle_input_digest=bundle_digest)
100
+ if program.checked()["index"] != index:
101
+ raise ValueError("captured index metadata differs from original source")
102
+ if keywords and program.checked()["keywordIndex"] != keyword_index:
103
+ raise ValueError("captured keyword index metadata differs from original source")
104
+ return program, str(vector.value.args[0]), vector.kind == "text-vector", aliases