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
umf_access/bulk.py ADDED
@@ -0,0 +1,227 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Bulk plan delegation; engines retain original control and attempt authority."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+ from datetime import timedelta
8
+ from typing import Generic, Protocol, TypeVar
9
+
10
+ from .protocols import NativeOutcomeDetails, Receipt
11
+ from .types import StrictModel
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class BulkPreview:
16
+ selected: tuple[StrictModel, ...]
17
+ statement_summary: str
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class BulkOutcome:
22
+ selected: int
23
+ changed: int
24
+ receipt: Receipt
25
+ original: NativeOutcomeDetails
26
+
27
+
28
+ class AtomicBulkExecutor(Protocol):
29
+ def preview(self, *, timeout: timedelta | None = None) -> BulkPreview: ...
30
+ def execute(self, *, timeout: timedelta | None = None) -> BulkOutcome: ...
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class AtomicBulkPlan:
35
+ executor: AtomicBulkExecutor
36
+
37
+ def preview(self, *, timeout: timedelta | None = None) -> BulkPreview:
38
+ return self.executor.preview(timeout=timeout)
39
+
40
+ def execute(self, *, timeout: timedelta | None = None) -> BulkOutcome:
41
+ return self.executor.execute(timeout=timeout)
42
+
43
+
44
+ class AsyncAtomicBulkExecutor(Protocol):
45
+ async def preview(self, *, timeout: timedelta | None = None) -> BulkPreview: ...
46
+ async def execute(self, *, timeout: timedelta | None = None) -> BulkOutcome: ...
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class AsyncAtomicBulkPlan:
51
+ executor: AsyncAtomicBulkExecutor
52
+
53
+ async def preview(self, *, timeout: timedelta | None = None) -> BulkPreview:
54
+ return await self.executor.preview(timeout=timeout)
55
+
56
+ async def execute(self, *, timeout: timedelta | None = None) -> BulkOutcome:
57
+ return await self.executor.execute(timeout=timeout)
58
+
59
+
60
+ AttemptT_contra = TypeVar("AttemptT_contra", contravariant=True)
61
+ ArtifactT_contra = TypeVar("ArtifactT_contra", contravariant=True)
62
+ RecoveryT_contra = TypeVar("RecoveryT_contra", contravariant=True)
63
+ SealT_co = TypeVar("SealT_co", covariant=True)
64
+ SubmitT_co = TypeVar("SubmitT_co", covariant=True)
65
+ ControlT_co = TypeVar("ControlT_co", covariant=True)
66
+
67
+
68
+ class ManifestBulkExecutor(
69
+ Protocol[
70
+ AttemptT_contra,
71
+ ArtifactT_contra,
72
+ RecoveryT_contra,
73
+ SealT_co,
74
+ SubmitT_co,
75
+ ControlT_co,
76
+ ]
77
+ ):
78
+ """Original engine carriers, including every refusal and unknown member.
79
+
80
+ The engine issues attempts and artifacts, checks current authorization and
81
+ blocks fresh mutation after an unknown acknowledgement. Recovery delegates
82
+ to its original operation; it must never repeat seal or submit.
83
+ """
84
+
85
+ def preview(self, *, timeout: timedelta | None = None) -> BulkPreview: ...
86
+ def seal(
87
+ self, *, attempt: AttemptT_contra, timeout: timedelta | None = None
88
+ ) -> SealT_co: ...
89
+ def submit(
90
+ self,
91
+ sealed: ArtifactT_contra,
92
+ *,
93
+ submission_key: str,
94
+ attempt: AttemptT_contra,
95
+ timeout: timedelta | None = None,
96
+ ) -> SubmitT_co: ...
97
+ def recover_control(
98
+ self, recovery: RecoveryT_contra, *, timeout: timedelta | None = None
99
+ ) -> ControlT_co: ...
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class ManifestBulkPlan(
104
+ Generic[
105
+ AttemptT_contra,
106
+ ArtifactT_contra,
107
+ RecoveryT_contra,
108
+ SealT_co,
109
+ SubmitT_co,
110
+ ControlT_co,
111
+ ]
112
+ ):
113
+ """Typed view of an engine-owned plan; no control result is reconstructed.
114
+
115
+ Host-native attempt, sealed artifact, recovery and complete result types
116
+ remain generic so this library cannot invent authority or discard extensions.
117
+ The host retains its original status/review/lookup/reconcile/cancel client.
118
+ """
119
+
120
+ executor: ManifestBulkExecutor[
121
+ AttemptT_contra,
122
+ ArtifactT_contra,
123
+ RecoveryT_contra,
124
+ SealT_co,
125
+ SubmitT_co,
126
+ ControlT_co,
127
+ ]
128
+
129
+ def preview(self, *, timeout: timedelta | None = None) -> BulkPreview:
130
+ return self.executor.preview(timeout=timeout)
131
+
132
+ def seal(
133
+ self, *, attempt: AttemptT_contra, timeout: timedelta | None = None
134
+ ) -> SealT_co:
135
+ return self.executor.seal(attempt=attempt, timeout=timeout)
136
+
137
+ def submit(
138
+ self,
139
+ sealed: ArtifactT_contra,
140
+ *,
141
+ submission_key: str,
142
+ attempt: AttemptT_contra,
143
+ timeout: timedelta | None = None,
144
+ ) -> SubmitT_co:
145
+ return self.executor.submit(
146
+ sealed, submission_key=submission_key, attempt=attempt, timeout=timeout
147
+ )
148
+
149
+ def recover_control(
150
+ self, recovery: RecoveryT_contra, *, timeout: timedelta | None = None
151
+ ) -> ControlT_co:
152
+ return self.executor.recover_control(recovery, timeout=timeout)
153
+
154
+
155
+ class AsyncManifestBulkExecutor(
156
+ Protocol[
157
+ AttemptT_contra,
158
+ ArtifactT_contra,
159
+ RecoveryT_contra,
160
+ SealT_co,
161
+ SubmitT_co,
162
+ ControlT_co,
163
+ ]
164
+ ):
165
+ async def preview(self, *, timeout: timedelta | None = None) -> BulkPreview: ...
166
+ async def seal(
167
+ self, *, attempt: AttemptT_contra, timeout: timedelta | None = None
168
+ ) -> SealT_co: ...
169
+ async def submit(
170
+ self,
171
+ sealed: ArtifactT_contra,
172
+ *,
173
+ submission_key: str,
174
+ attempt: AttemptT_contra,
175
+ timeout: timedelta | None = None,
176
+ ) -> SubmitT_co: ...
177
+ async def recover_control(
178
+ self, recovery: RecoveryT_contra, *, timeout: timedelta | None = None
179
+ ) -> ControlT_co: ...
180
+
181
+
182
+ @dataclass(frozen=True)
183
+ class AsyncManifestBulkPlan(
184
+ Generic[
185
+ AttemptT_contra,
186
+ ArtifactT_contra,
187
+ RecoveryT_contra,
188
+ SealT_co,
189
+ SubmitT_co,
190
+ ControlT_co,
191
+ ]
192
+ ):
193
+ """Async original-carrier delegation; cancellation never starts another call."""
194
+
195
+ executor: AsyncManifestBulkExecutor[
196
+ AttemptT_contra,
197
+ ArtifactT_contra,
198
+ RecoveryT_contra,
199
+ SealT_co,
200
+ SubmitT_co,
201
+ ControlT_co,
202
+ ]
203
+
204
+ async def preview(self, *, timeout: timedelta | None = None) -> BulkPreview:
205
+ return await self.executor.preview(timeout=timeout)
206
+
207
+ async def seal(
208
+ self, *, attempt: AttemptT_contra, timeout: timedelta | None = None
209
+ ) -> SealT_co:
210
+ return await self.executor.seal(attempt=attempt, timeout=timeout)
211
+
212
+ async def submit(
213
+ self,
214
+ sealed: ArtifactT_contra,
215
+ *,
216
+ submission_key: str,
217
+ attempt: AttemptT_contra,
218
+ timeout: timedelta | None = None,
219
+ ) -> SubmitT_co:
220
+ return await self.executor.submit(
221
+ sealed, submission_key=submission_key, attempt=attempt, timeout=timeout
222
+ )
223
+
224
+ async def recover_control(
225
+ self, recovery: RecoveryT_contra, *, timeout: timedelta | None = None
226
+ ) -> ControlT_co:
227
+ return await self.executor.recover_control(recovery, timeout=timeout)
@@ -0,0 +1,23 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Public, dependency-free canonical JSON rendering used by native modules."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+
9
+ def canonical_json(value: Any) -> str:
10
+ # The Weft owner uses UTF-16 ordering, including non-BMP identifiers.
11
+ def ordered(item: Any) -> Any:
12
+ if isinstance(item, dict):
13
+ return {
14
+ key: ordered(item[key])
15
+ for key in sorted(item, key=lambda key: key.encode("utf-16-be"))
16
+ }
17
+ if isinstance(item, list):
18
+ return [ordered(v) for v in item]
19
+ return item
20
+
21
+ return json.dumps(
22
+ ordered(value), ensure_ascii=False, separators=(",", ":"), allow_nan=False
23
+ )
umf_access/capture.py ADDED
@@ -0,0 +1,410 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Pure in-memory capture of explicitly supplied declarations, never module scanning."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import inspect
7
+ import json
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass, fields, is_dataclass
10
+ from datetime import date, datetime
11
+ from decimal import Decimal
12
+ from itertools import combinations
13
+ from types import UnionType
14
+ from typing import Any, Union, cast, get_args, get_origin, get_type_hints
15
+
16
+ from pydantic import BaseModel
17
+
18
+ from .dsl import GeneratedSource, Join, Param, Terminal
19
+ from .dsl._context import CURRENT, CaptureContext
20
+
21
+ # Explicit public re-export is required by static consumers.
22
+ from .dsl._context import CaptureError as CaptureError # noqa: PLC0414
23
+ from .dsl._nodes import (
24
+ FieldRef,
25
+ KeyLiteral,
26
+ Node,
27
+ RecordRef,
28
+ key_identity,
29
+ )
30
+ from .dsl._nodes import KeyLiteral as CapturedKey # noqa: F401 -- Retained public compatibility alias.
31
+ from .dsl._nodes import Node as ExpressionNode # noqa: F401 -- Retained public compatibility alias.
32
+ from .dsl._nodes import ProjectionRef as ProjectionRef # noqa: PLC0414 -- Explicit typed public re-export.
33
+ from .dsl.render import render_logical as render_logical # noqa: PLC0414 -- Explicit typed public re-export.
34
+ from .dsl.search import SearchLeg
35
+ from .types import MISSING, ActionRef, ActionSource, Vector
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class CapturedParameter:
40
+ name: str
41
+ carrier: object
42
+ optional: bool
43
+ key_components: tuple[str, ...] = ()
44
+ key_identity: tuple[tuple[str, str], ...] = ()
45
+ key_source: GeneratedSource | None = None
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class CapturedVariant:
50
+ presence: tuple[str, ...]
51
+ node: Node
52
+ parameters: tuple[CapturedParameter, ...]
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class CapturedDeclaration:
57
+ name: str
58
+ kind: str
59
+ parameters: tuple[CapturedParameter, ...]
60
+ variants: tuple[CapturedVariant, ...]
61
+ action: ActionSource | None = None
62
+
63
+
64
+ def _members(annotation: object) -> tuple[object, ...]:
65
+ return (
66
+ get_args(annotation)
67
+ if get_origin(annotation) in (Union, UnionType)
68
+ else (annotation,)
69
+ )
70
+
71
+
72
+ def _supported(annotation: object) -> bool:
73
+ if annotation == Vector:
74
+ return True
75
+ if annotation is MISSING or annotation is type(None):
76
+ return True
77
+ if any(
78
+ annotation is carrier
79
+ for carrier in (str, bool, int, Decimal, bytes, date, datetime)
80
+ ):
81
+ return True
82
+ origin = get_origin(annotation)
83
+ args = get_args(annotation)
84
+ if origin in (Union, UnionType):
85
+ return all(_supported(arg) for arg in args)
86
+ if origin in (list, tuple):
87
+ return bool(args) and all(arg is Ellipsis or _supported(arg) for arg in args)
88
+ if origin is dict:
89
+ return len(args) == 2 and args[0] is str and _supported(args[1])
90
+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):
91
+ key_identity(annotation)
92
+ return True
93
+ return False
94
+
95
+
96
+ def _parameters(function: Callable[..., Any]) -> tuple[CapturedParameter, ...]:
97
+ original = inspect.unwrap(function)
98
+ try:
99
+ hints = get_type_hints(original)
100
+ signature = inspect.signature(original)
101
+ except (NameError, TypeError, ValueError) as error:
102
+ raise CaptureError(
103
+ "CAPTURE_SIGNATURE", "unresolved declaration annotations"
104
+ ) from error
105
+ if len(signature.parameters) > 64:
106
+ raise CaptureError("CAPTURE_SIGNATURE", "more than 64 declaration parameters")
107
+ result: list[CapturedParameter] = []
108
+ for name, parameter in signature.parameters.items():
109
+ annotation = hints.get(name)
110
+ if parameter.kind in (
111
+ inspect.Parameter.VAR_POSITIONAL,
112
+ inspect.Parameter.VAR_KEYWORD,
113
+ ):
114
+ raise CaptureError(
115
+ "CAPTURE_SIGNATURE", "variadic declarations are unsupported"
116
+ )
117
+ if get_origin(annotation) is not Param or len(get_args(annotation)) != 1:
118
+ raise CaptureError(
119
+ "CAPTURE_SIGNATURE",
120
+ "every parameter must be Param with supported carrier",
121
+ )
122
+ carrier = get_args(annotation)[0]
123
+ if not _supported(carrier):
124
+ raise CaptureError("CAPTURE_SIGNATURE", "unsupported parameter carrier")
125
+ members = _members(carrier)
126
+ key_models = [
127
+ m for m in members if isinstance(m, type) and issubclass(m, BaseModel)
128
+ ]
129
+ components = tuple(key_models[0].model_fields) if len(key_models) == 1 else ()
130
+ result.append(CapturedParameter(name, carrier, any(m is MISSING for m in members), components, key_identity(key_models[0]) if key_models else (), getattr(key_models[0], "UMF_SOURCE", None) if key_models else None))
131
+ names = {p.name for p in result}
132
+ expanded = [f"{p.name}__{c}" for p in result for c in p.key_components]
133
+ if len(set(expanded)) != len(expanded) or names.intersection(expanded):
134
+ raise CaptureError("CAPTURE_SIGNATURE", "key component parameter names collide")
135
+ return tuple(result)
136
+
137
+
138
+ def _canonical(value: object) -> object:
139
+ # Keep capture deterministic across Python's configurable int-to-text cap.
140
+ # Refuse oversized authored Integer tokens before the canonical JSON writer.
141
+ if type(value) is int:
142
+ if value.bit_length() > 13607 or len(format(Decimal(value), "f").removeprefix("-")) > 4096:
143
+ raise CaptureError("CAPTURE_UNSUPPORTED", "Integer literal exceeds 4096-digit capture token profile")
144
+ return value
145
+ if isinstance(value, Decimal):
146
+ # Bucket widths retain the exact carrier/spelling in captured source.
147
+ return ("decimal", str(value))
148
+ if isinstance(value, frozenset):
149
+ return tuple(sorted(cast(frozenset[str], value)))
150
+ if isinstance(value, tuple):
151
+ return tuple(_canonical(item) for item in cast(tuple[object, ...], value))
152
+ if is_dataclass(value) and not isinstance(value, type):
153
+ return (
154
+ type(value).__module__,
155
+ type(value).__qualname__,
156
+ tuple((f.name, _canonical(getattr(value, f.name))) for f in fields(value)
157
+ if not (f.name == "alias" and getattr(value, f.name) is None)),
158
+ )
159
+ if isinstance(value, type):
160
+ return (value.__module__, value.__qualname__)
161
+ return value
162
+
163
+
164
+ def _validate_node(node: Node, parameters: tuple[CapturedParameter, ...]) -> None:
165
+ if node.op not in {
166
+ "all",
167
+ "first",
168
+ "one",
169
+ "count",
170
+ "exists",
171
+ "get",
172
+ "page",
173
+ "group_count",
174
+ "update",
175
+ "search_top",
176
+ }:
177
+ raise CaptureError("CAPTURE_UNSUPPORTED", "unsupported terminal form")
178
+ if not node.args or not isinstance(node.args[0], RecordRef):
179
+ raise CaptureError("CAPTURE_UNSUPPORTED", "terminal has no record identity")
180
+ record = node.args[0]
181
+ steps = cast(tuple[Node, ...], node.args[1])
182
+ selections = [value for step in steps if step.op == "select" for value in step.args]
183
+ scalar_selection = any(isinstance(value, Node) for value in selections)
184
+ if any(s.op == "group" for s in steps) and not selections and not any(s.op == "into" for s in steps) and node.op != "group_count":
185
+ raise CaptureError("CAPTURE_UNSUPPORTED", "grouped query requires explicit selection or count")
186
+ if scalar_selection and node.op not in {"all", "first", "one"}:
187
+ raise CaptureError("CAPTURE_UNSUPPORTED", "scalar aggregate/bucket projection does not admit this terminal")
188
+ owners = {(record.module, record.element, record.alias)}
189
+ for step in steps:
190
+ if step.op == "join":
191
+ relation = cast(Join[Any, Any, Any], step.args[0])
192
+ if (relation.ref.module, relation.ref.element, relation.ref.alias) not in owners:
193
+ raise CaptureError("CAPTURE_UNSUPPORTED", "join source is absent")
194
+ owners.add((relation.target.module, relation.target.element, relation.target.alias))
195
+ parameter_map = {p.name: p for p in parameters}
196
+ temporal_parameters: dict[str, str] = {}
197
+
198
+ def has_omitted(value: object) -> bool:
199
+ if isinstance(value, Node):
200
+ return value.op == "omitted" or any(
201
+ has_omitted(child) for child in value.args
202
+ )
203
+ return isinstance(value, tuple) and any(
204
+ has_omitted(child) for child in cast(tuple[object, ...], value)
205
+ )
206
+
207
+ def visit(value: object) -> None:
208
+ if isinstance(value, FieldRef):
209
+ if (value.module, value.element, value.alias) not in owners:
210
+ raise TypeError("expression column belongs to another Record")
211
+ elif isinstance(value, SearchLeg):
212
+ if (value.record.module, value.record.element) != (
213
+ record.module,
214
+ record.element,
215
+ ):
216
+ raise CaptureError("SEARCH_DECLARATION", "foreign search Record")
217
+ if value.value is not None:
218
+ if value.value.op != "param":
219
+ raise CaptureError(
220
+ "SEARCH_DECLARATION", "search requires bound parameters"
221
+ )
222
+ parameter = parameter_map.get(cast(str, value.value.args[0]))
223
+ wanted = Vector if value.kind == "vector" else str
224
+ if parameter is None or parameter.carrier != wanted:
225
+ raise CaptureError(
226
+ "CAPTURE_SIGNATURE",
227
+ "search parameter carrier differs from selected leg",
228
+ )
229
+ visit(value.value)
230
+ for leg in value.legs:
231
+ visit(leg)
232
+ elif isinstance(value, Join):
233
+ visit(value.ref)
234
+ elif isinstance(value, Node):
235
+ if value.op == "related":
236
+ from .dsl.navigation import navigation_parts
237
+
238
+ if len(value.args) != 4:
239
+ raise CaptureError("CAPTURE_UNSUPPORTED", "malformed navigation source")
240
+ source, source_steps, relationship, direction = value.args
241
+ if not isinstance(source, RecordRef) or type(source_steps) is not tuple or any(not isinstance(step, Node) for step in source_steps) or direction not in ("forward", "inverse"):
242
+ raise CaptureError("CAPTURE_UNSUPPORTED", "closed navigation source required")
243
+ original_source, original_target, _, _ = navigation_parts(relationship)
244
+ expected_source, expected_target = (original_source, original_target) if direction == "forward" else (original_target, original_source)
245
+ if source != expected_source or record != expected_target:
246
+ raise CaptureError("CAPTURE_UNSUPPORTED", "navigation selected root differs")
247
+ _validate_node(Node("all", (source, source_steps)), parameters)
248
+ return
249
+ if value.op in ("aggregate", "bucket_width"):
250
+ from .dsl._selection import scalar_fields
251
+ scalar_fields(value)
252
+ if value.op == "aggregate":
253
+ op, field, scale = value.args
254
+ if op not in {"sum", "min", "max", "avg", "count", "count_distinct", "approx_count_distinct"}:
255
+ raise CaptureError("CAPTURE_UNSUPPORTED", "unknown aggregate operation")
256
+ if isinstance(field, FieldRef) and field.temporal is not None:
257
+ raise CaptureError("CAPTURE_UNSUPPORTED", "temporal aggregate qualification is held")
258
+ if op == "avg" and (type(scale) is not int or not 0 <= scale <= 1000):
259
+ raise CaptureError("CAPTURE_UNSUPPORTED", "average requires bounded literal scale")
260
+ if value.op in ("param", "key_param"):
261
+ name = cast(str, value.args[0])
262
+ if name not in parameter_map:
263
+ raise CaptureError(
264
+ "CAPTURE_SIGNATURE",
265
+ "expression references an undeclared parameter",
266
+ )
267
+ components = value.args[1] if value.op == "key_param" else ()
268
+ identity = value.args[2] if value.op == "key_param" else ()
269
+ if (
270
+ components != parameter_map[name].key_components
271
+ or identity != parameter_map[name].key_identity
272
+ ):
273
+ raise CaptureError(
274
+ "CAPTURE_SIGNATURE",
275
+ "Key component parameters differ from declared carrier",
276
+ )
277
+ if value.op in ("=", "<>", "<", "<=", ">", ">=", "BETWEEN", "IN", "NOT IN", "IS DISTINCT FROM", "IS NOT DISTINCT FROM"):
278
+ left = value.args[0]
279
+ if isinstance(left, Node) and left.op == "column":
280
+ field = cast(FieldRef, left.args[0])
281
+ if field.temporal is not None:
282
+ for right in value.args[1:]:
283
+ if isinstance(right, Node) and right.op == "param":
284
+ name = cast(str, right.args[0])
285
+ if (
286
+ name in temporal_parameters
287
+ and temporal_parameters[name] != field.temporal
288
+ ):
289
+ raise CaptureError(
290
+ "CAPTURE_UNSUPPORTED",
291
+ "parameter spans incompatible temporal profiles",
292
+ )
293
+ temporal_parameters[name] = field.temporal
294
+ if value.op in ("and", "or", "not") and has_omitted(value):
295
+ raise CaptureError(
296
+ "CAPTURE_UNSUPPORTED",
297
+ "optional filters must be top-level filter arguments",
298
+ )
299
+ for child in value.args:
300
+ visit(child)
301
+ elif isinstance(value, tuple):
302
+ for child in cast(tuple[object, ...], value):
303
+ visit(child)
304
+ if node.op in ("get", "page"):
305
+ key = cast(Node, node.args[2] if node.op == "get" else node.args[3])
306
+ identity = dict(cast(tuple[tuple[str, str], ...], key.args[2])) if key.op == "key_param" else dict(cast(KeyLiteral, key.args[0]).identity) if key.op == "key" else {}
307
+ if identity and (identity["module"], identity["element"]) != (record.module, record.element):
308
+ raise CaptureError("CAPTURE_SIGNATURE", "Key belongs to another Record")
309
+ if record.key_id is not None and record.source is not None:
310
+ expected = {"documentId": record.source.document_id, "coreVersion": record.source.core_version, "module": record.module, "element": record.element, "key": record.key_id}
311
+ if identity != expected:
312
+ raise CaptureError("CAPTURE_SIGNATURE", "Key differs from selected Record Key")
313
+ visit(node)
314
+
315
+
316
+ def _invoke(
317
+ function: Callable[..., Any],
318
+ parameters: tuple[CapturedParameter, ...],
319
+ presence: frozenset[str],
320
+ ) -> tuple[Node, frozenset[str]]:
321
+ context = CaptureContext(
322
+ frozenset(p.name for p in parameters if p.optional), presence
323
+ )
324
+ token = CURRENT.set(context)
325
+ try:
326
+ signature = inspect.signature(function)
327
+ positional: list[Param[Any]] = []
328
+ keywords: dict[str, Param[Any]] = {}
329
+ for parameter in parameters:
330
+ symbolic = Param[Any](
331
+ parameter.name, parameter.key_components, parameter.key_identity
332
+ )
333
+ if (
334
+ signature.parameters[parameter.name].kind
335
+ is inspect.Parameter.POSITIONAL_ONLY
336
+ ):
337
+ positional.append(symbolic)
338
+ else:
339
+ keywords[parameter.name] = symbolic
340
+ try:
341
+ result = function(*positional, **keywords)
342
+ except AttributeError as error:
343
+ raise CaptureError(
344
+ "CAPTURE_UNSUPPORTED", "declaration uses an unsupported form"
345
+ ) from error
346
+ if not isinstance(result, Terminal):
347
+ raise CaptureError(
348
+ "CAPTURE_UNSUPPORTED", "declaration must return a DSL terminal"
349
+ )
350
+ _validate_node(result.node, parameters)
351
+ return result.node, frozenset(context.used_optional)
352
+ finally:
353
+ CURRENT.reset(token)
354
+
355
+
356
+ def capture(function: Callable[..., Any]) -> CapturedDeclaration:
357
+ kind = getattr(function, "__umf_kind__", None)
358
+ if kind not in ("query", "command"):
359
+ raise CaptureError(
360
+ "CAPTURE_UNSUPPORTED", "explicit query/command decorator required"
361
+ )
362
+ parameters = _parameters(function)
363
+ optional = frozenset(p.name for p in parameters if p.optional)
364
+
365
+ def twice(presence: frozenset[str]) -> tuple[Node, frozenset[str]]:
366
+ first = _invoke(function, parameters, presence)
367
+ second = _invoke(function, parameters, presence)
368
+ first_text = json.dumps(
369
+ _canonical(first),
370
+ ensure_ascii=False,
371
+ allow_nan=False,
372
+ separators=(",", ":"),
373
+ )
374
+ second_text = json.dumps(
375
+ _canonical(second),
376
+ ensure_ascii=False,
377
+ allow_nan=False,
378
+ separators=(",", ":"),
379
+ )
380
+ if first_text != second_text:
381
+ raise CaptureError("CAPTURE_NONDETERMINISTIC", "two captures differ")
382
+ return first
383
+
384
+ _, used = twice(optional)
385
+ if len(used) > 4:
386
+ raise CaptureError("VARIANT_LIMIT", "optional filters exceed 16 variants")
387
+ # Declaration order, not set iteration, controls deterministic variant bytes.
388
+ names = tuple(p.name for p in parameters if p.name in used)
389
+ variants: list[CapturedVariant] = []
390
+ for size in range(len(names) + 1):
391
+ for selected in combinations(names, size):
392
+ node, variant_used = twice(frozenset(selected))
393
+ if variant_used != used:
394
+ raise CaptureError(
395
+ "CAPTURE_UNSUPPORTED",
396
+ "optional-filter topology changes across variants",
397
+ )
398
+ if (node.op == "update") != (kind == "command"):
399
+ raise CaptureError(
400
+ "CAPTURE_UNSUPPORTED",
401
+ "writes require command and reads require query",
402
+ )
403
+ variants.append(CapturedVariant(selected, node, parameters))
404
+ action = None
405
+ if kind == "command":
406
+ reference = getattr(function, "__umf_action__", None)
407
+ if not isinstance(reference, ActionRef):
408
+ raise CaptureError("CAPTURE_UNSUPPORTED", "command requires generated action identity")
409
+ action = reference.source
410
+ return CapturedDeclaration(cast(str, function.__name__), kind, parameters, tuple(variants), action)