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,1007 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Source-bound native statement execution. Weft owns all business SQL.
3
+
4
+ The host admission port owns the original native deployment/authority fence and
5
+ writer incarnation. A descriptor is never authentication or a fence credential.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import json
12
+ import math
13
+ import time
14
+ from collections.abc import Callable, Generator, Mapping
15
+ from dataclasses import dataclass
16
+ from datetime import timedelta
17
+ from decimal import Decimal
18
+ from typing import Any, Protocol, cast
19
+
20
+ from .native_program import NativeProgram, mutation_locks
21
+ from .native_program import canonical_json as _json
22
+ from .postgres_read import _catalog_fence_programs, _snapshot_free_timeout
23
+ from .protocols import (
24
+ ActionDenied,
25
+ ActionFailed,
26
+ ActionOutcome,
27
+ ActionRefused,
28
+ Committed,
29
+ Conflict,
30
+ Denied,
31
+ Indeterminate,
32
+ NativeOutcomeDetails,
33
+ Receipt,
34
+ Rejected,
35
+ TimedOut,
36
+ ValidationFailure,
37
+ ValidationResult,
38
+ )
39
+ from .types import ActionRef, StrictModel
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class NativeScope:
44
+ store: str
45
+ epoch: str
46
+ authenticated: str
47
+ effective: str
48
+ custody: object
49
+ attribution_json: str | None = None
50
+
51
+ def __post_init__(self) -> None:
52
+ if any(
53
+ type(v) is not str or not v
54
+ for v in (self.store, self.epoch, self.authenticated, self.effective)
55
+ ):
56
+ raise ActionRefused("ORIGINAL_NATIVE_SCOPE_REQUIRED")
57
+
58
+
59
+ class NativeAdmission(Protocol):
60
+ def admit(
61
+ self, connection: Any, program: Mapping[str, Any], *, deadline: float
62
+ ) -> NativeScope: ...
63
+ def reconnect(
64
+ self, connection: Any, original: NativeScope, *, deadline: float
65
+ ) -> NativeScope: ...
66
+ def quarantine(self, connection: Any, original: NativeScope | None) -> None: ...
67
+
68
+
69
+ def _literal(value: Any) -> Any:
70
+ if value is None:
71
+ return None
72
+ if not isinstance(value, dict) or len(value) != 1:
73
+ raise ActionRefused("NATIVE_LITERAL")
74
+ key, item = next(iter(value.items()))
75
+ if key in ("string", "boolean"):
76
+ return item
77
+ if key == "integerToken":
78
+ return int(item)
79
+ if key == "decimalToken":
80
+ return Decimal(item)
81
+ raise ActionRefused("NATIVE_LITERAL")
82
+
83
+
84
+ def _field_key(reference: Any) -> str:
85
+ return _json([reference["module"], reference["element"]])
86
+
87
+
88
+ def native_input_value(value: object) -> Any:
89
+ if value is None:
90
+ return None
91
+ if type(value) is bool:
92
+ return {"boolean": value}
93
+ if type(value) is str:
94
+ return {"string": value}
95
+ if type(value) is int:
96
+ return {"integerToken": str(value)}
97
+ if isinstance(value, Decimal):
98
+ return {"decimalToken": str(value)}
99
+ if isinstance(value, StrictModel) and getattr(type(value), "UMF_KEY", False):
100
+ return {
101
+ "key": dict(type(value).KEY_IDENTITY),
102
+ "components": [
103
+ {
104
+ "field": {"module": module, "element": field},
105
+ "value": native_input_value(getattr(value, name)),
106
+ }
107
+ for module, field, name in type(value).UMF_FIELDS
108
+ ],
109
+ }
110
+ raise ActionRefused("NATIVE_INPUT_CARRIER")
111
+
112
+
113
+ class _State:
114
+ def __init__(
115
+ self,
116
+ action: ActionRef[Any, Any],
117
+ program: NativeProgram,
118
+ inputs: Mapping[str, object],
119
+ ):
120
+ from .codec_support import revalidate_model
121
+
122
+ program.bind(action)
123
+ checked = revalidate_model(
124
+ action.input_type,
125
+ action.input_type.model_validate(dict(inputs), strict=True),
126
+ )
127
+ self.action, self.program, self.inputs = (
128
+ action,
129
+ program.checked(),
130
+ dict(checked),
131
+ )
132
+ if (
133
+ getattr(action.input_type, "UMF_BUNDLE_INPUT_DIGEST", None)
134
+ != program.bundle_input_digest
135
+ ):
136
+ raise ActionRefused("CATALOG_STALE")
137
+ self.statements = json.loads(program.statements_json)
138
+ self.pre: dict[str, Any] = {}
139
+ self.post: dict[str, Any] = {}
140
+ self.scope: NativeScope | None = None
141
+ self.receipt: Receipt | None = None
142
+ self.markers: list[Any] = []
143
+ self.verification: list[Any] = []
144
+ self.changes: list[Any] = []
145
+ self.request = _json(
146
+ {
147
+ "program": self.program,
148
+ "inputDigest": program.bundle_input_digest,
149
+ "parameters": {
150
+ name: native_input_value(value)
151
+ for name, value in self.inputs.items()
152
+ },
153
+ }
154
+ )
155
+ if len(self.request.encode()) > 4_194_304:
156
+ raise ActionRefused("NATIVE_REQUEST_BUDGET")
157
+ if action.source is None:
158
+ raise ActionRefused("ACTION_SOURCE_REQUIRED")
159
+ source = self.program["source"]
160
+ for name, attribute in [
161
+ ("documentId", "document_id"),
162
+ ("coreVersion", "core_version"),
163
+ ("module", "module"),
164
+ ("action", "action"),
165
+ ("documentSha256", "document_sha256"),
166
+ ("actionPointer", "action_pointer"),
167
+ ]:
168
+ if source[name] != getattr(action.source, attribute):
169
+ raise ActionRefused("NATIVE_ACTION_SOURCE_MISMATCH")
170
+ self.parameters = {
171
+ source: self.inputs[name]
172
+ for source, name in action.input_fields
173
+ if name in self.inputs
174
+ }
175
+ if set(self.parameters) != {
176
+ p["id"] for p in self.program["action"]["parameters"]
177
+ }:
178
+ raise ActionRefused("NATIVE_INPUT_INVENTORY")
179
+
180
+ def resolve(self, source: Any) -> Any:
181
+ if "input" in source:
182
+ return self.parameters[source["input"]]
183
+ if "entity" in source:
184
+ entity = self.parameters[source["entity"]]
185
+ ref = next(
186
+ p["target"]
187
+ for p in self.program["action"]["parameters"]
188
+ if p["id"] == source["entity"]
189
+ )
190
+ key = next(
191
+ k
192
+ for k in self.action.key_types
193
+ if k.module == ref["module"]
194
+ and k.element == ref["element"]
195
+ and k.key == ref["key"]
196
+ )
197
+ if type(entity) is not key.model:
198
+ raise ActionRefused("NATIVE_NOMINAL_KEY")
199
+ field = next(
200
+ v
201
+ for v in self.program["entities"].values()
202
+ if v["key"]["reference"] == ref
203
+ )["key"]["fields"][source["component"]]["reference"]
204
+ name = next(
205
+ name
206
+ for module, element, name in key.model.UMF_FIELDS
207
+ if (module, element) == (field["module"], field["element"])
208
+ )
209
+ return getattr(entity, name)
210
+ if "literal" in source:
211
+ return _literal(source["literal"])
212
+ if "nativeRole" in source:
213
+ return source["nativeRole"]
214
+ if "snapshotExists" in source:
215
+ return (self.pre if source["snapshotExists"] == "pre" else self.post)[
216
+ source["image"]
217
+ ] is not None
218
+ if "snapshot" in source:
219
+ row = (self.pre if source["snapshot"] == "pre" else self.post)[
220
+ source["image"]
221
+ ]
222
+ return None if row is None else row[_field_key(source["field"])]
223
+ raise ActionRefused("NATIVE_BINDING_SOURCE")
224
+
225
+ def statement(self, path: str) -> tuple[str, tuple[Any, ...]]:
226
+ value: Any = self.program
227
+ for part in path.strip("/").split("/"):
228
+ value = value[int(part)] if isinstance(value, list) else value[part]
229
+ slots = [self.resolve(p["source"]) for p in value["parameters"]]
230
+ bound = self.statements[path]
231
+ return bound["sql"], tuple(slots[i] for i in bound["order"])
232
+
233
+ def details(self, transaction: str) -> NativeOutcomeDetails:
234
+ return NativeOutcomeDetails(
235
+ self.action,
236
+ self.program["profile"],
237
+ _json(self.markers),
238
+ not self.changes if transaction == "committed" else None,
239
+ _json(self.verification),
240
+ _json(self.changes),
241
+ None
242
+ if self.scope is None
243
+ else self.scope.attribution_json
244
+ if self.scope.attribution_json is not None
245
+ else _json(
246
+ {
247
+ "authenticated": self.scope.authenticated,
248
+ "effective": self.scope.effective,
249
+ }
250
+ ),
251
+ self.receipt,
252
+ _json({"state": transaction}),
253
+ self.request,
254
+ self.scope,
255
+ )
256
+
257
+ def key(self, entity: Any) -> StrictModel:
258
+ ref = entity["key"]["reference"]
259
+ key_type = next(
260
+ k.model
261
+ for k in self.action.key_types
262
+ if (k.module, k.element, k.key)
263
+ == (ref["module"], ref["element"], ref["key"])
264
+ )
265
+ # Explicit source Field mapping, never a guessed primary Key/order.
266
+ values = {
267
+ _field_key(f["reference"]): self.resolve(v)
268
+ for f, v in zip(entity["key"]["fields"], entity["components"], strict=True)
269
+ }
270
+ mapping = key_type.UMF_FIELDS
271
+ return key_type.model_validate(
272
+ {name: values[_json([module, field])] for module, field, name in mapping},
273
+ strict=True,
274
+ )
275
+
276
+ def images(self, phase: str) -> Generator[Any, Any, None]:
277
+ target = self.pre if phase == "pre" else self.post
278
+ for index, image in enumerate(
279
+ self.program["preImages" if phase == "pre" else "postImages"]
280
+ ):
281
+ rows = yield (
282
+ "query",
283
+ *self.statement(
284
+ "/"
285
+ + ("preImages" if phase == "pre" else "postImages")
286
+ + "/"
287
+ + str(index)
288
+ + "/statement"
289
+ ),
290
+ )
291
+ if len(rows) > 1:
292
+ raise ActionRefused("NATIVE_KEY_CARDINALITY")
293
+ if rows:
294
+ from typing import Annotated
295
+
296
+ from pydantic import TypeAdapter
297
+
298
+ for f, value in zip(image["columns"], rows[0], strict=True):
299
+ record = next(
300
+ r.model
301
+ for r in self.action.record_types
302
+ if any(
303
+ (module, element)
304
+ == (f["reference"]["module"], f["reference"]["element"])
305
+ for module, element, _ in r.model.UMF_FIELDS
306
+ )
307
+ )
308
+ name = next(
309
+ name
310
+ for module, element, name in record.UMF_FIELDS
311
+ if (module, element)
312
+ == (f["reference"]["module"], f["reference"]["element"])
313
+ )
314
+ field = record.model_fields[name]
315
+ TypeAdapter(
316
+ cast(
317
+ Any,
318
+ Annotated[(field.annotation, *field.metadata)]
319
+ if field.metadata
320
+ else field.annotation,
321
+ )
322
+ ).validate_python(value, strict=True)
323
+ target[image["name"]] = (
324
+ None
325
+ if not rows
326
+ else {
327
+ _field_key(f["reference"]): value
328
+ for f, value in zip(image["columns"], rows[0], strict=True)
329
+ }
330
+ )
331
+
332
+ def conditions(
333
+ self, phase: str, *, collect_all: bool = False
334
+ ) -> Generator[Any, Any, list[ValidationFailure]]:
335
+ failures = []
336
+ for index, condition in enumerate(self.program[phase + "conditions"]):
337
+ rows = yield (
338
+ "query",
339
+ *self.statement(
340
+ "/" + phase + "conditions/" + str(index) + "/statement"
341
+ ),
342
+ )
343
+ if len(rows) != 1 or len(rows[0]) != 2:
344
+ raise ActionRefused("NATIVE_CONDITION_MARKER")
345
+ error, passed = rows[0]
346
+ if type(error) is not bool or type(passed) is not bool:
347
+ raise ActionRefused("NATIVE_CONDITION_MARKER")
348
+ self.verification.append(
349
+ {
350
+ "phase": phase,
351
+ "id": condition["id"],
352
+ "evaluationError": error,
353
+ "passed": passed,
354
+ }
355
+ )
356
+ if error:
357
+ raise ActionFailed(
358
+ "RULE_EVALUATION",
359
+ ValueError("native rule evaluation error"),
360
+ self.details("pending"),
361
+ )
362
+ if not passed:
363
+ failures.append(ValidationFailure(condition["code"]))
364
+ if not collect_all:
365
+ break
366
+ return failures
367
+
368
+ def schema_admissions(self) -> Generator[Any, Any, None]:
369
+ # The original action owner binds qualified schemas literally or resolves
370
+ # its exact unqualified relation with to_regclass. This port has no read-target schema
371
+ # configuration and cannot reinterpret an appSchema placeholder.
372
+ from .postgres_read import _compiled_admissions
373
+
374
+ fence = _catalog_fence_programs(self.program)
375
+ if fence is not None:
376
+ for sql, parameters in fence[1]:
377
+ rows = yield ("query", sql, parameters)
378
+ if len(rows) != 1 or len(rows[0]) != 1 or rows[0][0] is not True:
379
+ raise ActionRefused("NATIVE_TEXT_SEARCH_FENCE_MISMATCH")
380
+ obligations = self.program["obligations"]
381
+ groups = [("NATIVE_SCHEMA_MISMATCH", "NATIVE_SCHEMA_BINDING_SOURCE", obligations["nativeProjection"]["columns"])]
382
+ if "termFilter" in obligations:
383
+ groups.append(("NATIVE_TERM_MISMATCH", "NATIVE_TERM_BINDING_SOURCE", obligations["termFilter"]["indexes"]))
384
+ if "textSearchEffects" in obligations:
385
+ groups.append(("NATIVE_TEXT_SEARCH_EFFECT_MISMATCH", "NATIVE_TEXT_SEARCH_EFFECT_BINDING_SOURCE", obligations["textSearchEffects"]["indexes"]))
386
+ for mismatch, binding_error, descriptors in groups:
387
+ for descriptor in descriptors:
388
+ admission = descriptor.get("nativeAdmission") if isinstance(descriptor, dict) else None
389
+ parameters = admission.get("parameters") if isinstance(admission, dict) else None
390
+ if not isinstance(parameters, list) or any(
391
+ not isinstance(parameter, dict)
392
+ or not isinstance(parameter.get("source"), dict)
393
+ or set(parameter["source"]) != {"literal"}
394
+ for parameter in parameters
395
+ ):
396
+ raise ActionRefused(binding_error)
397
+ for sql, parameters in _compiled_admissions(descriptors, ""):
398
+ rows = yield ("query", sql, parameters)
399
+ if len(rows) != 1 or len(rows[0]) != 1 or rows[0][0] is not True:
400
+ raise ActionRefused(mismatch)
401
+
402
+ def execute(
403
+ self, validate: bool
404
+ ) -> Generator[Any, Any, ActionOutcome | ValidationResult]:
405
+ rows = yield ("query", *self.statement("/admission"))
406
+ if len(rows) != 1 or len(rows[0]) != 4:
407
+ raise ActionRefused("NATIVE_ADMISSION_MARKER")
408
+ allowed, authenticated, effective, xid = rows[0]
409
+ if self.scope is None or (authenticated, effective) != (
410
+ self.scope.authenticated,
411
+ self.scope.effective,
412
+ ):
413
+ raise ActionRefused("NATIVE_SESSION_CHANGED")
414
+ if not isinstance(xid, str) or not xid.isdecimal():
415
+ raise ActionRefused("NATIVE_XID8")
416
+ self.receipt = Receipt(self.scope.store, self.scope.epoch, xid)
417
+ if allowed is not True:
418
+ yield ("rollback",)
419
+ return (
420
+ ValidationResult(False, (ValidationFailure("ROLE_DENIED"),), True)
421
+ if validate
422
+ else Denied("ROLE_DENIED", self.details("rolled-back"))
423
+ )
424
+ for sql in self.program["lockSql"]:
425
+ yield ("query", sql, None)
426
+ yield from self.schema_admissions()
427
+ yield from self.images("pre")
428
+ missing = [
429
+ name
430
+ for name, entity in self.program["entities"].items()
431
+ if entity["requiredExisting"] and self.pre["entity:" + name] is None
432
+ ]
433
+ failures = (
434
+ [ValidationFailure("ENTITY_MISSING")]
435
+ if missing
436
+ else (yield from self.conditions("pre", collect_all=validate))
437
+ )
438
+ if failures or validate:
439
+ yield from self.schema_admissions()
440
+ yield ("rollback",)
441
+ if validate:
442
+ return ValidationResult(
443
+ not failures,
444
+ tuple(failures),
445
+ not missing or not self.program["preconditions"],
446
+ )
447
+ condition = next(
448
+ (
449
+ c
450
+ for c in self.program["preconditions"]
451
+ if c["code"] == failures[0].code
452
+ ),
453
+ None,
454
+ )
455
+ return Rejected(
456
+ failures[0].code,
457
+ False if condition is None else condition["retryable"],
458
+ self.details("rolled-back"),
459
+ )
460
+ for index, effect in enumerate(self.program["effects"]):
461
+ if effect["guard"] is not None:
462
+ guard = yield (
463
+ "query",
464
+ *self.statement("/effects/" + str(index) + "/guard"),
465
+ )
466
+ if not guard:
467
+ raise ActionFailed(
468
+ "ENTITY_MISSING",
469
+ ValueError("effect entity unavailable"),
470
+ self.details("pending"),
471
+ )
472
+ if len(guard) != 1 or type(guard[0][0]) is not bool:
473
+ raise ActionRefused("NATIVE_EFFECT_MARKER")
474
+ if guard[0][0] is False:
475
+ self.markers.append({"id": effect["id"], "changed": False})
476
+ continue
477
+ rows = yield (
478
+ "query",
479
+ *self.statement("/effects/" + str(index) + "/statement"),
480
+ )
481
+ if not rows:
482
+ raise ActionDenied("NATIVE_EFFECT_DENIED", self.details("pending"))
483
+ if len(rows) != 1:
484
+ raise ActionRefused("NATIVE_EFFECT_CARDINALITY")
485
+ expected = tuple(self.resolve(v) for v in effect["entity"]["components"])
486
+ if tuple(rows[0]) != expected:
487
+ raise ActionRefused("NATIVE_EFFECT_KEY_MISMATCH")
488
+ self.markers.append({"id": effect["id"], "changed": True})
489
+ yield from self.images("post")
490
+ failures = yield from self.conditions("post")
491
+ if failures:
492
+ raise ActionFailed(
493
+ "POSTCONDITION_" + failures[0].code,
494
+ ValueError("native postcondition failed"),
495
+ self.details("pending"),
496
+ )
497
+ created: list[StrictModel] = []
498
+ changed: list[StrictModel] = []
499
+ combined: dict[str, Any] = {}
500
+ for index, effect in enumerate(self.program["effects"]):
501
+ identity = _json(
502
+ [
503
+ effect["entity"]["key"]["reference"],
504
+ [
505
+ {"carrier": f["carrier"], "value": str(self.resolve(v))}
506
+ for f, v in zip(
507
+ effect["entity"]["key"]["fields"],
508
+ effect["entity"]["components"],
509
+ strict=True,
510
+ )
511
+ ],
512
+ ]
513
+ )
514
+ before, after = (
515
+ self.pre["effect:" + str(index)],
516
+ self.post["effect:" + str(index)],
517
+ )
518
+ if identity not in combined:
519
+ combined[identity] = {
520
+ "entity": effect["entity"],
521
+ "before": None if before is None else {},
522
+ "after": None if after is None else {},
523
+ }
524
+ net = combined[identity]
525
+ for phase, row in (("before", before), ("after", after)):
526
+ if (net[phase] is None) != (row is None):
527
+ raise ActionRefused("NATIVE_ENTITY_IMAGE_DISAGREEMENT")
528
+ if row is not None:
529
+ net[phase].update(row)
530
+ for identity, net in combined.items():
531
+ before, after = net["before"], net["after"]
532
+ if before == after:
533
+ continue
534
+ key = self.key(net["entity"])
535
+ kind = (
536
+ "created"
537
+ if before is None and after is not None
538
+ else "deleted"
539
+ if after is None
540
+ else "updated"
541
+ )
542
+ self.changes.append({"kind": kind, "key": identity})
543
+ if kind == "created":
544
+ created.append(key)
545
+ elif kind == "updated":
546
+ changed.append(key)
547
+ result: Committed[object] = Committed(
548
+ None,
549
+ self.receipt,
550
+ tuple(created),
551
+ tuple(changed),
552
+ self.details("committed"),
553
+ )
554
+ yield from self.schema_admissions()
555
+ yield ("commit", result)
556
+ return result
557
+
558
+
559
+ class PostgresActionExecutor:
560
+ """One caller-owned idle connection, no retry, explicit host fence/custody."""
561
+
562
+ def __init__(
563
+ self,
564
+ connection: Any,
565
+ programs: tuple[NativeProgram, ...],
566
+ admission: NativeAdmission,
567
+ *,
568
+ default_timeout: timedelta,
569
+ reconnect: Callable[[], Any] | None = None,
570
+ ):
571
+ if (
572
+ type(default_timeout) is not timedelta
573
+ or not 0 < default_timeout.total_seconds() < 2_147_483
574
+ ):
575
+ raise ActionRefused("FINITE_DEFAULT_TIMEOUT_REQUIRED")
576
+ (
577
+ self.connection,
578
+ self.programs,
579
+ self.admission,
580
+ self.default_timeout,
581
+ self.reconnect,
582
+ ) = connection, programs, admission, default_timeout, reconnect
583
+ self.quarantined = False
584
+
585
+ def _state(
586
+ self, action: ActionRef[Any, Any], inputs: Mapping[str, object]
587
+ ) -> _State:
588
+ if self.quarantined:
589
+ raise ActionRefused("NATIVE_CONNECTION_QUARANTINED")
590
+ matching = [
591
+ p
592
+ for p in self.programs
593
+ if p.checked()["source"]["documentSha256"]
594
+ == getattr(action.source, "document_sha256", None)
595
+ and p.checked()["source"]["action"] == action.action
596
+ ]
597
+ if len(matching) != 1:
598
+ raise ActionRefused("NATIVE_ACTION_NOT_COMPILED")
599
+ if matching[0].checked().get("profile") != "umf.actions.native-sql/0.1":
600
+ raise ActionRefused("POSTGRESQL_NATIVE_PROFILE_REQUIRED")
601
+ return _State(action, matching[0], inputs)
602
+
603
+ def _quarantine(self, state: _State) -> Indeterminate:
604
+ self.quarantined = True
605
+ with contextlib.suppress(BaseException):
606
+ self.admission.quarantine(self.connection, state.scope)
607
+ return Indeterminate(state.details("indeterminate"))
608
+
609
+ def _run(
610
+ self,
611
+ action: ActionRef[Any, Any],
612
+ inputs: Mapping[str, object],
613
+ timeout: timedelta | None,
614
+ validate: bool,
615
+ ) -> ActionOutcome | ValidationResult:
616
+ state = self._state(action, inputs)
617
+ duration = self.default_timeout if timeout is None else timeout
618
+ if (
619
+ type(duration) is not timedelta
620
+ or not math.isfinite(duration.total_seconds())
621
+ or duration.total_seconds() <= 0
622
+ ):
623
+ raise ActionRefused("DEADLINE_EXPIRED")
624
+ deadline = time.monotonic() + duration.total_seconds()
625
+ fence = _catalog_fence_programs(state.program)
626
+ table_locks = mutation_locks(state.program)
627
+ began = False
628
+ committed: Committed[Any] | None = None
629
+ if self.connection.info.transaction_status != 0:
630
+ raise ActionRefused("IDLE_CONNECTION_REQUIRED")
631
+ try:
632
+ self.connection.execute(
633
+ "BEGIN ISOLATION LEVEL SERIALIZABLE"
634
+ + (" READ ONLY" if getattr(state, "read_only", False) else "")
635
+ )
636
+ began = True
637
+ if fence is not None:
638
+ self.connection.execute(_snapshot_free_timeout(deadline))
639
+ self.connection.execute(fence[0])
640
+ for lock_sql in table_locks:
641
+ self.connection.execute(_snapshot_free_timeout(deadline))
642
+ self.connection.execute(lock_sql)
643
+ if time.monotonic() >= deadline:
644
+ raise TimeoutError("native deadline")
645
+ self.connection.execute(
646
+ "SELECT pg_catalog.set_config('statement_timeout', %s, true)",
647
+ (str(max(1, math.ceil((deadline - time.monotonic()) * 1000))),),
648
+ )
649
+ state.scope = self.admission.admit(
650
+ self.connection, state.program, deadline=deadline
651
+ )
652
+ program = state.execute(validate)
653
+ result: Any = None
654
+ while True:
655
+ try:
656
+ operation = program.send(result)
657
+ except StopIteration as done:
658
+ return cast(ActionOutcome | ValidationResult, done.value)
659
+ if operation[0] == "query":
660
+ if time.monotonic() >= deadline:
661
+ raise TimeoutError("native deadline")
662
+ self.connection.execute(
663
+ "SELECT pg_catalog.set_config('statement_timeout', %s, true)",
664
+ (str(max(1, math.ceil((deadline - time.monotonic()) * 1000))),),
665
+ )
666
+ cursor = self.connection.execute(operation[1], operation[2])
667
+ result = (
668
+ []
669
+ if cursor.description is None
670
+ else cursor.fetchmany(operation[3] if len(operation) > 3 else 2)
671
+ )
672
+ elif operation[0] == "rollback":
673
+ self.connection.rollback()
674
+ began = False
675
+ result = None
676
+ elif operation[0] == "commit":
677
+ committed = operation[1]
678
+ self.connection.commit()
679
+ began = False
680
+ result = None
681
+ except BaseException as error:
682
+ if committed is not None:
683
+ if self.reconnect is not None and state.scope is not None:
684
+ recovered = None
685
+ try:
686
+ recovered = self.reconnect()
687
+ scope = self.admission.reconnect(
688
+ recovered, state.scope, deadline=time.monotonic() + 2
689
+ )
690
+ if (scope.store, scope.epoch) != (
691
+ state.scope.store,
692
+ state.scope.epoch,
693
+ ):
694
+ return self._quarantine(state)
695
+ status = recovered.execute(
696
+ "SELECT pg_catalog.pg_xact_status(%s::pg_catalog.xid8)",
697
+ (committed.receipt.version,),
698
+ ).fetchone()[0]
699
+ if status == "committed":
700
+ self._quarantine(state)
701
+ return committed
702
+ if status == "aborted":
703
+ raise ActionFailed(
704
+ "ABORTED_CAUSE_UNKNOWN",
705
+ error,
706
+ state.details("rolled-back"),
707
+ )
708
+ except ActionFailed:
709
+ raise
710
+ # Retain native failure custody across cleanup, cancellation and audit boundaries. Preserve the original failure without automatically logging native private details.
711
+ except BaseException: # noqa: BLE001, S110
712
+ pass
713
+ finally:
714
+ if recovered is not None:
715
+ recovered.close()
716
+ return self._quarantine(state)
717
+ if began:
718
+ try:
719
+ self.connection.rollback()
720
+ # Retain native failure custody across cleanup, cancellation and audit boundaries.
721
+ except BaseException: # noqa: BLE001
722
+ return self._quarantine(state)
723
+ details = state.details("rolled-back")
724
+ code = getattr(error, "sqlstate", None)
725
+ if code in ("40001", "40P01"):
726
+ return Conflict(False, code, details)
727
+ if code == "42501" or isinstance(error, ActionDenied):
728
+ return Denied(getattr(error, "code", "NATIVE_PRIVILEGE"), details)
729
+ if time.monotonic() >= deadline and (
730
+ code == "57014" or isinstance(error, TimeoutError)
731
+ ):
732
+ return TimedOut(details)
733
+ if isinstance(error, ActionRefused):
734
+ raise
735
+ raise ActionFailed(
736
+ getattr(error, "code", "NATIVE_ACTION_FAILED"), error, details
737
+ ) from error
738
+
739
+ def invoke(
740
+ self,
741
+ action: ActionRef[StrictModel, object],
742
+ input: Mapping[str, object],
743
+ *,
744
+ timeout: timedelta | None = None,
745
+ ) -> ActionOutcome:
746
+ return cast(ActionOutcome, self._run(action, input, timeout, False))
747
+
748
+ def validate(
749
+ self,
750
+ action: ActionRef[StrictModel, object],
751
+ input: Mapping[str, object],
752
+ *,
753
+ timeout: timedelta | None = None,
754
+ ) -> ValidationResult:
755
+ return cast(ValidationResult, self._run(action, input, timeout, True))
756
+
757
+
758
+ class AsyncNativeAdmission(Protocol):
759
+ async def admit(
760
+ self, connection: Any, program: Mapping[str, Any], *, deadline: float
761
+ ) -> NativeScope: ...
762
+ async def reconnect(
763
+ self, connection: Any, original: NativeScope, *, deadline: float
764
+ ) -> NativeScope: ...
765
+ async def quarantine(
766
+ self, connection: Any, original: NativeScope | None
767
+ ) -> None: ...
768
+
769
+
770
+ class AsyncPostgresActionExecutor:
771
+ """Native async driver for the same statement/state program; no worker thread."""
772
+
773
+ def __init__(
774
+ self,
775
+ connection: Any,
776
+ programs: tuple[NativeProgram, ...],
777
+ admission: AsyncNativeAdmission,
778
+ *,
779
+ default_timeout: timedelta,
780
+ reconnect: Any = None,
781
+ ):
782
+ if (
783
+ type(default_timeout) is not timedelta
784
+ or not 0 < default_timeout.total_seconds() < 2_147_483
785
+ ):
786
+ raise ActionRefused("FINITE_DEFAULT_TIMEOUT_REQUIRED")
787
+ (
788
+ self.connection,
789
+ self.programs,
790
+ self.admission,
791
+ self.default_timeout,
792
+ self.reconnect,
793
+ ) = connection, programs, admission, default_timeout, reconnect
794
+ self.quarantined = False
795
+
796
+ def _state(
797
+ self, action: ActionRef[Any, Any], inputs: Mapping[str, object]
798
+ ) -> _State:
799
+ if self.quarantined:
800
+ raise ActionRefused("NATIVE_CONNECTION_QUARANTINED")
801
+ matching = [
802
+ p
803
+ for p in self.programs
804
+ if p.checked()["source"]["documentSha256"]
805
+ == getattr(action.source, "document_sha256", None)
806
+ and p.checked()["source"]["action"] == action.action
807
+ ]
808
+ if len(matching) != 1:
809
+ raise ActionRefused("NATIVE_ACTION_NOT_COMPILED")
810
+ if matching[0].checked().get("profile") != "umf.actions.native-sql/0.1":
811
+ raise ActionRefused("POSTGRESQL_NATIVE_PROFILE_REQUIRED")
812
+ return _State(action, matching[0], inputs)
813
+
814
+ async def _quarantine(self, state: _State) -> Indeterminate:
815
+ import asyncio
816
+
817
+ self.quarantined = True
818
+ try:
819
+ async with asyncio.timeout(1):
820
+ await self.admission.quarantine(self.connection, state.scope)
821
+ # Retain native failure custody across cleanup, cancellation and audit boundaries. Preserve the original failure without automatically logging native private details.
822
+ except BaseException: # noqa: BLE001, S110
823
+ pass
824
+ return Indeterminate(state.details("indeterminate"))
825
+
826
+ async def _run(
827
+ self,
828
+ action: ActionRef[Any, Any],
829
+ inputs: Mapping[str, object],
830
+ timeout: timedelta | None,
831
+ validate: bool,
832
+ ) -> ActionOutcome | ValidationResult:
833
+ import asyncio
834
+
835
+ state = self._state(action, inputs)
836
+ duration = self.default_timeout if timeout is None else timeout
837
+ if (
838
+ type(duration) is not timedelta
839
+ or not math.isfinite(duration.total_seconds())
840
+ or duration.total_seconds() <= 0
841
+ ):
842
+ raise ActionRefused("DEADLINE_EXPIRED")
843
+ deadline = time.monotonic() + duration.total_seconds()
844
+ fence = _catalog_fence_programs(state.program)
845
+ table_locks = mutation_locks(state.program)
846
+ began = False
847
+ committed: Committed[Any] | None = None
848
+ if self.connection.info.transaction_status != 0:
849
+ raise ActionRefused("IDLE_CONNECTION_REQUIRED")
850
+ try:
851
+ async with asyncio.timeout(duration.total_seconds()):
852
+ await self.connection.execute(
853
+ "BEGIN ISOLATION LEVEL SERIALIZABLE"
854
+ + (" READ ONLY" if getattr(state, "read_only", False) else "")
855
+ )
856
+ began = True
857
+ if fence is not None:
858
+ await self.connection.execute(_snapshot_free_timeout(deadline))
859
+ await self.connection.execute(fence[0])
860
+ for lock_sql in table_locks:
861
+ await self.connection.execute(_snapshot_free_timeout(deadline))
862
+ await self.connection.execute(lock_sql)
863
+ if time.monotonic() >= deadline:
864
+ raise TimeoutError("native deadline")
865
+ await self.connection.execute(
866
+ "SELECT pg_catalog.set_config('statement_timeout', %s, true)",
867
+ (str(max(1, math.ceil((deadline - time.monotonic()) * 1000))),),
868
+ )
869
+ state.scope = await self.admission.admit(
870
+ self.connection, state.program, deadline=deadline
871
+ )
872
+ program = state.execute(validate)
873
+ result: Any = None
874
+ while True:
875
+ try:
876
+ operation = program.send(result)
877
+ except StopIteration as done:
878
+ return cast(ActionOutcome | ValidationResult, done.value)
879
+ if operation[0] == "query":
880
+ cursor = await self.connection.execute(
881
+ operation[1], operation[2]
882
+ )
883
+ result = (
884
+ []
885
+ if cursor.description is None
886
+ else await cursor.fetchmany(
887
+ operation[3] if len(operation) > 3 else 2
888
+ )
889
+ )
890
+ elif operation[0] == "rollback":
891
+ await self.connection.rollback()
892
+ began = False
893
+ result = None
894
+ elif operation[0] == "commit":
895
+ committed = operation[1]
896
+ await self.connection.commit()
897
+ began = False
898
+ result = None
899
+ # Retain native failure custody across cleanup, cancellation and audit boundaries.
900
+ except BaseException as error: # noqa: BLE001
901
+ # Settlement has its own finite bound and survives caller cancellation.
902
+ async def settle(
903
+ original_error: BaseException = error,
904
+ ) -> ActionOutcome | ValidationResult:
905
+ if committed is not None:
906
+ if self.reconnect is not None and state.scope is not None:
907
+ recovered = None
908
+ try:
909
+ recovered = await self.reconnect()
910
+ scope = await self.admission.reconnect(
911
+ recovered, state.scope, deadline=time.monotonic() + 2
912
+ )
913
+ if (scope.store, scope.epoch) != (
914
+ state.scope.store,
915
+ state.scope.epoch,
916
+ ):
917
+ return await self._quarantine(state)
918
+ cursor = await recovered.execute(
919
+ "SELECT pg_catalog.pg_xact_status(%s::pg_catalog.xid8)",
920
+ (committed.receipt.version,),
921
+ )
922
+ row = await cursor.fetchone()
923
+ status = None if row is None else row[0]
924
+ if status == "committed":
925
+ await self._quarantine(state)
926
+ return committed
927
+ if status == "aborted":
928
+ raise ActionFailed(
929
+ "ABORTED_CAUSE_UNKNOWN",
930
+ original_error,
931
+ state.details("rolled-back"),
932
+ )
933
+ except ActionFailed:
934
+ raise
935
+ # Retain native failure custody across cleanup, cancellation and audit boundaries. Preserve the original failure without automatically logging native private details.
936
+ except BaseException: # noqa: BLE001, S110
937
+ pass
938
+ finally:
939
+ if recovered is not None:
940
+ await recovered.close()
941
+ return await self._quarantine(state)
942
+ if began:
943
+ try:
944
+ await self.connection.rollback()
945
+ # Retain native failure custody across cleanup, cancellation and audit boundaries.
946
+ except BaseException: # noqa: BLE001
947
+ return await self._quarantine(state)
948
+ details = state.details("rolled-back")
949
+ code = getattr(original_error, "sqlstate", None)
950
+ if code in ("40001", "40P01"):
951
+ return Conflict(False, code, details)
952
+ if code == "42501" or isinstance(original_error, ActionDenied):
953
+ return Denied(
954
+ getattr(original_error, "code", "NATIVE_PRIVILEGE"), details
955
+ )
956
+ if time.monotonic() >= deadline and (
957
+ code == "57014" or isinstance(original_error, TimeoutError)
958
+ ):
959
+ return TimedOut(details)
960
+ if isinstance(original_error, ActionRefused):
961
+ raise original_error
962
+ raise ActionFailed(
963
+ getattr(
964
+ original_error,
965
+ "code",
966
+ "CANCELLED"
967
+ if isinstance(original_error, asyncio.CancelledError)
968
+ else "NATIVE_ACTION_FAILED",
969
+ ),
970
+ original_error,
971
+ details,
972
+ ) from original_error
973
+
974
+ async def bounded() -> ActionOutcome | ValidationResult:
975
+ try:
976
+ async with asyncio.timeout(3):
977
+ return await settle()
978
+ except TimeoutError:
979
+ return await self._quarantine(state)
980
+
981
+ task = asyncio.create_task(bounded())
982
+ while True:
983
+ try:
984
+ return await asyncio.shield(task)
985
+ except asyncio.CancelledError:
986
+ # Repeated caller cancellation still awaits this one finite
987
+ # original settlement; it never starts another operation.
988
+ if task.done():
989
+ return task.result()
990
+
991
+ async def invoke(
992
+ self,
993
+ action: ActionRef[StrictModel, object],
994
+ input: Mapping[str, object],
995
+ *,
996
+ timeout: timedelta | None = None,
997
+ ) -> ActionOutcome:
998
+ return cast(ActionOutcome, await self._run(action, input, timeout, False))
999
+
1000
+ async def validate(
1001
+ self,
1002
+ action: ActionRef[StrictModel, object],
1003
+ input: Mapping[str, object],
1004
+ *,
1005
+ timeout: timedelta | None = None,
1006
+ ) -> ValidationResult:
1007
+ return cast(ValidationResult, await self._run(action, input, timeout, True))