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.
- umf_access/__init__.py +109 -0
- umf_access/adoption.py +41 -0
- umf_access/build/__init__.py +2 -0
- umf_access/build/approximate.py +34 -0
- umf_access/build/catalog.py +1626 -0
- umf_access/build/commands.py +394 -0
- umf_access/build/pg_privileges.py +1544 -0
- umf_access/build/privileges.py +134 -0
- umf_access/build/search.py +365 -0
- umf_access/build/unity_search.py +104 -0
- umf_access/bulk.py +227 -0
- umf_access/canonical.py +23 -0
- umf_access/capture.py +410 -0
- umf_access/catalog.py +325 -0
- umf_access/codec_support.py +427 -0
- umf_access/commands.py +93 -0
- umf_access/delta_read.py +758 -0
- umf_access/dsl/__init__.py +148 -0
- umf_access/dsl/_context.py +36 -0
- umf_access/dsl/_expressions.py +625 -0
- umf_access/dsl/_joined.py +4 -0
- umf_access/dsl/_nodes.py +207 -0
- umf_access/dsl/_query.py +5559 -0
- umf_access/dsl/_selection.py +143 -0
- umf_access/dsl/navigation.py +302 -0
- umf_access/dsl/render.py +516 -0
- umf_access/dsl/search.py +343 -0
- umf_access/engine_catalog.py +563 -0
- umf_access/generated_core.py +5 -0
- umf_access/lifecycle/__init__.py +46 -0
- umf_access/lifecycle/_darwin_process_observer.c +306 -0
- umf_access/lifecycle/approval.py +366 -0
- umf_access/lifecycle/backfills.py +79 -0
- umf_access/lifecycle/catalog.py +289 -0
- umf_access/lifecycle/cli.py +231 -0
- umf_access/lifecycle/concurrent.py +196 -0
- umf_access/lifecycle/conversion_policy.py +188 -0
- umf_access/lifecycle/correspondence.py +203 -0
- umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
- umf_access/lifecycle/generation_authority_session.py +125 -0
- umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
- umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
- umf_access/lifecycle/generation_ingress.py +185 -0
- umf_access/lifecycle/generation_root_registry.py +138 -0
- umf_access/lifecycle/head.py +250 -0
- umf_access/lifecycle/head_view.py +81 -0
- umf_access/lifecycle/host.py +1183 -0
- umf_access/lifecycle/ingress_custody.py +750 -0
- umf_access/lifecycle/ingress_local_postgres.py +7990 -0
- umf_access/lifecycle/ingress_store.py +1488 -0
- umf_access/lifecycle/ledger.py +276 -0
- umf_access/lifecycle/ledger_schema.py +116 -0
- umf_access/lifecycle/mixed.py +593 -0
- umf_access/lifecycle/outcome_schema.py +136 -0
- umf_access/lifecycle/owner_approval_core.py +1810 -0
- umf_access/lifecycle/owner_authority.py +472 -0
- umf_access/lifecycle/owner_bootstrap.py +2077 -0
- umf_access/lifecycle/owner_wire.py +161 -0
- umf_access/lifecycle/phase_fence.py +52 -0
- umf_access/lifecycle/phase_policy.py +422 -0
- umf_access/lifecycle/privileges.py +145 -0
- umf_access/lifecycle/probe.py +39 -0
- umf_access/lifecycle/progress.py +497 -0
- umf_access/lifecycle/roles.py +96 -0
- umf_access/lifecycle/row_originals.py +1712 -0
- umf_access/lifecycle/row_originals_creation.py +759 -0
- umf_access/lifecycle/row_originals_receipt.py +413 -0
- umf_access/lifecycle/seeds.py +99 -0
- umf_access/lifecycle/sql_containment.py +358 -0
- umf_access/lifecycle/sql_containment_cli.py +33 -0
- umf_access/lifecycle/sql_containment_parser.py +20 -0
- umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
- umf_access/lifecycle/table_boundary.py +22 -0
- umf_access/lifecycle/target_custody_codec.py +788 -0
- umf_access/lifecycle/witness.py +72 -0
- umf_access/managed_actions.py +271 -0
- umf_access/managed_bulk.py +353 -0
- umf_access/managed_delta.py +150 -0
- umf_access/managed_support.py +166 -0
- umf_access/manifest_commands.py +278 -0
- umf_access/native_actions.py +1007 -0
- umf_access/native_program.py +570 -0
- umf_access/pages.py +125 -0
- umf_access/postgres_bulk.py +509 -0
- umf_access/postgres_read.py +1230 -0
- umf_access/postgres_search.py +639 -0
- umf_access/protocols.py +665 -0
- umf_access/py.typed +0 -0
- umf_access/related_keys.py +233 -0
- umf_access/reviewed.py +706 -0
- umf_access/search_catalog.py +122 -0
- umf_access/targets.py +312 -0
- umf_access/types.py +220 -0
- umf_access/unified/__init__.py +187 -0
- umf_access/unified/_binding.py +654 -0
- umf_access/unified/head_session.py +144 -0
- umf_access/unified/native_binding.py +143 -0
- umf_access/unified/operation_values.py +173 -0
- umf_access/unified/outcome_values.py +76 -0
- umf_access/unified/session_async.py +161 -0
- umf_access/unified/session_binding.py +108 -0
- umf_access/unified/session_policy.py +152 -0
- umf_access/unified/session_psycopg2.py +70 -0
- umf_access/unified/session_sqlalchemy.py +161 -0
- umf_access/unified/session_sync.py +148 -0
- umf_access/unified/table_reads.py +314 -0
- umf_access/unified/table_writes.py +193 -0
- umf_access/unity_search.py +312 -0
- umf_access/values.py +280 -0
- umf_access/verification.py +64 -0
- umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
- umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
- umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
- umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Value-graph and inventory boundaries for generated codecs, without I/O."""
|
|
3
|
+
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from datetime import UTC
|
|
6
|
+
from typing import Annotated, Any, TypedDict, TypeVar, cast, get_args, get_origin
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ValidationError
|
|
9
|
+
|
|
10
|
+
from .types import MISSING, CodecError, StrictModel
|
|
11
|
+
from .values import validate_instant
|
|
12
|
+
|
|
13
|
+
M = TypeVar("M", bound=BaseModel)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _model_types(annotation: object) -> tuple[type[BaseModel], ...]:
|
|
17
|
+
if isinstance(annotation, type) and issubclass(annotation, BaseModel):
|
|
18
|
+
return (annotation,)
|
|
19
|
+
return tuple(
|
|
20
|
+
model for argument in get_args(annotation) for model in _model_types(argument)
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _raw_graph(
|
|
25
|
+
value: object,
|
|
26
|
+
active: set[int],
|
|
27
|
+
budget: list[int],
|
|
28
|
+
depth: int = 0,
|
|
29
|
+
annotation: object = None,
|
|
30
|
+
) -> object:
|
|
31
|
+
budget[0] -= 1
|
|
32
|
+
if depth > 128 or budget[0] < 0:
|
|
33
|
+
raise CodecError("value graph exceeds codec bounds")
|
|
34
|
+
identity = id(value)
|
|
35
|
+
if not isinstance(value, (BaseModel, list, tuple, dict)):
|
|
36
|
+
return value
|
|
37
|
+
if identity in active:
|
|
38
|
+
raise CodecError("cyclic value graph refused")
|
|
39
|
+
active.add(identity)
|
|
40
|
+
try:
|
|
41
|
+
if isinstance(value, BaseModel):
|
|
42
|
+
declared = _model_types(annotation)
|
|
43
|
+
if declared and type(value) not in declared:
|
|
44
|
+
raise CodecError("field model: wrong declared model identity")
|
|
45
|
+
attributes: dict[str, object] = dict(
|
|
46
|
+
object.__getattribute__(value, "__dict__")
|
|
47
|
+
)
|
|
48
|
+
extras = object.__getattribute__(value, "__pydantic_extra__")
|
|
49
|
+
if extras:
|
|
50
|
+
attributes.update(extras)
|
|
51
|
+
return {
|
|
52
|
+
key: _raw_graph(
|
|
53
|
+
item,
|
|
54
|
+
active,
|
|
55
|
+
budget,
|
|
56
|
+
depth + 1,
|
|
57
|
+
type(value).model_fields[key].annotation
|
|
58
|
+
if key in type(value).model_fields
|
|
59
|
+
else None,
|
|
60
|
+
)
|
|
61
|
+
for key, item in attributes.items()
|
|
62
|
+
}
|
|
63
|
+
if isinstance(value, dict):
|
|
64
|
+
entries = cast(dict[object, object], value)
|
|
65
|
+
return {
|
|
66
|
+
key: _raw_graph(item, active, budget, depth + 1, annotation)
|
|
67
|
+
for key, item in entries.items()
|
|
68
|
+
}
|
|
69
|
+
sequence = cast(list[object] | tuple[object, ...], value)
|
|
70
|
+
items = [
|
|
71
|
+
_raw_graph(item, active, budget, depth + 1, annotation) for item in sequence
|
|
72
|
+
]
|
|
73
|
+
return tuple(items) if isinstance(value, tuple) else items
|
|
74
|
+
finally:
|
|
75
|
+
active.remove(identity)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _field_names(model_type: type[BaseModel], seen: set[type[BaseModel]]) -> set[str]:
|
|
79
|
+
if model_type in seen:
|
|
80
|
+
return set()
|
|
81
|
+
seen.add(model_type)
|
|
82
|
+
names = set(model_type.model_fields)
|
|
83
|
+
|
|
84
|
+
def visit(annotation: object) -> None:
|
|
85
|
+
if isinstance(annotation, type) and issubclass(annotation, BaseModel):
|
|
86
|
+
names.update(_field_names(annotation, seen))
|
|
87
|
+
else:
|
|
88
|
+
for argument in get_args(annotation):
|
|
89
|
+
visit(argument)
|
|
90
|
+
|
|
91
|
+
for field in model_type.model_fields.values():
|
|
92
|
+
visit(field.annotation)
|
|
93
|
+
return names
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def revalidate_model(model_type: type[M], value: M) -> M:
|
|
97
|
+
"""Reconstruct every raw model/container before validation; never dump it."""
|
|
98
|
+
if not isinstance(value, model_type):
|
|
99
|
+
raise CodecError("codec requires the declared model type")
|
|
100
|
+
raw = _raw_graph(value, set(), [10000], annotation=model_type)
|
|
101
|
+
return validate_graph(model_type, raw)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def validate_graph(model_type: type[M], raw: object) -> M:
|
|
105
|
+
"""Persistence validation with locations limited to authored field names."""
|
|
106
|
+
try:
|
|
107
|
+
return model_type.model_validate(raw, strict=True)
|
|
108
|
+
except ValidationError as error:
|
|
109
|
+
# Locations may contain input map keys/extra names. Publish only names
|
|
110
|
+
# from trusted model declarations, never error messages/context/input.
|
|
111
|
+
names = _field_names(model_type, set())
|
|
112
|
+
fields: list[str] = []
|
|
113
|
+
for detail in error.errors(
|
|
114
|
+
include_input=False, include_context=False, include_url=False
|
|
115
|
+
):
|
|
116
|
+
location = ".".join(
|
|
117
|
+
part
|
|
118
|
+
for part in detail["loc"]
|
|
119
|
+
if isinstance(part, str) and part in names
|
|
120
|
+
)
|
|
121
|
+
if location and location not in fields:
|
|
122
|
+
fields.append(location)
|
|
123
|
+
label = ", ".join(fields) if fields else "<model>"
|
|
124
|
+
raise CodecError(
|
|
125
|
+
"field " + label + ": invalid carrier or authored rule"
|
|
126
|
+
) from None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _build_mapping(columns: Sequence[str], row: Sequence[object]) -> dict[str, object]:
|
|
130
|
+
return dict(zip(columns, row, strict=True))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def checked_row(
|
|
134
|
+
expected: Sequence[str], columns: Sequence[str], row: Sequence[object]
|
|
135
|
+
) -> dict[str, object]:
|
|
136
|
+
"""Check the complete inventory and row size before constructing a mapping."""
|
|
137
|
+
if (
|
|
138
|
+
isinstance(expected, (str, bytes))
|
|
139
|
+
or isinstance(columns, (str, bytes))
|
|
140
|
+
or isinstance(row, (str, bytes))
|
|
141
|
+
):
|
|
142
|
+
raise CodecError("column inventory and row require sequences")
|
|
143
|
+
inventory = tuple(expected)
|
|
144
|
+
actual = tuple(columns)
|
|
145
|
+
values = tuple(row)
|
|
146
|
+
if any(type(column) is not str for column in inventory + actual):
|
|
147
|
+
raise CodecError("column identity requires string")
|
|
148
|
+
if len(set(inventory)) != len(inventory) or len(set(actual)) != len(actual):
|
|
149
|
+
raise CodecError("duplicate column inventory")
|
|
150
|
+
if set(actual) != set(inventory):
|
|
151
|
+
raise CodecError("missing or unexpected columns")
|
|
152
|
+
if len(actual) != len(values):
|
|
153
|
+
raise CodecError("column and row cardinality mismatch")
|
|
154
|
+
return _build_mapping(actual, values)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class CodecField(TypedDict):
|
|
158
|
+
"""Resolved local carrier metadata; never a guessed target transport tag."""
|
|
159
|
+
|
|
160
|
+
python: str
|
|
161
|
+
field: str
|
|
162
|
+
kind: str
|
|
163
|
+
item: "CodecField | None"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _convert(value: object, field: CodecField) -> object:
|
|
167
|
+
if value is None or value is MISSING:
|
|
168
|
+
return value
|
|
169
|
+
if field["kind"] == "instant":
|
|
170
|
+
return validate_instant(value).astimezone(UTC)
|
|
171
|
+
if field["kind"] in ("array", "map"):
|
|
172
|
+
child = field["item"]
|
|
173
|
+
if child is None:
|
|
174
|
+
raise CodecError("container codec requires item metadata")
|
|
175
|
+
if field["kind"] == "map":
|
|
176
|
+
if type(value) is not dict:
|
|
177
|
+
raise CodecError("map carrier required")
|
|
178
|
+
return {
|
|
179
|
+
key: _convert(item, child)
|
|
180
|
+
for key, item in cast(dict[str, object], value).items()
|
|
181
|
+
}
|
|
182
|
+
if type(value) not in (list, tuple):
|
|
183
|
+
raise CodecError("array carrier required")
|
|
184
|
+
items = [
|
|
185
|
+
_convert(item, child)
|
|
186
|
+
for item in cast(list[object] | tuple[object, ...], value)
|
|
187
|
+
]
|
|
188
|
+
return tuple(items) if type(value) is tuple else items
|
|
189
|
+
if field["kind"] != "identity":
|
|
190
|
+
raise CodecError("unknown local codec carrier")
|
|
191
|
+
return value
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _codec_inventory(model_type: type[M], fields: tuple[CodecField, ...]) -> None:
|
|
195
|
+
names = tuple(field["python"] for field in fields)
|
|
196
|
+
identities = tuple(field["field"] for field in fields)
|
|
197
|
+
if (
|
|
198
|
+
any(type(name) is not str or not name for name in names + identities)
|
|
199
|
+
or len(set(names)) != len(names)
|
|
200
|
+
or len(set(identities)) != len(identities)
|
|
201
|
+
or set(names) != set(model_type.model_fields)
|
|
202
|
+
):
|
|
203
|
+
raise CodecError("codec metadata does not match declared model inventory")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def encode_model(
|
|
207
|
+
model_type: type[M], value: M, fields: tuple[CodecField, ...]
|
|
208
|
+
) -> dict[str, object]:
|
|
209
|
+
"""Revalidate the entire graph and copy admitted local carriers by Field ID.
|
|
210
|
+
|
|
211
|
+
This is the local Python carrier boundary. A target must still supply its
|
|
212
|
+
recognized Weft carrier conversion; this helper makes no native claim.
|
|
213
|
+
"""
|
|
214
|
+
_codec_inventory(model_type, fields)
|
|
215
|
+
checked = revalidate_model(model_type, value)
|
|
216
|
+
return {
|
|
217
|
+
field["field"]: _convert(item, field)
|
|
218
|
+
for field in fields
|
|
219
|
+
if (item := getattr(checked, field["python"])) is not MISSING
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def decode_model(
|
|
224
|
+
model_type: type[M],
|
|
225
|
+
columns: Sequence[str],
|
|
226
|
+
row: Sequence[object],
|
|
227
|
+
fields: tuple[CodecField, ...],
|
|
228
|
+
) -> M:
|
|
229
|
+
"""Check inventory before mapping and sanitize validation errors at ingress."""
|
|
230
|
+
_codec_inventory(model_type, fields)
|
|
231
|
+
values = checked_row(tuple(field["field"] for field in fields), columns, row)
|
|
232
|
+
# model_construct is deliberately followed by raw graph revalidation. This
|
|
233
|
+
# keeps decode and encode on the same sanitized, non-trusting boundary.
|
|
234
|
+
checked = revalidate_model(
|
|
235
|
+
model_type,
|
|
236
|
+
model_type.model_construct(
|
|
237
|
+
_fields_set=None,
|
|
238
|
+
**{field["python"]: values[field["field"]] for field in fields},
|
|
239
|
+
),
|
|
240
|
+
)
|
|
241
|
+
return revalidate_model(
|
|
242
|
+
model_type,
|
|
243
|
+
model_type.model_construct(
|
|
244
|
+
_fields_set=None,
|
|
245
|
+
**{
|
|
246
|
+
field["python"]: _convert(getattr(checked, field["python"]), field)
|
|
247
|
+
for field in fields
|
|
248
|
+
},
|
|
249
|
+
),
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
ClassT = TypeVar("ClassT")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def seal_model(model: type[ClassT]) -> type[ClassT]:
|
|
257
|
+
def refuse_subclass(cls: type[object], **kwargs: object) -> None:
|
|
258
|
+
raise TypeError("generated model is final")
|
|
259
|
+
|
|
260
|
+
type.__setattr__(model, "__init_subclass__", classmethod(refuse_subclass))
|
|
261
|
+
return model
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def unhashable_key(model: type[M]) -> type[M]:
|
|
265
|
+
type.__setattr__(model, "__hash__", None)
|
|
266
|
+
return model
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def initialize_rejection(
|
|
270
|
+
error: Exception, code: str, retryable: dict[str, bool]
|
|
271
|
+
) -> None:
|
|
272
|
+
if code not in retryable:
|
|
273
|
+
raise CodecError("undeclared action rejection code")
|
|
274
|
+
error.code = code # type: ignore[attr-defined]
|
|
275
|
+
error.retryable = retryable[code] # type: ignore[attr-defined]
|
|
276
|
+
Exception.__init__(error, "action rejected")
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def initialize_action_rejection(
|
|
280
|
+
error: Exception,
|
|
281
|
+
code: str,
|
|
282
|
+
retryable: dict[str, bool],
|
|
283
|
+
override: bool | None = None,
|
|
284
|
+
) -> bool:
|
|
285
|
+
"""New generated action ABI; retain the original three-argument helper."""
|
|
286
|
+
initialize_rejection(error, code, retryable)
|
|
287
|
+
resolved = retryable[code] if override is None else override
|
|
288
|
+
error.retryable = resolved # type: ignore[attr-defined]
|
|
289
|
+
return resolved
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def make_projection_model(
|
|
293
|
+
name: str,
|
|
294
|
+
fields: tuple[tuple[str, type[StrictModel], str], ...],
|
|
295
|
+
*,
|
|
296
|
+
nullable_fields: tuple[str, ...] = (),
|
|
297
|
+
) -> type[StrictModel]:
|
|
298
|
+
"""Build-time and inert stage-two projection metadata, reusing Field validators."""
|
|
299
|
+
from copy import copy
|
|
300
|
+
|
|
301
|
+
from pydantic import create_model
|
|
302
|
+
|
|
303
|
+
if not fields or len({alias for alias, _, _ in fields}) != len(fields):
|
|
304
|
+
raise CodecError("distinct projection fields required")
|
|
305
|
+
pins = {
|
|
306
|
+
(
|
|
307
|
+
getattr(owner, "UMF_BUNDLE_INPUT_DIGEST", None),
|
|
308
|
+
getattr(owner, "UMF_RUNTIME_ABI", None),
|
|
309
|
+
)
|
|
310
|
+
for _, owner, _ in fields
|
|
311
|
+
}
|
|
312
|
+
if len(pins) != 1:
|
|
313
|
+
raise CodecError("mixed generated projection sources")
|
|
314
|
+
definitions: dict[str, Any] = {}
|
|
315
|
+
for alias, owner, source in fields:
|
|
316
|
+
field = copy(owner.model_fields[source])
|
|
317
|
+
field.alias = None
|
|
318
|
+
if alias in nullable_fields:
|
|
319
|
+
annotation: Any = field.annotation
|
|
320
|
+
if annotation is None:
|
|
321
|
+
raise CodecError("projection field has no carrier")
|
|
322
|
+
field.annotation = cast(
|
|
323
|
+
Any,
|
|
324
|
+
(
|
|
325
|
+
Annotated[(annotation, *field.metadata)]
|
|
326
|
+
if field.metadata
|
|
327
|
+
else annotation
|
|
328
|
+
)
|
|
329
|
+
| None,
|
|
330
|
+
)
|
|
331
|
+
field.metadata = []
|
|
332
|
+
definitions[alias] = (field.annotation, field)
|
|
333
|
+
model = create_model(name, __base__=StrictModel, **definitions)
|
|
334
|
+
digest, abi = next(iter(pins))
|
|
335
|
+
if digest is not None:
|
|
336
|
+
type.__setattr__(model, "UMF_BUNDLE_INPUT_DIGEST", digest)
|
|
337
|
+
type.__setattr__(model, "UMF_RUNTIME_ABI", abi)
|
|
338
|
+
return model
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def make_scalar_projection_model(
|
|
342
|
+
name: str,
|
|
343
|
+
fields: tuple[tuple[str, type[StrictModel], str, str, object, bool], ...],
|
|
344
|
+
) -> type[StrictModel]:
|
|
345
|
+
"""Closed aggregate/bucket row metadata; never reuse input numeric bounds.
|
|
346
|
+
|
|
347
|
+
Group columns and extrema retain their original exact Field validators.
|
|
348
|
+
SUM/bucket/AVG outputs use fresh unbounded numeric domains: their result can
|
|
349
|
+
exceed the input's width, range, allowed set or decimal precision.
|
|
350
|
+
"""
|
|
351
|
+
from copy import copy
|
|
352
|
+
from decimal import Decimal
|
|
353
|
+
|
|
354
|
+
from pydantic import BeforeValidator, create_model
|
|
355
|
+
|
|
356
|
+
from .values import FieldValidator, validate_integer
|
|
357
|
+
|
|
358
|
+
if not fields or len({f[0] for f in fields}) != len(fields):
|
|
359
|
+
raise CodecError("distinct scalar projection aliases required")
|
|
360
|
+
pins = {(getattr(owner, "UMF_BUNDLE_INPUT_DIGEST", None), getattr(owner, "UMF_RUNTIME_ABI", None)) for _, owner, _, _, _, _ in fields}
|
|
361
|
+
if len(pins) != 1 or None in next(iter(pins)):
|
|
362
|
+
raise CodecError("mixed or absent generated scalar sources")
|
|
363
|
+
definitions: dict[str, Any] = {}
|
|
364
|
+
for alias, owner, source, op, argument, nullable in fields:
|
|
365
|
+
original = owner.model_fields.get(source)
|
|
366
|
+
if op in ("field", "min", "max"):
|
|
367
|
+
if original is None:
|
|
368
|
+
raise CodecError("scalar source field absent")
|
|
369
|
+
field = copy(original)
|
|
370
|
+
annotation: Any = field.annotation
|
|
371
|
+
if annotation is None:
|
|
372
|
+
raise CodecError("scalar source carrier absent")
|
|
373
|
+
if nullable or op != "field":
|
|
374
|
+
annotation = (Annotated[(annotation, *field.metadata)] if field.metadata else annotation) | None
|
|
375
|
+
field.metadata = []
|
|
376
|
+
field.alias = None
|
|
377
|
+
definitions[alias] = (annotation, field)
|
|
378
|
+
continue
|
|
379
|
+
def numeric_metadata(annotation: object) -> tuple[list[object], list[object]]:
|
|
380
|
+
if get_origin(annotation) is Annotated:
|
|
381
|
+
carrier, *metadata = get_args(annotation)
|
|
382
|
+
carriers, nested = numeric_metadata(carrier)
|
|
383
|
+
return carriers, [*metadata, *nested]
|
|
384
|
+
arguments = get_args(annotation)
|
|
385
|
+
if arguments:
|
|
386
|
+
carriers = []
|
|
387
|
+
metadata = []
|
|
388
|
+
for member in arguments:
|
|
389
|
+
found, validators = numeric_metadata(member)
|
|
390
|
+
carriers.extend(found)
|
|
391
|
+
metadata.extend(validators)
|
|
392
|
+
return carriers, metadata
|
|
393
|
+
return [annotation], []
|
|
394
|
+
candidates, nested_metadata = numeric_metadata(original.annotation) if original is not None else ([], [])
|
|
395
|
+
numeric = next((a for a in candidates if a in (int, Decimal)), None)
|
|
396
|
+
if op == "bucket_width" and type(None) in candidates:
|
|
397
|
+
nullable = True
|
|
398
|
+
if op in ("count", "count_distinct", "approx_count_distinct"):
|
|
399
|
+
annotation = Annotated[int, BeforeValidator(validate_integer)]
|
|
400
|
+
nullable = False
|
|
401
|
+
elif op in ("sum", "avg", "bucket_width") and numeric is not None:
|
|
402
|
+
decimal = numeric is Decimal or op == "avg" or op == "bucket_width" and type(argument) is Decimal
|
|
403
|
+
if op == "avg" and (type(argument) is not int or not 0 <= argument <= 1000):
|
|
404
|
+
raise CodecError("average output scale outside profile")
|
|
405
|
+
source_scales = [
|
|
406
|
+
validator.func.scale
|
|
407
|
+
for validator in ([*original.metadata, *nested_metadata] if original is not None else ())
|
|
408
|
+
if isinstance(validator, BeforeValidator)
|
|
409
|
+
and isinstance(validator.func, FieldValidator)
|
|
410
|
+
and validator.func.scale is not None
|
|
411
|
+
]
|
|
412
|
+
output_scale: int | None = cast(int, argument) if op == "avg" else max(source_scales, default=None)
|
|
413
|
+
if op == "bucket_width" and isinstance(argument, Decimal):
|
|
414
|
+
exponent = argument.as_tuple().exponent
|
|
415
|
+
assert isinstance(exponent, int)
|
|
416
|
+
output_scale = max(output_scale or 0, -exponent, 0)
|
|
417
|
+
annotation = Annotated[Decimal, BeforeValidator(FieldValidator(kind="decimal", scale=output_scale))] if decimal else Annotated[int, BeforeValidator(validate_integer)]
|
|
418
|
+
else:
|
|
419
|
+
raise CodecError("unsupported scalar result carrier")
|
|
420
|
+
if nullable:
|
|
421
|
+
annotation = annotation | None
|
|
422
|
+
definitions[alias] = (annotation, ...)
|
|
423
|
+
result = create_model(name, __base__=StrictModel, **definitions)
|
|
424
|
+
digest, abi = next(iter(pins))
|
|
425
|
+
type.__setattr__(result, "UMF_BUNDLE_INPUT_DIGEST", digest)
|
|
426
|
+
type.__setattr__(result, "UMF_RUNTIME_ABI", abi)
|
|
427
|
+
return result
|
umf_access/commands.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Typed command catalog dispatch. Plans are supplied by the selected target."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Awaitable, Mapping
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import timedelta
|
|
9
|
+
from typing import Any, Protocol, TypeVar, overload
|
|
10
|
+
|
|
11
|
+
from .adoption import TargetIdentity
|
|
12
|
+
from .catalog import Argument, CatalogError, NotCompiledForTarget, TargetPin
|
|
13
|
+
from .native_program import NativeProgram
|
|
14
|
+
from .types import MISSING, ActionRef
|
|
15
|
+
|
|
16
|
+
# Preserve the published generic parameter spelling and variance.
|
|
17
|
+
PlanT = TypeVar("PlanT", covariant=True) # noqa: PLC0105
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class CommandVariant:
|
|
22
|
+
presence: tuple[str, ...]
|
|
23
|
+
pin: TargetPin
|
|
24
|
+
program: NativeProgram
|
|
25
|
+
action: ActionRef[Any, Any]
|
|
26
|
+
parameters: tuple[tuple[str, str, str | None], ...]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BulkTarget(Protocol[PlanT]):
|
|
30
|
+
def identity(self) -> TargetIdentity: ...
|
|
31
|
+
def plan(
|
|
32
|
+
self,
|
|
33
|
+
entry: CommandVariant,
|
|
34
|
+
params: Mapping[str, object],
|
|
35
|
+
*,
|
|
36
|
+
timeout: timedelta | None = None,
|
|
37
|
+
) -> PlanT: ...
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class AsyncBulkTarget(Protocol[PlanT]):
|
|
41
|
+
def identity(self) -> TargetIdentity: ...
|
|
42
|
+
async def plan(
|
|
43
|
+
self, entry: CommandVariant, params: Mapping[str, object], *,
|
|
44
|
+
timeout: timedelta | None = None,
|
|
45
|
+
) -> PlanT: ...
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class CommandPlan:
|
|
50
|
+
name: str
|
|
51
|
+
arguments: tuple[Argument, ...]
|
|
52
|
+
variants: tuple[CommandVariant, ...]
|
|
53
|
+
|
|
54
|
+
@overload
|
|
55
|
+
def run(self, target: AsyncBulkTarget[PlanT], values: Mapping[str, object], *, timeout: timedelta | None = None) -> Awaitable[PlanT]: ...
|
|
56
|
+
@overload
|
|
57
|
+
def run(self, target: BulkTarget[PlanT], values: Mapping[str, object], *, timeout: timedelta | None = None) -> PlanT: ...
|
|
58
|
+
def run(
|
|
59
|
+
self,
|
|
60
|
+
target: BulkTarget[PlanT] | AsyncBulkTarget[PlanT],
|
|
61
|
+
values: Mapping[str, object],
|
|
62
|
+
*,
|
|
63
|
+
timeout: timedelta | None = None,
|
|
64
|
+
) -> PlanT | Awaitable[PlanT]:
|
|
65
|
+
if set(values) != {a.name for a in self.arguments}:
|
|
66
|
+
raise CatalogError("exact command argument inventory required")
|
|
67
|
+
checked = {a.name: a.validate(values[a.name]) for a in self.arguments}
|
|
68
|
+
presence = tuple(
|
|
69
|
+
a.name
|
|
70
|
+
for a in self.arguments
|
|
71
|
+
if a.optional and checked[a.name] is not MISSING
|
|
72
|
+
)
|
|
73
|
+
identity = target.identity()
|
|
74
|
+
matching = [
|
|
75
|
+
v
|
|
76
|
+
for v in self.variants
|
|
77
|
+
if v.presence == presence and v.pin.matches(identity)
|
|
78
|
+
]
|
|
79
|
+
if len(matching) != 1:
|
|
80
|
+
raise NotCompiledForTarget(
|
|
81
|
+
"no unique compiled command for target and presence"
|
|
82
|
+
)
|
|
83
|
+
entry = matching[0]
|
|
84
|
+
entry.program.bind(entry.action)
|
|
85
|
+
params = {
|
|
86
|
+
name: (
|
|
87
|
+
getattr(checked[source], component)
|
|
88
|
+
if component is not None
|
|
89
|
+
else checked[source]
|
|
90
|
+
)
|
|
91
|
+
for name, source, component in entry.parameters
|
|
92
|
+
}
|
|
93
|
+
return target.plan(entry, params, timeout=timeout)
|