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,1626 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Capture explicit trusted Python modules and publish deterministic stage-two files.
3
+
4
+ Only the build tool imports declarations and Weft. Runtime code contains inert
5
+ catalog artifacts and explicit model references; it never imports declarations.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import hashlib
12
+ import importlib
13
+ import importlib.metadata
14
+ import inspect
15
+ import json
16
+ import keyword
17
+ import os
18
+ import re
19
+ import shutil
20
+ import sys
21
+ import tempfile
22
+ from contextlib import contextmanager
23
+ from dataclasses import replace
24
+ from pathlib import Path
25
+ from threading import Lock
26
+ from types import UnionType
27
+ from typing import Annotated, Any, Union, cast, get_args, get_origin
28
+
29
+ from pydantic import create_model
30
+
31
+ from ..capture import ProjectionRef, capture
32
+ from ..codec_support import make_projection_model, make_scalar_projection_model
33
+ from ..dsl import (
34
+ FieldRef,
35
+ Node,
36
+ RecordRef,
37
+ nullable_join_owners,
38
+ render_logical,
39
+ render_related_logical,
40
+ )
41
+ from ..engine_catalog import EngineRead
42
+ from ..manifest_commands import manifest_registry
43
+ from ..native_program import NativeProgram, program_json
44
+ from ..related_keys import key_descriptor, make_related_result_model, validate_decoder
45
+ from ..reviewed import (
46
+ CatalogRead,
47
+ ReadBuildError,
48
+ ReadCompiler,
49
+ ReviewedSQL,
50
+ captured_source,
51
+ )
52
+ from ..types import MISSING, RUNTIME_IDENTITY, ActionRef, StrictModel
53
+ from .approximate import require_approximate_profile
54
+ from .commands import emit_command
55
+ from .privileges import privilege_report
56
+ from .search import emit_search
57
+
58
+ OWNED = (
59
+ "queries.py",
60
+ "_umf/catalog.json",
61
+ "_umf/catalog-manifest.json",
62
+ "_umf/privileges.json",
63
+ )
64
+
65
+
66
+ class CatalogBuildError(ValueError):
67
+ def __init__(self, message: str, *, code: str | None = None, **metadata: object):
68
+ super().__init__(message)
69
+ self.code = code
70
+ self.metadata = metadata
71
+
72
+
73
+ _owned_destinations: set[Path] = set()
74
+ _destination_lock = Lock()
75
+
76
+
77
+ @contextmanager
78
+ def _own_destination(root: Path, package: object):
79
+ if (
80
+ type(package) is not str
81
+ or not re.fullmatch(r"[a-z][a-z0-9_]*", package)
82
+ or keyword.iskeyword(package)
83
+ ):
84
+ raise CatalogBuildError("explicit generated package required")
85
+ destination = (root / package).resolve()
86
+ with _destination_lock:
87
+ if destination in _owned_destinations:
88
+ raise CatalogBuildError(
89
+ "output already has a cooperating operation", code="OUTPUT_BUSY"
90
+ )
91
+ _owned_destinations.add(destination)
92
+ try:
93
+ yield
94
+ finally:
95
+ with _destination_lock:
96
+ _owned_destinations.remove(destination)
97
+
98
+
99
+ def _json(value: object) -> str:
100
+ return json.dumps(
101
+ value,
102
+ ensure_ascii=False,
103
+ sort_keys=True,
104
+ separators=(",", ":"),
105
+ allow_nan=False,
106
+ )
107
+
108
+
109
+ def _sha(data: bytes) -> str:
110
+ return hashlib.sha256(data).hexdigest()
111
+
112
+
113
+ def _read(path: Path) -> bytes:
114
+ if path.is_symlink() or not path.is_file() or path.stat().st_size > 33_554_432:
115
+ raise CatalogBuildError("ordinary bounded source file required")
116
+ return path.read_bytes()
117
+
118
+
119
+ def _type(annotation: object, package: str) -> str:
120
+ from decimal import Decimal
121
+
122
+ from ..types import Vector
123
+
124
+ if annotation == Vector:
125
+ return "Vector"
126
+ from datetime import date, datetime
127
+
128
+ if annotation in (str, int, bool, bytes, float):
129
+ return annotation.__name__
130
+ if annotation is type(None):
131
+ return "None"
132
+ if annotation is MISSING:
133
+ return "MISSING"
134
+ if annotation is Decimal:
135
+ return "Decimal"
136
+ if annotation in (date, datetime):
137
+ raise CatalogBuildError("temporal catalog qualification held")
138
+ origin = get_origin(annotation)
139
+ if origin is Annotated:
140
+ return _type(get_args(annotation)[0], package)
141
+ if origin is list and len(get_args(annotation)) == 1:
142
+ return "list[" + _type(get_args(annotation)[0], package) + "]"
143
+ if origin in (UnionType, Union):
144
+ return " | ".join(_type(a, package) for a in get_args(annotation))
145
+ if (
146
+ isinstance(annotation, type)
147
+ and issubclass(annotation, StrictModel)
148
+ and annotation.__module__ in (package + ".keys", package + ".models")
149
+ ):
150
+ return annotation.__name__
151
+ raise CatalogBuildError("unsupported catalog signature carrier")
152
+
153
+
154
+ def _without_missing(annotation: object) -> object:
155
+ args = get_args(annotation)
156
+ if not args or MISSING not in args:
157
+ return annotation
158
+ parts = [a for a in args if a is not MISSING]
159
+ result = parts[0]
160
+ for part in parts[1:]:
161
+ result = result | part
162
+ return result
163
+
164
+
165
+ def _engine_selected_key(ref: RecordRef) -> dict[str, str]:
166
+ if type(ref.key_id) is not str or not ref.key_id:
167
+ raise CatalogBuildError("WEFT_BLOCKED: original selected Record Key required")
168
+ return {"module": ref.module, "record": ref.element, "key": ref.key_id}
169
+
170
+
171
+ def _native_binding_source(columns: Any) -> dict[str, str]:
172
+ binding = columns.get("binding") if type(columns) is dict else None
173
+ if (
174
+ type(binding) is not dict
175
+ or set(binding) != {"sourceId", "documentJson", "documentSha256"}
176
+ or any(type(binding[k]) is not str or not binding[k] for k in binding)
177
+ ):
178
+ raise CatalogBuildError("native columns require an original binding source")
179
+ try:
180
+ digest = _sha(binding["documentJson"].encode("utf-8"))
181
+ except UnicodeEncodeError as error:
182
+ raise CatalogBuildError("native binding source must be UTF-8") from error
183
+ if digest != binding["documentSha256"]:
184
+ raise CatalogBuildError("native binding source digest differs")
185
+ return binding
186
+
187
+
188
+ def _native_column_bindings(target: dict[str, Any]) -> tuple[dict[str, str], ...]:
189
+ """Collect original byte references only; native owners admit their meaning."""
190
+ if target.get("version") == "weft.related-read/0.1":
191
+ source, destination = target.get("source"), target.get("target")
192
+ if (
193
+ type(source) is not dict or type(destination) is not dict
194
+ or source.get("version") == "weft.related-read/0.1"
195
+ or destination.get("version") == "weft.related-read/0.1"
196
+ or type(source.get("binding")) is not dict
197
+ or source["binding"] != destination.get("binding")
198
+ ):
199
+ raise CatalogBuildError("related reads require one identical original native binding")
200
+ return _native_column_bindings(source) + _native_column_bindings(destination)
201
+ bindings = []
202
+ unity = target.get("unitySearch")
203
+ if type(unity) is dict and "nativeColumns" in unity:
204
+ bindings.append(_native_binding_source(unity["nativeColumns"]))
205
+ logical = target.get("binding")
206
+ if type(logical) is dict and "nativeColumns" in logical:
207
+ columns = logical["nativeColumns"]
208
+ sets = columns.get("sets") if type(columns) is dict else None
209
+ if type(sets) is not list or not 1 <= len(sets) <= 64:
210
+ raise CatalogBuildError(
211
+ "bounded original native ColumnSet sources required"
212
+ )
213
+ bindings.extend(_native_binding_source(item) for item in sets)
214
+ return tuple(bindings)
215
+
216
+
217
+ def _check_native_column_sources(
218
+ targets: list[dict[str, Any]], manifest: dict[str, Any], root: Path, package: str
219
+ ) -> None:
220
+ bindings = [
221
+ binding for target in targets for binding in _native_column_bindings(target)
222
+ ]
223
+ if not bindings:
224
+ return
225
+ path = f"{package}/_umf/sources.json"
226
+ entries = [item for item in manifest["inventory"] if item["path"] == path]
227
+ if len(entries) != 1:
228
+ raise CatalogBuildError("native binding requires inventoried stage-one sources")
229
+ data = _read(root / path)
230
+ if _sha(data) != entries[0]["sha256"]:
231
+ raise CatalogBuildError("stage-one source drift")
232
+ sources = json.loads(data)
233
+ if type(sources) is not list:
234
+ raise CatalogBuildError("invalid stage-one source inventory")
235
+ for binding in bindings:
236
+ matches = [
237
+ s for s in sources if type(s) is dict and s.get("id") == binding["sourceId"]
238
+ ]
239
+ if len(matches) != 1 or matches[0].get("text") != binding["documentJson"]:
240
+ raise CatalogBuildError(
241
+ "native binding differs from retained stage-one source"
242
+ )
243
+
244
+
245
+ def _resolve_schema_binding(target: dict[str, Any]) -> None:
246
+ if "schemaBinding" not in target:
247
+ return
248
+ mode, binding = target["schemaBinding"], target.get("binding")
249
+ if (
250
+ target.get("kind") not in ("postgresql", "lakebase")
251
+ or mode not in ("qualified", "search-path")
252
+ or type(binding) is not dict
253
+ or "schemaBinding" in binding
254
+ and binding["schemaBinding"] != mode
255
+ or mode == "qualified"
256
+ and (type(binding.get("schema")) is not str or not binding["schema"])
257
+ or mode == "search-path"
258
+ and binding.get("schema") is not None
259
+ ):
260
+ raise CatalogBuildError(
261
+ "schemaBinding differs from the explicit native binding"
262
+ )
263
+ binding["schemaBinding"] = mode
264
+
265
+
266
+ def resolve_configuration(
267
+ configuration: dict[str, Any], root: Path
268
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
269
+ """Resolve only explicitly named local files, before importing declarations.
270
+
271
+ Compact inline configurations retain their experimental profile. The full
272
+ profile additionally pins the installed compiler and original UMF sources.
273
+ """
274
+ root = root.resolve()
275
+ compact = {"package", "modules", "targets"}
276
+ if set(configuration) not in (compact, compact | {"weft", "umf"}):
277
+ raise CatalogBuildError("unknown or missing catalog configuration member")
278
+ resolved = json.loads(_json(configuration))
279
+ provenance: dict[str, Any] = {"configuration": configuration, "sources": []}
280
+ if "weft" not in configuration:
281
+ provenance["profile"] = "experimental-inline/0.1"
282
+ for target in resolved.get("targets", []):
283
+ _resolve_schema_binding(target)
284
+ return resolved, provenance
285
+ pin = configuration["weft"]
286
+ if (
287
+ type(pin) is not dict
288
+ or set(pin) != {"distribution", "version"}
289
+ or type(pin["distribution"]) is not str
290
+ or pin["distribution"] not in ("weft-sql", "umf-weft")
291
+ or type(pin["version"]) is not str
292
+ ):
293
+ raise CatalogBuildError("explicit Weft distribution/version required")
294
+ if importlib.metadata.version(pin["distribution"]) != pin["version"]:
295
+ raise CatalogBuildError(
296
+ "WEFT_BLOCKED: installed compiler version differs from configuration"
297
+ )
298
+ provenance.update(profile="source-pinned/0.1", weft=pin)
299
+
300
+ def source(descriptor: Any) -> bytes:
301
+ if (
302
+ type(descriptor) is not dict
303
+ or set(descriptor) != {"path", "sha256"}
304
+ or type(descriptor["path"]) is not str
305
+ ):
306
+ raise CatalogBuildError("explicit local path and SHA-256 source required")
307
+ relative = Path(descriptor["path"])
308
+ if relative.is_absolute() or ".." in relative.parts:
309
+ raise CatalogBuildError("source must be inside the explicit build root")
310
+ path = root / relative
311
+ if any(
312
+ p.is_symlink() for p in (path, *path.parents)
313
+ ) or not path.resolve().is_relative_to(root.resolve()):
314
+ raise CatalogBuildError("source symlinks or root escape refused")
315
+ data = _read(path)
316
+ if _sha(data) != descriptor["sha256"]:
317
+ raise CatalogBuildError("pinned source bytes differ")
318
+ provenance["sources"].append(descriptor)
319
+ return data
320
+
321
+ umf = configuration["umf"]
322
+ if (
323
+ type(umf) is not dict
324
+ or set(umf) != {"documents"}
325
+ or type(umf["documents"]) is not list
326
+ or not 1 <= len(umf["documents"]) <= 64
327
+ ):
328
+ raise CatalogBuildError("explicit bounded UMF document inventory required")
329
+ originals = [source(d).decode("utf-8") for d in umf["documents"]]
330
+ if len(set(originals)) != len(originals):
331
+ raise CatalogBuildError("duplicate original document source")
332
+ for target in resolved["targets"]:
333
+ if "bindingSource" in target:
334
+ if "binding" in target:
335
+ raise CatalogBuildError("duplicate binding source")
336
+ target["binding"] = program_json(
337
+ source(target.pop("bindingSource")).decode("utf-8")
338
+ )
339
+ _resolve_schema_binding(target)
340
+ if target.get("kind") in ("truss", "ashlar"):
341
+ requests = target.get("engineRequests")
342
+ manifests = target.get("manifestCommands")
343
+ if manifests is not None:
344
+ if target["kind"] != "truss" or type(manifests) is not dict or not manifests:
345
+ raise CatalogBuildError("MANIFEST_ORIGINAL_CONFIGURATION_REQUIRED")
346
+ for entry in manifests.values():
347
+ if (type(entry) is not dict or set(entry) != {"configuration", "request"}
348
+ or type(entry["configuration"]) is not str or type(entry["request"]) is not dict):
349
+ raise CatalogBuildError("MANIFEST_ORIGINAL_CONFIGURATION_REQUIRED")
350
+ registry = manifest_registry(entry["configuration"])
351
+ model = entry["request"].get("model")
352
+ if (type(registry) is not dict or type(registry.get("actions")) is not list
353
+ or type(model) is not dict or model.get("utf8") not in originals
354
+ or any(type(action) is not dict or type(action.get("snapshot")) is not dict
355
+ or action["snapshot"].get("utf8") not in originals
356
+ for action in registry["actions"])):
357
+ raise CatalogBuildError("manifest models must equal complete original pinned documents")
358
+ if requests is None and manifests is not None:
359
+ pass # Command-only target; read declarations still require their own owner request.
360
+ elif (
361
+ type(requests) is not dict
362
+ or not requests
363
+ or any(
364
+ type(r) is not dict
365
+ or not r.get("modules")
366
+ or any(m.get("documentJson") not in originals for m in r["modules"])
367
+ for r in requests.values()
368
+ )
369
+ ):
370
+ raise CatalogBuildError(
371
+ "complete original pinned engine request source inventory required"
372
+ )
373
+ if target.get("binding", {}).get("modelJson") not in originals:
374
+ raise CatalogBuildError(
375
+ "binding model must equal one complete original pinned document"
376
+ )
377
+ if any(
378
+ binding["documentJson"] not in originals
379
+ for binding in _native_column_bindings(target)
380
+ ):
381
+ raise CatalogBuildError(
382
+ "native binding must equal one complete original pinned document"
383
+ )
384
+ return resolved, provenance
385
+
386
+
387
+ def compile_catalog(
388
+ configuration: dict[str, Any], root: Path, compiler: ReadCompiler
389
+ ) -> dict[str, bytes]:
390
+ with _own_destination(root, configuration.get("package")):
391
+ return _compile_catalog_owned(configuration, root, compiler)
392
+
393
+
394
+ def _compile_catalog_owned(
395
+ configuration: dict[str, Any], root: Path, compiler: ReadCompiler
396
+ ) -> dict[str, bytes]:
397
+ configuration, configuration_provenance = resolve_configuration(configuration, root)
398
+ package = configuration.get("package")
399
+ if (
400
+ type(package) is not str
401
+ or not re.fullmatch(r"[a-z][a-z0-9_]*", package)
402
+ or keyword.iskeyword(package)
403
+ ):
404
+ raise CatalogBuildError("explicit generated package required")
405
+ package_root = root / package
406
+ manifest = json.loads(_read(package_root / "_umf/manifest.json"))
407
+ if manifest["runtimeAbi"] != {
408
+ "distribution": RUNTIME_IDENTITY[0],
409
+ "version": RUNTIME_IDENTITY[1],
410
+ "abi": RUNTIME_IDENTITY[2],
411
+ }:
412
+ raise CatalogBuildError("CATALOG_STALE: stage-one runtime ABI differs")
413
+ for item in manifest["inventory"]:
414
+ relative = Path(item["path"])
415
+ if (
416
+ relative.is_absolute()
417
+ or ".." in relative.parts
418
+ or relative.parts[0] != package
419
+ ):
420
+ raise CatalogBuildError("unsafe stage-one inventory")
421
+ if _sha(_read(root / relative)) != item["sha256"]:
422
+ raise CatalogBuildError("stage-one source drift")
423
+ modules = configuration.get("modules")
424
+ targets = configuration.get("targets")
425
+ if (
426
+ not isinstance(modules, list)
427
+ or not modules
428
+ or len(set(modules)) != len(modules)
429
+ or not isinstance(targets, list)
430
+ or not targets
431
+ ):
432
+ raise CatalogBuildError(
433
+ "explicit ordered declaration modules and targets required"
434
+ )
435
+ if (
436
+ len(modules) > 64
437
+ or len(targets) > 32
438
+ or len({t["id"] for t in targets}) != len(targets)
439
+ ):
440
+ raise CatalogBuildError("catalog bound or duplicate target")
441
+ _check_native_column_sources(targets, manifest, root, package)
442
+ sys.path.insert(0, str(root))
443
+ generated = importlib.import_module(package)
444
+ imported_digest = getattr(
445
+ importlib.import_module(package + ".keys"), "BUNDLE_INPUT_DIGEST", None
446
+ )
447
+ if imported_digest != manifest["inputDigest"]:
448
+ raise CatalogBuildError("CATALOG_STALE: mixed loaded generation")
449
+ models: dict[str, Any] = {
450
+ v.__name__: v
451
+ for v in vars(generated).values()
452
+ if isinstance(v, type) and issubclass(v, StrictModel)
453
+ }
454
+ records = {
455
+ (m.objects.ref.module, m.objects.ref.element): m
456
+ for m in models.values()
457
+ if hasattr(m, "objects")
458
+ }
459
+ provenance = []
460
+ declarations = []
461
+ names = set()
462
+ for name in modules:
463
+ if type(name) is not str or not all(
464
+ re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", part) and not keyword.iskeyword(part)
465
+ for part in name.split(".")
466
+ ):
467
+ raise CatalogBuildError("explicit absolute Python module names required")
468
+ module = importlib.import_module(name)
469
+ source_path = Path(inspect.getfile(module)).resolve()
470
+ provenance.append(
471
+ {"module": name, "path": str(source_path), "sha256": _sha(_read(source_path))}
472
+ )
473
+ for symbol, function in vars(module).items():
474
+ if (
475
+ callable(function)
476
+ and getattr(function, "__module__", None) == name
477
+ and getattr(function, "__umf_kind__", None) in ("query", "command")
478
+ ):
479
+ if symbol in names:
480
+ raise CatalogBuildError("duplicate public catalog name")
481
+ names.add(symbol)
482
+ declarations.append((symbol, capture(function)))
483
+ # Validate original capture before resolving aliases or manufacturing result
484
+ # classes: count/tuple projections otherwise erase their source provenance.
485
+ for _, declaration in declarations:
486
+ for variant in declaration.variants:
487
+ for target in targets:
488
+ source = captured_source(variant, binding=target["binding"])
489
+ root_ref = cast(RecordRef, variant.node.args[0])
490
+ record = records.get((root_ref.module, root_ref.element))
491
+ original_root = replace(
492
+ root_ref,
493
+ alias=None,
494
+ key=tuple(replace(field, alias=None) for field in root_ref.key),
495
+ )
496
+ if (
497
+ source.input_digest != manifest["inputDigest"]
498
+ or record is None
499
+ or getattr(record, "UMF_SOURCE", None) != source
500
+ or record.objects.ref != original_root
501
+ ):
502
+ raise ReadBuildError(
503
+ "CATALOG_STALE: captured root differs from selected stage-one generation"
504
+ )
505
+ if (not declarations and not any(t.get("nativeActions") for t in targets)) or len(
506
+ declarations
507
+ ) > 1000:
508
+ raise CatalogBuildError("bounded declarations required")
509
+ lines = [
510
+ "# Generated stage-two catalog. Regenerate; do not edit.",
511
+ "from __future__ import annotations",
512
+ "from datetime import timedelta",
513
+ "from decimal import Decimal",
514
+ "from typing import ClassVar, cast, overload, TypeVar",
515
+ "from collections.abc import Awaitable, Generator, AsyncGenerator",
516
+ "from umf_access.types import MISSING",
517
+ "from umf_access.types import StrictModel",
518
+ "from umf_access.reviewed import CatalogRead",
519
+ "from umf_access.engine_catalog import EngineRead",
520
+ "from umf_access.pages import ReadPage, ReadContinuation",
521
+ "from umf_access.dsl import Page, Continuation, WithKeys",
522
+ "from umf_access.related_keys import make_related_result_model",
523
+ "from umf_access.protocols import ReadTarget, AsyncReadTarget",
524
+ "from umf_access.catalog import Argument, ReadPlan, ReadVariant, TargetPin, run_query, run_stream",
525
+ "from umf_access.codec_support import make_projection_model, make_scalar_projection_model",
526
+ "from .models import *",
527
+ "from .keys import *",
528
+ "",
529
+ ]
530
+ lines.extend(
531
+ [
532
+ "from umf_access.commands import BulkTarget, AsyncBulkTarget, CommandVariant, CommandPlan",
533
+ "from umf_access.native_program import NativeProgram",
534
+ "_PlanT = TypeVar('_PlanT')",
535
+ "",
536
+ ]
537
+ )
538
+ lines.extend(
539
+ [
540
+ "from umf_access.search_catalog import SearchPlan, SearchVariant, SearchEntry, SearchTarget, AsyncSearchTarget",
541
+ "from umf_access.dsl import SearchResult, Fusion",
542
+ "from umf_access.types import Vector",
543
+ "",
544
+ ]
545
+ )
546
+ entries = []
547
+ native_programs = []
548
+ action_module = (
549
+ importlib.import_module(package + ".actions")
550
+ if any(s["role"] == "action-ref" for s in manifest["symbols"])
551
+ else None
552
+ )
553
+ action_refs = (
554
+ [a for a in vars(action_module).values() if isinstance(a, ActionRef)]
555
+ if action_module
556
+ else []
557
+ )
558
+ action_requests = {}
559
+ for target in targets:
560
+ if set(target) - {
561
+ "id",
562
+ "kind",
563
+ "backendId",
564
+ "backendVersion",
565
+ "targetProfile",
566
+ "schemaBinding",
567
+ "binding",
568
+ "platform",
569
+ "nativeActions",
570
+ "manifestCommands",
571
+ "security",
572
+ "roleMappings",
573
+ "sessionPrincipal",
574
+ "maxItems",
575
+ "vectorBindings",
576
+ "unitySearch",
577
+ "snapshots",
578
+ "engineRequests",
579
+ "engineCompiler",
580
+ }:
581
+ raise CatalogBuildError("unknown target configuration member")
582
+ if target.get("manifestCommands") is not None and target["kind"] != "truss":
583
+ raise CatalogBuildError("MANIFEST_TARGET_UNSUPPORTED")
584
+ if target["kind"] in ("truss", "ashlar"):
585
+ # CONTRACT-071: engine action dispatch stays in the engine SDK;
586
+ # shared generated packages may still retain selected ActionRefs.
587
+ if target.get("nativeActions"):
588
+ raise CatalogBuildError("engine targets have no native action catalog entries")
589
+ continue
590
+ requests = target.get("nativeActions")
591
+ if requests is None:
592
+ requests = []
593
+ for reference in action_refs:
594
+ if not all(
595
+ key in target
596
+ for key in ("security", "roleMappings", "sessionPrincipal")
597
+ ):
598
+ raise CatalogBuildError(
599
+ "WEFT_BLOCKED: selected actions require original target security, role mappings and principal profile"
600
+ )
601
+ action_source = reference.source
602
+ if action_source is None:
603
+ raise CatalogBuildError("original selected action source required")
604
+ requests.append(
605
+ {
606
+ "version": "weft.native-action/0.1",
607
+ "target": {
608
+ "postgresql": "postgresql18",
609
+ "lakebase": "lakebase18",
610
+ "spark-delta": "spark-delta4",
611
+ }.get(target["kind"]),
612
+ "binding": target["binding"],
613
+ "source": {
614
+ "documentId": action_source.document_id,
615
+ "coreVersion": action_source.core_version,
616
+ "module": action_source.module,
617
+ "action": action_source.action,
618
+ "documentSha256": action_source.document_sha256,
619
+ "actionPointer": action_source.action_pointer,
620
+ "invocation": {
621
+ "id": action_source.invocation_id,
622
+ "version": action_source.invocation_version,
623
+ },
624
+ },
625
+ "security": target["security"],
626
+ "roleMappings": target["roleMappings"],
627
+ "sessionPrincipal": target["sessionPrincipal"],
628
+ }
629
+ )
630
+ if {(r["source"]["module"], r["source"]["action"]) for r in requests} != {
631
+ (a.module, a.action) for a in action_refs
632
+ } or len(requests) != len(action_refs):
633
+ raise CatalogBuildError(
634
+ "every selected action must compile once for each raw target"
635
+ )
636
+ for action_request in requests:
637
+ if action_request["binding"] != target["binding"] or action_request[
638
+ "target"
639
+ ] != {
640
+ "postgresql": "postgresql18",
641
+ "lakebase": "lakebase18",
642
+ "spark-delta": "spark-delta4",
643
+ }.get(target["kind"]):
644
+ raise CatalogBuildError("native action target/binding differs")
645
+ original = action_request["source"]
646
+ action_module = importlib.import_module(package + ".actions")
647
+ selected_actions = [
648
+ a
649
+ for a in vars(action_module).values()
650
+ if getattr(a, "source", None) is not None
651
+ and a.source.document_sha256 == original["documentSha256"]
652
+ and a.module == original["module"]
653
+ and a.action == original["action"]
654
+ ]
655
+ if len(selected_actions) != 1:
656
+ raise CatalogBuildError(
657
+ "native action is outside selected stage-one generation"
658
+ )
659
+ program = NativeProgram.build(
660
+ compiler, action_request, bundle_input_digest=manifest["inputDigest"]
661
+ )
662
+ native_programs.append((target["id"], program))
663
+ action_requests[(target["id"], original["module"], original["action"])] = (
664
+ action_request
665
+ )
666
+ entries.append(
667
+ {
668
+ "name": original["action"],
669
+ "kind": "native-action",
670
+ "targetId": target["id"],
671
+ "artifact": json.loads(program.original_json),
672
+ "bundleInputDigest": manifest["inputDigest"],
673
+ }
674
+ )
675
+ if native_programs:
676
+ lines.append("from umf_access.native_program import NativeProgram")
677
+ lines.append("from .actions import *")
678
+ lines.append(
679
+ "NATIVE_ACTION_PROGRAMS = ("
680
+ + ", ".join(
681
+ "("
682
+ + repr(target_id)
683
+ + ", NativeProgram("
684
+ + repr(program.original_json)
685
+ + ", "
686
+ + repr(program.statements_json)
687
+ + ", "
688
+ + repr(program.bundle_input_digest)
689
+ + "))"
690
+ for target_id, program in native_programs
691
+ )
692
+ + ",)"
693
+ )
694
+ for number, (name, declaration) in enumerate(declarations):
695
+ if declaration.kind == "command":
696
+ if any(target["kind"] == "ashlar" for target in targets):
697
+ raise CatalogBuildError("ASHLAR_COMMAND_UNSUPPORTED: Ashlar has no SDK BulkTarget")
698
+ command_ref = cast(RecordRef, declaration.variants[0].node.args[0])
699
+ command_record = records[(command_ref.module, command_ref.element)]
700
+ command_lines, command_entries = emit_command(
701
+ compiler,
702
+ declaration,
703
+ command_record,
704
+ targets,
705
+ action_requests,
706
+ action_refs,
707
+ manifest,
708
+ number,
709
+ name,
710
+ package,
711
+ _type,
712
+ )
713
+ lines.extend(command_lines)
714
+ entries.extend(command_entries)
715
+ continue
716
+ first = declaration.variants[0]
717
+ node = first.node
718
+ terminal = node.op
719
+ steps = cast(tuple[Node, ...], node.args[1])
720
+ snapshot = any(step.op == "snapshot" for step in steps)
721
+ record_ref = cast(RecordRef, node.args[0])
722
+ record = records[(record_ref.module, record_ref.element)]
723
+ projection = next(
724
+ (cast(ProjectionRef, s.args[0]) for s in steps if s.op == "into"), None
725
+ )
726
+ selected = cast(
727
+ tuple[FieldRef | Node, ...] | None,
728
+ next((s.args for s in steps if s.op == "select"), None),
729
+ )
730
+ cursor_name = (
731
+ str(cast(Node, node.args[3]).args[0]) if terminal == "page" else None
732
+ )
733
+ cursor_key = None
734
+ if cursor_name:
735
+ cursor_parameter = next(
736
+ p for p in declaration.parameters if p.name == cursor_name
737
+ )
738
+ cursor_key = next(
739
+ a
740
+ for a in get_args(cursor_parameter.carrier)
741
+ if isinstance(a, type) and issubclass(a, StrictModel)
742
+ )
743
+ cursor_key_name = cursor_key.__name__ if cursor_key is not None else "object"
744
+ key_components: tuple[tuple[str, int], ...] = ()
745
+ tuple_names: tuple[str, ...] = ()
746
+ nullable_fields: tuple[str, ...] = ()
747
+ nullable_owners = nullable_join_owners(steps)
748
+ if terminal == "group_count":
749
+ grouped_fields = cast(
750
+ tuple[FieldRef | Node, ...],
751
+ next((s.args for s in steps if s.op == "group"), ()),
752
+ )
753
+ selected = (*grouped_fields, Node("aggregate", ("count", None, None)))
754
+ scalar_result = selected is not None and any(
755
+ isinstance(value, Node) for value in selected
756
+ )
757
+ if scalar_result and projection is None:
758
+ assert selected is not None
759
+ specs = []
760
+ expressions = []
761
+ for ordinal, value in enumerate(selected):
762
+ alias = f"col_{ordinal}"
763
+ field_ref: object
764
+ operation: str
765
+ argument: object
766
+ if isinstance(value, FieldRef):
767
+ field_ref, operation, argument = value, "field", None
768
+ elif value.op == "aggregate":
769
+ raw_operation, field_ref, argument = value.args
770
+ operation = cast(str, raw_operation)
771
+ elif value.op == "bucket_width":
772
+ field_ref, argument = value.args
773
+ operation = "bucket_width"
774
+ else:
775
+ raise CatalogBuildError(
776
+ "WEFT_BLOCKED: unsupported selected scalar expression"
777
+ )
778
+ if field_ref is None and operation == "count":
779
+ owner, field_name, nullable = record, "", False
780
+ elif isinstance(field_ref, FieldRef):
781
+ owner = records[(field_ref.module, field_ref.element)]
782
+ matches = [
783
+ n
784
+ for n in owner.model_fields
785
+ if getattr(owner.c, n).ref == replace(field_ref, alias=None)
786
+ ]
787
+ if len(matches) != 1:
788
+ raise CatalogBuildError(
789
+ "CATALOG_STALE: scalar field differs from original generated source"
790
+ )
791
+ field_name = matches[0]
792
+ nullable = (
793
+ field_ref.module,
794
+ field_ref.element,
795
+ field_ref.alias,
796
+ ) in nullable_owners
797
+ else:
798
+ raise CatalogBuildError(
799
+ "WEFT_BLOCKED: scalar source metadata is absent"
800
+ )
801
+ if operation in ("sum", "min", "max", "avg"):
802
+ nullable = True
803
+ if operation in ("count", "count_distinct", "approx_count_distinct"):
804
+ nullable = False
805
+ specs.append((alias, owner, field_name, operation, argument, nullable))
806
+ expressions.append(
807
+ f"({alias!r}, {owner.__name__}, {field_name!r}, {operation!r}, {argument!r}, {nullable!r})"
808
+ )
809
+ result_expr = f"_Q{number}Result"
810
+ result = make_scalar_projection_model(result_expr, tuple(specs))
811
+ lines.append(
812
+ f"{result_expr} = make_scalar_projection_model({result_expr!r}, ({', '.join(expressions)},))"
813
+ )
814
+ projection_fields = tuple(selected)
815
+ projection_names = tuple(spec[0] for spec in specs)
816
+ tuple_names = projection_names
817
+ return_type = (
818
+ "tuple["
819
+ + ", ".join(
820
+ _type(result.model_fields[n].annotation, package)
821
+ for n in tuple_names
822
+ )
823
+ + "]"
824
+ )
825
+ elif projection is not None:
826
+ result = models[projection.name]
827
+ result_expr = result.__name__
828
+ return_type = result.__name__
829
+ projection_fields = projection.fields
830
+ projection_names = projection.names
831
+ elif terminal == "count":
832
+ result = create_model("_Count", __base__=StrictModel, count=(int, ...))
833
+ result_expr = f"_Q{number}Result"
834
+ return_type = "int"
835
+ projection_fields = ()
836
+ projection_names = ()
837
+ lines.extend([f"class {result_expr}(StrictModel):", " count: int", ""])
838
+ else:
839
+ refs = (
840
+ selected
841
+ if selected is not None
842
+ else tuple(
843
+ replace(getattr(record.c, n).ref, alias=record_ref.alias)
844
+ for n in record.model_fields
845
+ )
846
+ )
847
+ if terminal == "exists":
848
+ refs = record_ref.key
849
+ owner_fields = []
850
+ for ordinal, ref in enumerate(refs):
851
+ if not isinstance(ref, FieldRef):
852
+ raise CatalogBuildError(
853
+ "WEFT_BLOCKED: non-field projection metadata requires scalar result"
854
+ )
855
+ owner = records[(ref.module, ref.element)]
856
+ field = next(
857
+ n
858
+ for n in owner.model_fields
859
+ if getattr(owner.c, n).ref == replace(ref, alias=None)
860
+ )
861
+ alias = (
862
+ f"_col_{ordinal}"
863
+ if selected is not None or terminal == "exists"
864
+ else field
865
+ )
866
+ owner_fields.append((alias, owner, field))
867
+ if selected is None and terminal != "exists":
868
+ result = record
869
+ result_expr = record.__name__
870
+ return_type = record.__name__
871
+ else:
872
+ # Field names must be public Pydantic identifiers; preserve tuple order independently.
873
+ owner_fields = [(a.removeprefix("_"), o, f) for a, o, f in owner_fields]
874
+ nullable_fields = tuple(
875
+ a
876
+ for index, (a, _owner, _field) in enumerate(owner_fields)
877
+ if (cast(FieldRef, refs[index]).module, cast(FieldRef, refs[index]).element, cast(FieldRef, refs[index]).alias)
878
+ in nullable_owners
879
+ )
880
+ result = make_projection_model(
881
+ f"_Q{number}Result",
882
+ tuple(owner_fields),
883
+ nullable_fields=nullable_fields,
884
+ )
885
+ result_expr = f"_Q{number}Result"
886
+ args = ", ".join(
887
+ f"({a!r}, {o.__name__}, {f!r})" for a, o, f in owner_fields
888
+ )
889
+ lines.append(
890
+ f"{result_expr} = make_projection_model({result_expr!r}, ({args},), nullable_fields={nullable_fields!r})"
891
+ )
892
+ tuple_names = (
893
+ tuple(a for a, _, _ in owner_fields) if terminal != "exists" else ()
894
+ )
895
+ return_type = (
896
+ "tuple["
897
+ + ", ".join(
898
+ (
899
+ _type(o.model_fields[f].annotation, package)
900
+ + (" | None" if a in nullable_fields else "")
901
+ )
902
+ for a, o, f in owner_fields
903
+ )
904
+ + "]"
905
+ if terminal != "exists"
906
+ else "bool"
907
+ )
908
+ projection_fields = tuple(refs)
909
+ projection_names = tuple(a for a, _, _ in owner_fields)
910
+ related_field = None
911
+ related_row_expr = None
912
+ related_base_result = None
913
+ includes = tuple(step for step in steps if step.op == "include_keys")
914
+ if includes:
915
+ if len(includes) != 1 or terminal not in ("all", "first", "one", "get", "page") or any(step.op in ("group", "having") for step in steps):
916
+ raise CatalogBuildError("WEFT_BLOCKED: WR-A6 bounded relationship Keys require an entity-row terminal")
917
+ include = includes[0]
918
+ if len(include.args) not in (3, 4) or not isinstance(include.args[0], FieldRef) or not isinstance(include.args[2], RecordRef):
919
+ raise CatalogBuildError("CATALOG_STALE: regenerate original relationship Key metadata")
920
+ relation_ref = cast(FieldRef, include.args[0])
921
+ bound = include.args[1]
922
+ key_target = cast(RecordRef, include.args[2])
923
+ if type(bound) is not int or not 1 <= bound <= 1000:
924
+ raise CatalogBuildError("WEFT_BLOCKED: WR-A6 bounded relationship Key limit required")
925
+ if key_target.source is None or key_target.key_id is None:
926
+ raise CatalogBuildError("CATALOG_STALE: original relationship Key source missing")
927
+ identity = {"documentId": key_target.source.document_id, "coreVersion": key_target.source.core_version, "module": key_target.module, "element": key_target.element, "key": key_target.key_id}
928
+ key_module = importlib.import_module(package + ".keys")
929
+ keys = [value for value in vars(key_module).values() if isinstance(value, type) and issubclass(value, StrictModel) and getattr(value, "UMF_KEY", False) and dict(getattr(value, "KEY_IDENTITY", {})) == identity and getattr(value, "UMF_SOURCE", None) == key_target.source]
930
+ if len(keys) != 1:
931
+ raise CatalogBuildError("CATALOG_STALE: exact original relationship Key class required")
932
+ related_key_model = keys[0]
933
+ related_field = relation_ref.field + "_keys"
934
+ decoder = {"profile": "pg-related-keys-json/0.1", "bound": bound, "relationship": {"module": relation_ref.field_module, "id": relation_ref.field, "direction": include.args[3] if len(include.args) == 4 else "forward"}, "key": key_descriptor(related_key_model)}
935
+ related_row_expr = result_expr
936
+ related_base_result = result
937
+ if any(target["kind"] in ("postgresql", "lakebase") for target in targets):
938
+ related_expr = f"_Q{number}Related"
939
+ result = make_related_result_model(related_expr, result, related_key_model, related_field, decoder, record)
940
+ lines.append(f"{related_expr} = make_related_result_model({related_expr!r}, {related_row_expr}, {related_key_model.__name__}, {related_field!r}, {decoder!r}, {record.__name__})")
941
+ result_expr = related_expr
942
+ return_type = "WithKeys[" + return_type + ", " + related_key_model.__name__ + "]"
943
+ item_return_type = return_type
944
+ if terminal in ("all", "group_count"):
945
+ return_type = "list[" + return_type + "]"
946
+ elif terminal == "first":
947
+ return_type += " | None"
948
+ elif terminal == "page":
949
+ return_type = "Page[" + return_type + ", " + cursor_key_name + "]"
950
+ elif terminal == "search_top":
951
+ return_type = "SearchResult[" + return_type + "]"
952
+ argument_code = []
953
+ signature = []
954
+ argument_names = []
955
+ for parameter in declaration.parameters:
956
+ annotation = (
957
+ "Continuation[" + cursor_key_name + "] | None"
958
+ if parameter.name == cursor_name
959
+ else _type(parameter.carrier, package)
960
+ )
961
+ signature.append(
962
+ f"{parameter.name}: {annotation}"
963
+ + (" = MISSING" if parameter.optional else "")
964
+ )
965
+ argument_names.append(parameter.name)
966
+ key = next(
967
+ (
968
+ a
969
+ for a in (get_args(parameter.carrier) or (parameter.carrier,))
970
+ if isinstance(a, type) and issubclass(a, StrictModel)
971
+ ),
972
+ None,
973
+ )
974
+ argument_code.append(
975
+ f"Argument({parameter.name!r}, {annotation}, {parameter.optional!r}, {key.__name__ if key else 'None'})"
976
+ )
977
+ if terminal == "search_top":
978
+ key_module = importlib.import_module(package + ".keys")
979
+ key_models = {
980
+ n: v
981
+ for n, v in vars(key_module).items()
982
+ if isinstance(v, type)
983
+ and issubclass(v, StrictModel)
984
+ and hasattr(v, "KEY_IDENTITY")
985
+ }
986
+ search_lines, search_entries = emit_search(
987
+ compiler,
988
+ declaration,
989
+ record,
990
+ targets,
991
+ manifest,
992
+ number,
993
+ name,
994
+ result_expr,
995
+ cast(tuple[FieldRef, ...], projection_fields),
996
+ projection_names,
997
+ tuple_names,
998
+ signature,
999
+ argument_code,
1000
+ argument_names,
1001
+ return_type,
1002
+ key_models,
1003
+ )
1004
+ lines.extend(search_lines)
1005
+ entries.extend(search_entries)
1006
+ continue
1007
+ variants = []
1008
+ for vi, variant in enumerate(declaration.variants):
1009
+ parameters: dict[str, Any] = {}
1010
+ paths: list[tuple[str, str, str | None]] = []
1011
+ parameter_lines: list[str] = []
1012
+ for parameter in declaration.parameters:
1013
+ if (
1014
+ parameter.name == cursor_name
1015
+ or parameter.optional
1016
+ and parameter.name not in variant.presence
1017
+ ):
1018
+ continue
1019
+ carrier = _without_missing(parameter.carrier)
1020
+ if parameter.key_components:
1021
+ key = next(
1022
+ a
1023
+ for a in (get_args(carrier) or (carrier,))
1024
+ if isinstance(a, type) and issubclass(a, StrictModel)
1025
+ )
1026
+ for component in parameter.key_components:
1027
+ flat = parameter.name + "__" + component
1028
+ parameters[flat] = (key.model_fields[component].annotation, ...)
1029
+ paths.append((flat, parameter.name, component))
1030
+ parameter_lines.append(
1031
+ f" {flat}: {_type(key.model_fields[component].annotation, package)}"
1032
+ )
1033
+ else:
1034
+ parameters[parameter.name] = (carrier, ...)
1035
+ paths.append((parameter.name, parameter.name, None))
1036
+ parameter_lines.append(
1037
+ f" {parameter.name}: {_type(carrier, package)}"
1038
+ )
1039
+ params_name = f"_Q{number}P{vi}"
1040
+ params = create_model(params_name, __base__=StrictModel, **parameters)
1041
+ type.__setattr__(params, "UMF_BUNDLE_INPUT_DIGEST", manifest["inputDigest"])
1042
+ type.__setattr__(params, "UMF_RUNTIME_ABI", RUNTIME_IDENTITY)
1043
+ type.__setattr__(params, "UMF_SOURCE", record.UMF_SOURCE)
1044
+ lines.extend(
1045
+ [
1046
+ f"class {params_name}(StrictModel):",
1047
+ *(parameter_lines or [" pass"]),
1048
+ f" UMF_BUNDLE_INPUT_DIGEST: ClassVar[str] = {manifest['inputDigest']!r}",
1049
+ f" UMF_RUNTIME_ABI: ClassVar[tuple[str,str,str]] = {RUNTIME_IDENTITY!r}",
1050
+ f" UMF_SOURCE: ClassVar[object] = {record.__name__}.UMF_SOURCE",
1051
+ "",
1052
+ ]
1053
+ )
1054
+ # Every variant carries identical projections; only explicit presence changes predicates.
1055
+ current = variant
1056
+ if projection is None and terminal != "count":
1057
+ current = replace(
1058
+ variant,
1059
+ node=Node(
1060
+ node.op,
1061
+ (
1062
+ variant.node.args[0],
1063
+ tuple(
1064
+ s
1065
+ for s in cast(tuple[Node, ...], variant.node.args[1])
1066
+ if s.op != "select"
1067
+ )
1068
+ + (
1069
+ Node(
1070
+ "into",
1071
+ (
1072
+ ProjectionRef(
1073
+ package + ".models",
1074
+ result.__name__,
1075
+ projection_fields,
1076
+ projection_names,
1077
+ ),
1078
+ ),
1079
+ ),
1080
+ ),
1081
+ *variant.node.args[2:],
1082
+ ),
1083
+ ),
1084
+ )
1085
+ for target_index, target in enumerate(targets):
1086
+ kind = target["kind"]
1087
+ entry_result = result
1088
+ entry_result_expr = result_expr
1089
+ if related_field is not None and kind not in ("postgresql", "lakebase", "truss", "ashlar"):
1090
+ raise CatalogBuildError("WEFT_BLOCKED: WR-A6 target-specific bounded relationship-Key output profile required")
1091
+ if snapshot and kind not in ("spark-delta", "unity-catalog", "ashlar"):
1092
+ raise CatalogBuildError(
1093
+ "SNAPSHOT_UNSUPPORTED: selected target has no admitted snapshot pages"
1094
+ )
1095
+ profile = {
1096
+ "postgresql": "postgresql18",
1097
+ "lakebase": "lakebase18",
1098
+ "spark-delta": "spark-delta4",
1099
+ }.get(kind)
1100
+ engine = kind in ("truss", "ashlar")
1101
+ if profile is None and not engine:
1102
+ raise CatalogBuildError(
1103
+ "WEFT_BLOCKED: target has no admitted read compiler"
1104
+ )
1105
+ binding = target["binding"]
1106
+ engine_page = replace(current, node=Node("all", current.node.args[:2])) if engine and terminal == "page" else None
1107
+ related = render_related_logical(engine_page or current, binding=binding, owner_bound=engine_page is not None)
1108
+ logical = related.target_sql if related is not None else render_logical(current, binding=binding)
1109
+ if terminal == "count":
1110
+ logical = logical.replace(
1111
+ "SELECT COUNT(*) FROM", 'SELECT COUNT(*) AS "count" FROM', 1
1112
+ )
1113
+ entry_class = "CatalogRead"
1114
+ if engine:
1115
+ if terminal == "page" and related is None:
1116
+ logical = render_logical(
1117
+ replace(current, node=Node("all", current.node.args[:2])),
1118
+ binding=binding,
1119
+ owner_bound=True,
1120
+ )
1121
+ method = target.get("engineCompiler")
1122
+ if method not in (
1123
+ {"truss-runtime", "truss-runtime-binary"}
1124
+ if kind == "truss"
1125
+ else {
1126
+ "registered",
1127
+ "ashlar-spark4",
1128
+ "ashlar-spark4-fields",
1129
+ "ashlar-spark4-sdk",
1130
+ "ashlar-spark4-sdk-pages",
1131
+ "ashlar-dbsql-20261016",
1132
+ "ashlar-spark4-pages",
1133
+ "ashlar-dbsql-20261016-pages",
1134
+ }
1135
+ ):
1136
+ raise CatalogBuildError(
1137
+ "explicit engine compiler selection required"
1138
+ )
1139
+ if (
1140
+ terminal == "page"
1141
+ and kind == "ashlar"
1142
+ and method
1143
+ not in ("ashlar-spark4-pages", "ashlar-dbsql-20261016-pages", "ashlar-spark4-sdk-pages")
1144
+ ):
1145
+ raise CatalogBuildError(
1146
+ "WEFT_BLOCKED: separately registered original Ashlar page compiler required"
1147
+ )
1148
+ original = target.get("engineRequests", {}).get(
1149
+ name + ":" + str(vi)
1150
+ )
1151
+ if type(original) is not dict or original.get("sql") != logical:
1152
+ raise CatalogBuildError(
1153
+ "original admitted engine SQL must equal the captured declaration"
1154
+ )
1155
+ native = original.get("target", {})
1156
+ if any(
1157
+ native.get(k) != target[k]
1158
+ for k in ("backendId", "backendVersion", "targetProfile")
1159
+ ):
1160
+ raise CatalogBuildError("original engine target differs")
1161
+ if not original.get("modules") or any(
1162
+ m.get("documentJson") != binding["modelJson"]
1163
+ for m in original["modules"]
1164
+ ):
1165
+ raise CatalogBuildError(
1166
+ "original engine model differs from selected logical binding"
1167
+ )
1168
+ navigation: dict[str, Any] = {
1169
+ "related_source": {**original, "sql": related.source_sql},
1170
+ "relationship": related.relationship,
1171
+ } if related is not None else {}
1172
+ if method == "truss-runtime-binary" and related is not None:
1173
+ raise CatalogBuildError("WEFT_BLOCKED: explicit Truss binary profile does not admit navigation")
1174
+ successor_engine = method in ("ashlar-spark4-sdk", "ashlar-spark4-sdk-pages", "truss-runtime-binary")
1175
+ if successor_engine:
1176
+ if terminal == "page":
1177
+ navigation["selected_key"] = _engine_selected_key(record_ref)
1178
+ if method != "truss-runtime-binary" and terminal != "page" and any(step.op == "order" for step in current.node.args[1]):
1179
+ navigation["order_key"] = _engine_selected_key(record_ref)
1180
+ if related is not None:
1181
+ source_step = next(step for step in current.node.args[1] if step.op == "related")
1182
+ source_ref = source_step.args[0]
1183
+ navigation["source_selected_key"] = _engine_selected_key(cast(RecordRef, source_ref))
1184
+ if related_field is not None:
1185
+ original_program = EngineRead.compile_original(
1186
+ compiler, original, method=method,
1187
+ page_size=cast(int, node.args[2]) if terminal == "page" else None,
1188
+ **navigation,
1189
+ )
1190
+ original_outputs = program_json(original_program).get("outputs")
1191
+ candidates = [output for output in original_outputs if type(output) is dict and output.get("name") == related_field] if type(original_outputs) is list else []
1192
+ if len(candidates) != 1 or candidates[0].get("carrier") != "related-keys" or candidates[0].get("nullable") is not False:
1193
+ raise CatalogBuildError("WEFT_BLOCKED: WR-A6 original engine related-Key output descriptor required")
1194
+ engine_decoder = validate_decoder(candidates[0].get("decoder"), related_key_model)
1195
+ if any(engine_decoder[key] != decoder[key] for key in ("bound", "relationship", "key")) or related_base_result is None:
1196
+ raise CatalogBuildError("CATALOG_STALE: original engine relationship or Key differs from captured declaration")
1197
+ entry_result_expr = f"_Q{number}RelatedE{vi}_{target_index}"
1198
+ entry_result = make_related_result_model(entry_result_expr, related_base_result, related_key_model, related_field, engine_decoder, record)
1199
+ lines.append(f"{entry_result_expr} = make_related_result_model({entry_result_expr!r}, {related_row_expr}, {related_key_model.__name__}, {related_field!r}, {engine_decoder!r}, {record.__name__})")
1200
+ compiled: CatalogRead[Any, Any] = EngineRead.from_original(original_program, parameters=params, result=entry_result)
1201
+ else:
1202
+ compiled = EngineRead.build(
1203
+ compiler,
1204
+ original,
1205
+ parameters=params,
1206
+ result=result,
1207
+ method=method,
1208
+ page_size=cast(int, node.args[2])
1209
+ if terminal == "page"
1210
+ else None,
1211
+ **navigation,
1212
+ )
1213
+ entry_class = "EngineRead"
1214
+ else:
1215
+ try:
1216
+ compiled = ReviewedSQL(
1217
+ logical, params, result, 1000, keyset=terminal == "page"
1218
+ ).build(
1219
+ compiler,
1220
+ target=cast(str, profile),
1221
+ binding=binding,
1222
+ snapshots=target.get("snapshots"),
1223
+ snapshot=snapshot,
1224
+ stream_page_size=terminal == "page",
1225
+ related_source=related.source_sql if related is not None else None,
1226
+ related_relationship=related.relationship if related is not None else None,
1227
+ )
1228
+ except ReadBuildError as error:
1229
+ if _requests_approximate_distinct(node):
1230
+ raise CatalogBuildError(
1231
+ "WEFT_BLOCKED: WR-A10 approximate distinct; "
1232
+ + str(error)
1233
+ ) from error
1234
+ raise
1235
+ if _requests_approximate_distinct(node):
1236
+ require_approximate_profile(compiled.artifact(), profile)
1237
+ context = _json(
1238
+ {
1239
+ "inputDigest": manifest["inputDigest"],
1240
+ "entryName": name,
1241
+ "presence": variant.presence,
1242
+ "targetId": target["id"],
1243
+ "configurationSha256": _sha(_json(configuration).encode()),
1244
+ **({"selectedKey": navigation["selected_key"]} if engine and successor_engine and terminal == "page" else {}),
1245
+ **({"sourceSelectedKey": navigation["source_selected_key"]} if engine and successor_engine and related is not None else {}),
1246
+ **({"orderKey": navigation["order_key"]} if engine and successor_engine and "order_key" in navigation else {}),
1247
+ }
1248
+ )
1249
+ compiled = replace(compiled, context_json=context)
1250
+ if cursor_key is not None:
1251
+ ordering = json.loads(compiled.artifact_json).get("cursorOrdering")
1252
+ if engine:
1253
+ engine_program = cast(EngineRead[Any, Any], compiled).artifact()
1254
+ ordered_page = engine_program.get("page") if engine_program["version"] == "weft.engine-page/0.2" and engine_program["compiler"] == "ashlar-spark4-sdk-pages" else None
1255
+ native_key = ordered_page["key"] if ordered_page is not None else engine_program["artifact"]["logicalPlan"]["pageKey"]
1256
+ key_identity = dict(cursor_parameter.key_identity)
1257
+ fields = getattr(cursor_key, "UMF_FIELDS", ())
1258
+ if (
1259
+ native_key["id"] != key_identity["key"]
1260
+ or key_identity["module"] != record_ref.module
1261
+ or key_identity["element"] != record_ref.element
1262
+ or [
1263
+ (f["documentId"], f["module"], f["element"])
1264
+ for f in native_key["fields"]
1265
+ ]
1266
+ != [
1267
+ (key_identity["documentId"], m, e) for m, e, _ in fields
1268
+ ]
1269
+ ):
1270
+ raise CatalogBuildError(
1271
+ "WEFT_BLOCKED: native authored page Key differs from declared Key"
1272
+ )
1273
+ ordering = [
1274
+ {
1275
+ "table": [
1276
+ record_ref.logical_namespace,
1277
+ record_ref.logical_name,
1278
+ ],
1279
+ "field": getattr(
1280
+ record.c, python_name
1281
+ ).ref.logical_name,
1282
+ }
1283
+ for _, _, python_name in fields
1284
+ ]
1285
+ if not isinstance(ordering, list):
1286
+ raise CatalogBuildError(
1287
+ "WEFT_BLOCKED: complete ordering provenance required"
1288
+ )
1289
+ components = []
1290
+ for key_ordinal, key_field in enumerate(cursor_key.model_fields):
1291
+ if engine and ordered_page is not None:
1292
+ components.append((key_field, ordered_page["keySlots"][key_ordinal]))
1293
+ continue
1294
+ logical = getattr(record.c, key_field).ref.logical_name
1295
+ matches = [
1296
+ i
1297
+ for i, item in enumerate(ordering)
1298
+ if item["table"]
1299
+ == [
1300
+ record.objects.ref.logical_namespace,
1301
+ record.objects.ref.logical_name,
1302
+ ]
1303
+ and item["field"] == logical
1304
+ ]
1305
+ if len(matches) != 1:
1306
+ raise CatalogBuildError(
1307
+ "WEFT_BLOCKED: exact selected Key absent from ordering"
1308
+ )
1309
+ components.append((key_field, matches[0]))
1310
+ key_components = tuple(components)
1311
+ digest = (
1312
+ original["target"]["bindingSha256"]
1313
+ if engine
1314
+ else _sha(_json(binding).encode())
1315
+ )
1316
+ platform = tuple(
1317
+ (p["name"], tuple(str(v) for v in p["versions"]))
1318
+ for p in target["platform"]
1319
+ )
1320
+ pin = (
1321
+ kind,
1322
+ target["backendId"],
1323
+ target["backendVersion"],
1324
+ target["targetProfile"],
1325
+ digest,
1326
+ platform,
1327
+ )
1328
+ variants.append(
1329
+ f"ReadVariant({variant.presence!r}, TargetPin{pin!r}, {entry_class}({compiled.artifact_json!r}, {params_name}, {entry_result_expr}, context_json={context!r}), {tuple(paths)!r})"
1330
+ )
1331
+ entries.append(
1332
+ {
1333
+ "name": name,
1334
+ "kind": "query",
1335
+ "targetId": target["id"],
1336
+ "presence": variant.presence,
1337
+ "artifact": json.loads(compiled.artifact_json),
1338
+ "pin": pin,
1339
+ "parameters": paths,
1340
+ }
1341
+ )
1342
+ plan = f"_Q{number}"
1343
+ argument_tuple = (
1344
+ "(" + ", ".join(argument_code) + ("," if argument_code else "") + ")"
1345
+ )
1346
+ lines.extend(
1347
+ [
1348
+ f"{plan} = ReadPlan({name!r}, {terminal!r}, {argument_tuple}, ({', '.join(variants)},), {tuple_names!r}, {cursor_name!r}, {cursor_key.__name__ if cursor_key else 'None'}, {key_components!r}" + (f", related_field={related_field!r}, related_row_model={related_row_expr}" if related_field is not None else "") + ")",
1349
+ "",
1350
+ ]
1351
+ )
1352
+ arguments = "{" + ", ".join(repr(n) + ": " + n for n in argument_names) + "}"
1353
+ # Required parameters precede optional parameters without changing declaration binding.
1354
+ ordered = [s for s in signature if " = MISSING" not in s] + [
1355
+ s for s in signature if " = MISSING" in s
1356
+ ]
1357
+ tail = ", *, " + ", ".join(ordered + ["timeout: timedelta | None = None"])
1358
+ for target_type, returned in [
1359
+ ("ReadTarget", return_type),
1360
+ ("AsyncReadTarget", "Awaitable[" + return_type + "]"),
1361
+ ]:
1362
+ lines.extend(
1363
+ [
1364
+ "@overload",
1365
+ f"def {name}(target: {target_type}{tail}) -> {returned}: ...",
1366
+ ]
1367
+ )
1368
+ combined = f"{return_type} | Awaitable[{return_type}]"
1369
+ lines.extend(
1370
+ [
1371
+ f"def {name}(target: ReadTarget | AsyncReadTarget{tail}) -> {combined}:",
1372
+ f" return cast({combined}, run_query({plan}, target, {arguments}, timeout=timeout))",
1373
+ "",
1374
+ ]
1375
+ )
1376
+ if terminal == "page":
1377
+ item_type = item_return_type
1378
+ stream_tail = ", *, " + ", ".join(
1379
+ ordered
1380
+ + [
1381
+ "max_rows: int",
1382
+ "page_size: int | None = None",
1383
+ "timeout: timedelta | None = None",
1384
+ ]
1385
+ )
1386
+ for target_type, returned in [
1387
+ ("ReadTarget", f"Generator[{item_type},None,None]"),
1388
+ ("AsyncReadTarget", f"AsyncGenerator[{item_type},None]"),
1389
+ ]:
1390
+ lines.extend(
1391
+ [
1392
+ "@overload",
1393
+ f"def {name}_stream(target: {target_type}{stream_tail}) -> {returned}: ...",
1394
+ ]
1395
+ )
1396
+ lines.extend(
1397
+ [
1398
+ f"def {name}_stream(target: ReadTarget | AsyncReadTarget{stream_tail}) -> Generator[{item_type},None,None] | AsyncGenerator[{item_type},None]:",
1399
+ f" return cast(Generator[{item_type},None,None] | AsyncGenerator[{item_type},None], run_stream({plan},target,{arguments},max_rows=max_rows,page_size=page_size,timeout=timeout))",
1400
+ "",
1401
+ ]
1402
+ )
1403
+ catalog = {
1404
+ "contract": "umf-access-catalog/0.1",
1405
+ "inputDigest": manifest["inputDigest"],
1406
+ "runtimeAbi": manifest["runtimeAbi"],
1407
+ "modules": provenance,
1408
+ "configuration": configuration,
1409
+ "buildProvenance": configuration_provenance,
1410
+ "entries": entries,
1411
+ }
1412
+ outputs = {
1413
+ "queries.py": ("\n".join(lines) + "\n").encode(),
1414
+ "_umf/catalog.json": (_json(catalog) + "\n").encode(),
1415
+ "_umf/privileges.json": (
1416
+ _json(privilege_report(targets, entries)) + "\n"
1417
+ ).encode(),
1418
+ }
1419
+ stage = {
1420
+ "contract": "umf-access-catalog/0.1",
1421
+ "inputDigest": manifest["inputDigest"],
1422
+ "runtimeAbi": manifest["runtimeAbi"],
1423
+ "inventory": [
1424
+ {"path": name, "sha256": _sha(data)}
1425
+ for name, data in sorted(outputs.items())
1426
+ ],
1427
+ }
1428
+ outputs["_umf/catalog-manifest.json"] = (_json(stage) + "\n").encode()
1429
+ return outputs
1430
+
1431
+
1432
+ def publish_catalog(
1433
+ root: Path, package: str, outputs: dict[str, bytes], *, check: bool = False
1434
+ ) -> None:
1435
+ with _own_destination(root, package):
1436
+ _publish_catalog_owned(root, package, outputs, check=check)
1437
+
1438
+
1439
+ def _requests_approximate_distinct(value: object) -> bool:
1440
+ if isinstance(value, Node):
1441
+ return (
1442
+ value.op == "aggregate"
1443
+ and len(value.args) == 3
1444
+ and value.args[0] == "approx_count_distinct"
1445
+ ) or any(_requests_approximate_distinct(child) for child in value.args)
1446
+ if isinstance(value, tuple):
1447
+ return any(_requests_approximate_distinct(child) for child in value)
1448
+ return False
1449
+
1450
+
1451
+ def _check_publication_generation(
1452
+ root: Path, package: str, outputs: dict[str, bytes]
1453
+ ) -> None:
1454
+ if set(outputs) != set(OWNED):
1455
+ raise CatalogBuildError("exact owned stage-two paths required")
1456
+ manifest = json.loads(_read(root / package / "_umf/manifest.json"))
1457
+ identity = {key: manifest.get(key) for key in ("inputDigest", "runtimeAbi")}
1458
+ if (
1459
+ identity["runtimeAbi"]
1460
+ != dict(zip(("distribution", "version", "abi"), RUNTIME_IDENTITY, strict=True))
1461
+ or type(identity["inputDigest"]) is not str
1462
+ ):
1463
+ raise CatalogBuildError(
1464
+ "CATALOG_STALE: stage-one identity differs", code="CATALOG_STALE"
1465
+ )
1466
+ for name in ("_umf/catalog.json", "_umf/catalog-manifest.json"):
1467
+ candidate = json.loads(outputs[name])
1468
+ if any(candidate.get(key) != value for key, value in identity.items()):
1469
+ raise CatalogBuildError(
1470
+ "CATALOG_STALE: candidate belongs to another stage-one generation",
1471
+ code="CATALOG_STALE",
1472
+ )
1473
+ inventory = manifest.get("inventory")
1474
+ if type(inventory) is not list:
1475
+ raise CatalogBuildError(
1476
+ "CATALOG_STALE: stage-one inventory required", code="CATALOG_STALE"
1477
+ )
1478
+ seen: set[str] = set()
1479
+ for item in inventory:
1480
+ if (
1481
+ type(item) is not dict
1482
+ or set(item) != {"path", "sha256"}
1483
+ or type(item["path"]) is not str
1484
+ ):
1485
+ raise CatalogBuildError(
1486
+ "CATALOG_STALE: invalid stage-one inventory", code="CATALOG_STALE"
1487
+ )
1488
+ relative = Path(item["path"])
1489
+ if (
1490
+ relative.is_absolute()
1491
+ or ".." in relative.parts
1492
+ or not relative.parts
1493
+ or str(relative) != item["path"]
1494
+ or "\\" in item["path"]
1495
+ or relative.parts[0] != package
1496
+ or str(relative.relative_to(package)) in OWNED
1497
+ or item["path"] in seen
1498
+ ):
1499
+ raise CatalogBuildError(
1500
+ "CATALOG_STALE: unsafe stage-one inventory", code="CATALOG_STALE"
1501
+ )
1502
+ seen.add(item["path"])
1503
+ path = root / relative
1504
+ if (
1505
+ any(parent.is_symlink() for parent in (path, *path.parents))
1506
+ or _sha(_read(path)) != item["sha256"]
1507
+ ):
1508
+ raise CatalogBuildError(
1509
+ "CATALOG_STALE: stage-one source drift", code="CATALOG_STALE"
1510
+ )
1511
+
1512
+
1513
+ def _publication_tree(destination: Path) -> dict[str, bytes]:
1514
+ files: dict[str, bytes] = {}
1515
+ for path in sorted(destination.rglob("*")):
1516
+ if path.is_symlink():
1517
+ raise CatalogBuildError("package symlinks refuse publication")
1518
+ if path.is_file():
1519
+ files[str(path.relative_to(destination))] = _read(path)
1520
+ return files
1521
+
1522
+
1523
+ def _publish_catalog_owned(
1524
+ root: Path, package: str, outputs: dict[str, bytes], *, check: bool = False
1525
+ ) -> None:
1526
+ destination = root / package
1527
+ if any(path.is_symlink() for path in (destination, *destination.parents)):
1528
+ raise CatalogBuildError("package symlinks refuse publication")
1529
+ _check_publication_generation(root, package, outputs)
1530
+ previous = destination / "_umf/catalog-manifest.json"
1531
+ if previous.exists():
1532
+ inventory = json.loads(_read(previous))["inventory"]
1533
+ expected = set(OWNED) - {"_umf/catalog-manifest.json"}
1534
+ if (
1535
+ type(inventory) is not list
1536
+ or len(inventory) != len(expected)
1537
+ or any(
1538
+ type(item) is not dict
1539
+ or set(item) != {"path", "sha256"}
1540
+ or type(item["path"]) is not str
1541
+ for item in inventory
1542
+ )
1543
+ or {item["path"] for item in inventory} != expected
1544
+ or any(
1545
+ _sha(_read(destination / item["path"])) != item["sha256"]
1546
+ for item in inventory
1547
+ )
1548
+ ):
1549
+ raise CatalogBuildError("catalog hand edit or unsafe inventory")
1550
+ elif any((destination / path).exists() for path in OWNED):
1551
+ raise CatalogBuildError("unowned existing catalog output")
1552
+ if check:
1553
+ if any(
1554
+ not (destination / name).is_file() or _read(destination / name) != data
1555
+ for name, data in outputs.items()
1556
+ ):
1557
+ raise CatalogBuildError("CATALOG_STALE: regenerated bytes differ")
1558
+ return
1559
+ if set(outputs) != set(OWNED) or destination.is_symlink():
1560
+ raise CatalogBuildError("exact owned stage-two paths required")
1561
+ before = _publication_tree(destination)
1562
+ stage = Path(tempfile.mkdtemp(prefix=".umf-catalog-", dir=root))
1563
+ candidate = stage / package
1564
+ backup = stage / "original"
1565
+ moved = False
1566
+ installed = False
1567
+ try:
1568
+ shutil.copytree(destination, candidate)
1569
+ for name, data in outputs.items():
1570
+ path = candidate / name
1571
+ path.parent.mkdir(parents=True, exist_ok=True)
1572
+ path.write_bytes(data)
1573
+ if _publication_tree(destination) != before:
1574
+ raise CatalogBuildError(
1575
+ "output changed while staging", code="OUTPUT_CHANGED"
1576
+ )
1577
+ os.replace(destination, backup)
1578
+ moved = True
1579
+ try:
1580
+ os.replace(candidate, destination)
1581
+ installed = True
1582
+ except BaseException:
1583
+ try:
1584
+ os.replace(backup, destination)
1585
+ moved = False
1586
+ except BaseException as restore_error:
1587
+ raise CatalogBuildError(
1588
+ "replacement and restoration failed; original package retained",
1589
+ code="WRITE_UNRESOLVED",
1590
+ destination=str(destination.resolve()),
1591
+ backup=str(backup.resolve()),
1592
+ staging=str(stage.resolve()),
1593
+ unresolved=True,
1594
+ ) from restore_error
1595
+ raise
1596
+ finally:
1597
+ if not moved or installed:
1598
+ shutil.rmtree(stage)
1599
+
1600
+
1601
+ def main() -> int:
1602
+ parser = argparse.ArgumentParser(description=__doc__)
1603
+ parser.add_argument("operation", choices=["catalog"])
1604
+ parser.add_argument("--config", type=Path, required=True)
1605
+ parser.add_argument("--root", type=Path, default=Path.cwd())
1606
+ parser.add_argument("--check", action="store_true")
1607
+ args = parser.parse_args()
1608
+ try:
1609
+ weft = cast(ReadCompiler, importlib.import_module("weft"))
1610
+ root = args.root.resolve()
1611
+ config = program_json(_read(args.config).decode("utf-8"))
1612
+ with _own_destination(root, config.get("package")):
1613
+ outputs = _compile_catalog_owned(config, root, weft)
1614
+ _publish_catalog_owned(root, config["package"], outputs, check=args.check)
1615
+ print(_json({"status": "pass", "files": list(OWNED)}))
1616
+ return 0
1617
+ except (ValueError, KeyError, TypeError) as error:
1618
+ details: dict[str, Any] = {"status": "refused", "reason": str(error)}
1619
+ if isinstance(error, CatalogBuildError) and error.code is not None:
1620
+ details.update(code=error.code, **error.metadata)
1621
+ print(_json(details), file=sys.stderr)
1622
+ return 1
1623
+
1624
+
1625
+ if __name__ == "__main__":
1626
+ raise SystemExit(main())