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,148 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Psycopg 3 synchronous per-call leases; the host owns connections and pools."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
from collections.abc import Callable, Iterator
|
|
9
|
+
from contextlib import AbstractContextManager, contextmanager
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
from .session_policy import (
|
|
13
|
+
GET_SETTING,
|
|
14
|
+
GET_SETTINGS,
|
|
15
|
+
ROLE_SETTINGS_CHECK,
|
|
16
|
+
SET_SETTINGS,
|
|
17
|
+
SETTING_NAMES,
|
|
18
|
+
SessionError,
|
|
19
|
+
SessionIdentity,
|
|
20
|
+
SessionPolicy,
|
|
21
|
+
_effective_settings,
|
|
22
|
+
_setting_values,
|
|
23
|
+
_tuple_row,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@contextmanager
|
|
28
|
+
def _lease(factory, identity):
|
|
29
|
+
lease = factory(identity)
|
|
30
|
+
connection = lease.__enter__()
|
|
31
|
+
try:
|
|
32
|
+
yield connection
|
|
33
|
+
except BaseException:
|
|
34
|
+
try:
|
|
35
|
+
lease.__exit__(*sys.exc_info())
|
|
36
|
+
except BaseException:
|
|
37
|
+
connection.close()
|
|
38
|
+
raise
|
|
39
|
+
raise
|
|
40
|
+
else:
|
|
41
|
+
try:
|
|
42
|
+
lease.__exit__(None, None, None)
|
|
43
|
+
except BaseException:
|
|
44
|
+
connection.close()
|
|
45
|
+
raise
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class SyncSession:
|
|
49
|
+
"""Use a factory returning a direct-connection or pool lease context manager.
|
|
50
|
+
|
|
51
|
+
The factory runs once per call, after authentication. It must release the
|
|
52
|
+
connection on exit and discard closed/broken connections. This adapter never
|
|
53
|
+
creates a pool, changes autocommit, or closes a healthy caller connection.
|
|
54
|
+
Create this object and its host pool after spawning a child process.
|
|
55
|
+
"""
|
|
56
|
+
def __init__(self, factory: Callable[[SessionIdentity], AbstractContextManager[Any]], policy: SessionPolicy,
|
|
57
|
+
*, transaction_owner: Literal["adapter", "caller"] = "adapter"):
|
|
58
|
+
if transaction_owner not in ("adapter", "caller"):
|
|
59
|
+
raise ValueError("transaction_owner must be adapter or caller")
|
|
60
|
+
self.transaction_owner = transaction_owner
|
|
61
|
+
self.factory = factory
|
|
62
|
+
self.policy = policy
|
|
63
|
+
self._pid = os.getpid()
|
|
64
|
+
self._active: set[int] = set()
|
|
65
|
+
self._lock = threading.Lock()
|
|
66
|
+
|
|
67
|
+
def _prepare_connection(self, connection):
|
|
68
|
+
return connection
|
|
69
|
+
|
|
70
|
+
def _control_cursor(self, connection):
|
|
71
|
+
return connection.cursor(row_factory=_tuple_row)
|
|
72
|
+
|
|
73
|
+
def control_cursor(self, native):
|
|
74
|
+
"""Private control work on an already leased connection; never acquire."""
|
|
75
|
+
return self._control_cursor(self._prepare_connection(native))
|
|
76
|
+
|
|
77
|
+
@contextmanager
|
|
78
|
+
def open(self, identity: SessionIdentity, *, read_only: bool = True) -> Iterator[Any]:
|
|
79
|
+
if os.getpid() != self._pid:
|
|
80
|
+
raise SessionError("create session factories and pools after process creation")
|
|
81
|
+
if type(read_only) is not bool:
|
|
82
|
+
raise ValueError("read_only must be bool")
|
|
83
|
+
settings = self.policy.settings(identity) # reject before acquiring a lease
|
|
84
|
+
with _lease(self.factory, identity) as connection:
|
|
85
|
+
key = id(connection)
|
|
86
|
+
with self._lock:
|
|
87
|
+
if key in self._active:
|
|
88
|
+
raise SessionError("connection already leased by this adapter")
|
|
89
|
+
self._active.add(key)
|
|
90
|
+
entered = False
|
|
91
|
+
try:
|
|
92
|
+
native = connection
|
|
93
|
+
connection = self._prepare_connection(native)
|
|
94
|
+
status = int(connection.info.transaction_status)
|
|
95
|
+
if status not in (0, 2):
|
|
96
|
+
raise SessionError("connection is not idle or in a healthy caller transaction")
|
|
97
|
+
owned = self.transaction_owner == "adapter"
|
|
98
|
+
if status != (0 if owned else 2):
|
|
99
|
+
raise SessionError("connection state differs from explicit transaction ownership")
|
|
100
|
+
transaction = connection.transaction()
|
|
101
|
+
try:
|
|
102
|
+
transaction.__enter__()
|
|
103
|
+
entered = True
|
|
104
|
+
except BaseException:
|
|
105
|
+
connection.close()
|
|
106
|
+
raise
|
|
107
|
+
with self._control_cursor(connection) as cursor:
|
|
108
|
+
if owned:
|
|
109
|
+
if read_only:
|
|
110
|
+
cursor.execute("SET TRANSACTION READ ONLY")
|
|
111
|
+
elif read_only:
|
|
112
|
+
cursor.execute(GET_SETTING, ("transaction_read_only",))
|
|
113
|
+
if cursor.fetchone() != ("on",):
|
|
114
|
+
raise SessionError("caller transaction must already be read-only")
|
|
115
|
+
previous = {}
|
|
116
|
+
if not owned:
|
|
117
|
+
cursor.execute(GET_SETTINGS)
|
|
118
|
+
previous = dict(zip(SETTING_NAMES,cursor.fetchone(),strict=True))
|
|
119
|
+
cursor.execute(SET_SETTINGS, _setting_values(settings))
|
|
120
|
+
cursor.execute(ROLE_SETTINGS_CHECK)
|
|
121
|
+
session_user,effective = _effective_settings(cursor.fetchone(),settings["role"])
|
|
122
|
+
yield native
|
|
123
|
+
with self._control_cursor(connection) as cursor:
|
|
124
|
+
cursor.execute(ROLE_SETTINGS_CHECK)
|
|
125
|
+
_,observed = _effective_settings(cursor.fetchone(),settings["role"],session_user)
|
|
126
|
+
if observed != effective:
|
|
127
|
+
raise SessionError("session settings changed during execution")
|
|
128
|
+
# RELEASE SAVEPOINT preserves SET LOCAL. Restore the caller's
|
|
129
|
+
# values explicitly before releasing a successful nested lease.
|
|
130
|
+
if not owned:
|
|
131
|
+
cursor.execute(SET_SETTINGS, _setting_values(previous))
|
|
132
|
+
entered = False
|
|
133
|
+
try:
|
|
134
|
+
transaction.__exit__(None, None, None)
|
|
135
|
+
except BaseException:
|
|
136
|
+
connection.close() # uncertain commit/cleanup must not recycle
|
|
137
|
+
raise
|
|
138
|
+
except BaseException:
|
|
139
|
+
if entered:
|
|
140
|
+
try:
|
|
141
|
+
transaction.__exit__(*sys.exc_info())
|
|
142
|
+
except BaseException:
|
|
143
|
+
connection.close()
|
|
144
|
+
raise
|
|
145
|
+
raise
|
|
146
|
+
finally:
|
|
147
|
+
with self._lock:
|
|
148
|
+
self._active.remove(key)
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Declared native reads with source approval, live correspondence and scoped paging.
|
|
3
|
+
|
|
4
|
+
The host supplies authenticated identities and session leases. Neither SQL nor
|
|
5
|
+
compiled programs are accepted from callers. Writes require the separate durable
|
|
6
|
+
outcome protocol and are deliberately refused by this read-only entry point.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import copy
|
|
12
|
+
import os
|
|
13
|
+
import threading
|
|
14
|
+
from uuid import uuid4
|
|
15
|
+
|
|
16
|
+
from .head_session import _check_principal, _drive, _drive_async, _prepare
|
|
17
|
+
from .operation_values import (
|
|
18
|
+
canonical,
|
|
19
|
+
digest,
|
|
20
|
+
loads,
|
|
21
|
+
native_arguments,
|
|
22
|
+
result_frame,
|
|
23
|
+
token_decode,
|
|
24
|
+
)
|
|
25
|
+
from .session_async import AsyncSession
|
|
26
|
+
from .session_policy import SessionError, SessionIdentity
|
|
27
|
+
from .session_sync import SyncSession
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _supported_obligations(value):
|
|
31
|
+
"""Recognize the compiler ABI without re-deriving its trusted source proof."""
|
|
32
|
+
return (type(value) is dict and set(value)=={
|
|
33
|
+
'consistency','cursorScope','nativeExecutionQualified','nativeFunctionAndOperatorClosure',
|
|
34
|
+
'replay','transaction','tableLifecycle'}
|
|
35
|
+
and value['consistency'] in ('statement','transaction')
|
|
36
|
+
and value['nativeExecutionQualified'] is False
|
|
37
|
+
and value['nativeFunctionAndOperatorClosure']=='required-before-execution'
|
|
38
|
+
and type(value['tableLifecycle']) is dict and set(value['tableLifecycle'])=={
|
|
39
|
+
'version','module','sourceDigest','configurationDigest','deploymentDigest','cursorScope',
|
|
40
|
+
'generationLock','installedAuthority','nativeExecutionQualified','policy','principal',
|
|
41
|
+
'privileges','roleScope','sourceInterpretation','tables'}
|
|
42
|
+
and value['tableLifecycle']['version']=='umf.table-lifecycle/0.1'
|
|
43
|
+
and value['tableLifecycle']['policy']=='source-command-policy-and-native-forced-rls'
|
|
44
|
+
and value['tableLifecycle']['principal']=='verified-person-or-batch'
|
|
45
|
+
and value['tableLifecycle']['privileges']=='source-grants-and-native-effective-closure'
|
|
46
|
+
and value['tableLifecycle']['roleScope']=='native-transitive-current'
|
|
47
|
+
and value['tableLifecycle']['sourceInterpretation']=='original-umf-deployment-compiler')
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _operation_scope(context, operation, target, inputs, size, items, profile):
|
|
51
|
+
scope = {key:context[key] for key in ('module','schema','sourceDigest','configurationDigest',
|
|
52
|
+
'bundleDigest','headDigest','referenceDigest')}
|
|
53
|
+
scope.update(operation=operation, target=target, inputsDigest=digest(inputs if items is None else items),
|
|
54
|
+
requestedSize=size, profile='python-sorted-json/0.1')
|
|
55
|
+
if profile == 'weft.table-operation-module/0.2':
|
|
56
|
+
scope['tableOperationModuleProfile'] = profile
|
|
57
|
+
return scope
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class _TableReader:
|
|
61
|
+
_mutation=False
|
|
62
|
+
def __init__(self, session: SyncSession | AsyncSession, bundle: dict[str, object],
|
|
63
|
+
reference: dict[str, object], binding: dict[str, object], *,
|
|
64
|
+
cursor_secret: bytes, target: str = 'postgresql18', _source_owner=None):
|
|
65
|
+
if target not in ('postgresql18', 'lakebase18'):
|
|
66
|
+
raise ValueError('an explicit PostgreSQL 18 target is required')
|
|
67
|
+
if type(cursor_secret) is not bytes or len(cursor_secret) < 32:
|
|
68
|
+
raise ValueError('cursor root secret requires at least 256 bits')
|
|
69
|
+
self._session = session
|
|
70
|
+
self._source_owner = self if _source_owner is None else _source_owner
|
|
71
|
+
self._table_operation_module_profile = session.policy.table_operation_module_profile
|
|
72
|
+
if _source_owner is None:
|
|
73
|
+
self._bundle, self._reference, self._binding = copy.deepcopy((bundle, reference, binding))
|
|
74
|
+
else:
|
|
75
|
+
if _source_owner._table_operation_module_profile != self._table_operation_module_profile:
|
|
76
|
+
raise SessionError('table operation module profile differs from shared source owner')
|
|
77
|
+
self._bundle, self._reference, self._binding = (_source_owner._bundle, _source_owner._reference, _source_owner._binding)
|
|
78
|
+
self._secret, self._target = cursor_secret, target
|
|
79
|
+
self._source_pid = os.getpid()
|
|
80
|
+
self._source_lock = threading.Lock()
|
|
81
|
+
self._source_state = self._source_policy = None
|
|
82
|
+
self._queries = {}
|
|
83
|
+
self._operation_module = None
|
|
84
|
+
self._operations = {}
|
|
85
|
+
self._descriptions = {}
|
|
86
|
+
|
|
87
|
+
def _prepare(self, identity, operation, inputs, size, cursor, *, items=None, key=None):
|
|
88
|
+
"""Prepare from one private copy for internal callers that pass shared data."""
|
|
89
|
+
owned_inputs, owned_items = copy.deepcopy((inputs, items))
|
|
90
|
+
return self._prepare_owned(
|
|
91
|
+
identity, operation, owned_inputs, size, cursor, items=owned_items, key=key
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
def _source_for(self, identity):
|
|
95
|
+
if self._source_owner is not self:
|
|
96
|
+
if self._session.policy.table_operation_module_profile != self._source_owner._table_operation_module_profile:
|
|
97
|
+
raise SessionError('table operation module profile differs from shared source owner')
|
|
98
|
+
return self._source_owner._source_for(identity)
|
|
99
|
+
if os.getpid() != self._source_pid:
|
|
100
|
+
raise SessionError("create session factories and pools after process creation")
|
|
101
|
+
policy = self._session.policy
|
|
102
|
+
if policy.table_operation_module_profile != self._table_operation_module_profile:
|
|
103
|
+
raise SessionError('table operation module profile differs from prepared source owner')
|
|
104
|
+
role = policy.role(identity)
|
|
105
|
+
# The constructor owns these source/reference/binding snapshots. Cache
|
|
106
|
+
# only source meaning, never a lease, principal or native observation.
|
|
107
|
+
with self._source_lock:
|
|
108
|
+
if self._source_state is None or self._source_policy is not policy:
|
|
109
|
+
probe = _prepare(self._session, identity, self._bundle, self._reference, True)
|
|
110
|
+
context = probe.binding_context
|
|
111
|
+
binding = self._binding
|
|
112
|
+
expected = {'version':'umf.table-lifecycle/0.1', 'module':context['module'],
|
|
113
|
+
'configurationDigest':context['configurationDigest'], 'deploymentDigest':context['bundleDigest']}
|
|
114
|
+
if (binding.get('modelJson') != context['sourceUtf8']
|
|
115
|
+
or binding.get('modelSha256') != context['sourceDigest']
|
|
116
|
+
or binding.get('schema') != context['schema'] or binding.get('nativeLifecycle') != expected):
|
|
117
|
+
raise SessionError('operation binding differs from the approved source')
|
|
118
|
+
source = loads(context['sourceUtf8'])
|
|
119
|
+
module = next(m for m in source['modules'] if m['id'] == context['module'])
|
|
120
|
+
declarations = {c['id']:c for c in module['extensions']['umf.tables'].get('commands', [])}
|
|
121
|
+
# Query ASTs are lazy: unused/unsupported declarations do not
|
|
122
|
+
# block independent CRUD or multiply first-use schema work.
|
|
123
|
+
self._queries = {}
|
|
124
|
+
self._operation_module = None
|
|
125
|
+
self._operations = {}
|
|
126
|
+
self._descriptions = {}
|
|
127
|
+
self._source_state = (probe,context,source,declarations)
|
|
128
|
+
self._source_policy = policy
|
|
129
|
+
template,context,source,declarations = self._source_state
|
|
130
|
+
probe = template.for_principal(principal_role=role,audience=identity.kind)
|
|
131
|
+
return probe,context,source,declarations
|
|
132
|
+
|
|
133
|
+
def _prepared_for(self, context, operation, *, query=False):
|
|
134
|
+
owner = self._source_owner
|
|
135
|
+
if (self._session.policy.table_operation_module_profile != self._table_operation_module_profile
|
|
136
|
+
or owner._table_operation_module_profile != self._table_operation_module_profile):
|
|
137
|
+
raise SessionError('table operation module profile differs from prepared source owner')
|
|
138
|
+
with owner._source_lock:
|
|
139
|
+
cache = owner._queries if query else owner._operations
|
|
140
|
+
prepared = cache.get(operation)
|
|
141
|
+
if prepared is None:
|
|
142
|
+
try:
|
|
143
|
+
if owner._operation_module is None:
|
|
144
|
+
from weft import prepare_table_operation_module_json
|
|
145
|
+
owner._operation_module = prepare_table_operation_module_json(canonical({
|
|
146
|
+
'version':self._table_operation_module_profile,'target':self._target,
|
|
147
|
+
'binding':owner._binding,'module':context['module']}))
|
|
148
|
+
prepared = (owner._operation_module.prepare_query(operation) if query
|
|
149
|
+
else owner._operation_module.prepare(operation))
|
|
150
|
+
except ValueError as error:
|
|
151
|
+
raise SessionError('declared read compilation refused') from error
|
|
152
|
+
if query:
|
|
153
|
+
prepared = (prepared, loads(prepared.program_json()))
|
|
154
|
+
cache[operation] = prepared
|
|
155
|
+
return prepared
|
|
156
|
+
|
|
157
|
+
def _prepare_owned(self, identity, operation, inputs, size, cursor, *, items=None, key=None):
|
|
158
|
+
probe, context, _source, declarations = self._source_for(identity)
|
|
159
|
+
declaration = declarations.get(operation) if type(operation) is str else None
|
|
160
|
+
if declaration is None:
|
|
161
|
+
raise SessionError('operation is not declared in this module')
|
|
162
|
+
if declaration.get('version') != 'umf.table-operation/0.1':
|
|
163
|
+
# Typed row expressions are migration-only at this runtime version.
|
|
164
|
+
# Refuse before program binding or any SQL/authority acquisition.
|
|
165
|
+
raise SessionError('unsupported ordinary table operation version')
|
|
166
|
+
query=declaration['body']['kind']=='query'
|
|
167
|
+
read=query or declaration['body']['kind']=='read'
|
|
168
|
+
if query and (size is not None or cursor is not None or items is not None):
|
|
169
|
+
raise SessionError('fixed queries do not accept paging or batches')
|
|
170
|
+
if not read and not self._mutation:
|
|
171
|
+
raise SessionError('writes require the durable outcome executor')
|
|
172
|
+
if read and self._mutation:
|
|
173
|
+
raise SessionError('a declared mutation is required')
|
|
174
|
+
secret = self._session.policy.cursor_secret(identity, self._secret)
|
|
175
|
+
scope = _operation_scope(context,operation,self._target,inputs,size,items,
|
|
176
|
+
self._table_operation_module_profile)
|
|
177
|
+
token = token_decode(secret, cursor) if cursor is not None else None
|
|
178
|
+
if token is not None and any(token['scope'].get(k) != v for k,v in scope.items()):
|
|
179
|
+
raise SessionError('cursor differs from this operation scope')
|
|
180
|
+
call = {'kind':'single', 'inputs':inputs}
|
|
181
|
+
if items is not None:
|
|
182
|
+
call={'kind':'batch','items':items}
|
|
183
|
+
if size is not None:
|
|
184
|
+
call['size'] = size
|
|
185
|
+
if token is not None:
|
|
186
|
+
call['after'] = token['after']
|
|
187
|
+
invocation = {'call':call}
|
|
188
|
+
if not read:
|
|
189
|
+
if key is None and declaration['replay']=='caller-key-optional':
|
|
190
|
+
key=uuid4().hex
|
|
191
|
+
if key is not None:
|
|
192
|
+
invocation['idempotencyKey']=key
|
|
193
|
+
# This exact optional public compiler boundary owns all statement text,
|
|
194
|
+
# parameter order, native scalar coercions and server-side frame guards.
|
|
195
|
+
# This is trusted in-process compiler output. External stored programs
|
|
196
|
+
# need Weft checking at their ingress; this API accepts no such program.
|
|
197
|
+
if query:
|
|
198
|
+
prepared,template=self._prepared_for(context,operation,query=True)
|
|
199
|
+
bound=loads(prepared.bind_json(canonical({'inputs':inputs})))
|
|
200
|
+
if type(bound) is not dict or set(bound)!={'nativeInputs'}:
|
|
201
|
+
raise SessionError('declared read compilation refused')
|
|
202
|
+
program={**template,'nativeInputs':bound['nativeInputs']}
|
|
203
|
+
else:
|
|
204
|
+
prepared=self._prepared_for(context,operation)
|
|
205
|
+
program=loads(prepared.bind_json(canonical(invocation)))
|
|
206
|
+
if program.get('status') != 'compiled':
|
|
207
|
+
raise SessionError('declared read compilation refused')
|
|
208
|
+
guard = {'profile':'pg18-read-frame/0.1', 'maxNativeBytes':8388608, 'sqlstate':'22012',
|
|
209
|
+
'includesLookahead':True, 'partialFrames':False}
|
|
210
|
+
valid_read=(program['result']['kind'] in ('many','one','optional','page','count')
|
|
211
|
+
and program['result']['nativeReadGuard']==guard)
|
|
212
|
+
valid_write=(program['result']['kind']=='mutation' and program['result']['nativeReadGuard'] is None
|
|
213
|
+
and program['result'].get('nativeWriteFrameGuard')=={**guard,'profile':'pg18-write-frame/0.1','includesLookahead':False}
|
|
214
|
+
and program['result']['nativeBoundGuard']=={'profile':'pg18-effect-count/0.1','sqlstate':'22012',
|
|
215
|
+
'excessEffects':'statement-error-and-transaction-rollback','writeLimitClipping':False})
|
|
216
|
+
if (not (valid_read if read else valid_write)
|
|
217
|
+
or program['version'] != 'weft.table-operation/0.1'
|
|
218
|
+
or not _supported_obligations(program['obligations'])
|
|
219
|
+
or program['transport'] != {'profile':'dbapi-percent/0.1','bindEmptyParameterTuple':True}):
|
|
220
|
+
raise SessionError('unsupported declared read execution profile')
|
|
221
|
+
return probe, program, scope, secret, token
|
|
222
|
+
|
|
223
|
+
def _before(self, identity, prepared, observed):
|
|
224
|
+
_check_principal(self._session, identity, observed)
|
|
225
|
+
scope = prepared[2]
|
|
226
|
+
scope.update(principalOid=observed['principalOid'], roleScopeDigest=observed['roleScopeDigest'])
|
|
227
|
+
token = prepared[4]
|
|
228
|
+
if token is not None and token['scope'] != scope:
|
|
229
|
+
raise SessionError('cursor authority changed')
|
|
230
|
+
|
|
231
|
+
def _needs_description(self, program):
|
|
232
|
+
with self._source_lock:
|
|
233
|
+
return program['operation'] in self._queries and program['operation'] not in self._descriptions
|
|
234
|
+
|
|
235
|
+
def _accept_description(self, cursor, program):
|
|
236
|
+
# OIDs here describe the original typed SELECT, before wire formatting.
|
|
237
|
+
# No nullability/domain guarantee is inferred from native OIDs.
|
|
238
|
+
allowed={'boolean':{16},'integer':{20,21,23},'decimal':{1700},
|
|
239
|
+
'string':{25,1042,1043},'float':{701},'date':{1082},
|
|
240
|
+
'timestamp':{1184},'uuid':{2950},'bits128':{17}}
|
|
241
|
+
description=getattr(cursor,'native_description',None)
|
|
242
|
+
if description is None:description=cursor.description
|
|
243
|
+
if len(description)!=len(program['outputs']):
|
|
244
|
+
raise SessionError('declared query result type differs')
|
|
245
|
+
metadata=[]
|
|
246
|
+
for column,output in zip(description,program['outputs']):
|
|
247
|
+
if (len(column)<2 or column[0]!=output['name']
|
|
248
|
+
or column[1] not in allowed.get(output['carrier'],())):
|
|
249
|
+
raise SessionError('declared query result type differs')
|
|
250
|
+
metadata.append((column[0],column[1]))
|
|
251
|
+
# A concurrent first call may describe the same immutable query. Never
|
|
252
|
+
# hold a Python lock over driver I/O or cache a connection/authorization.
|
|
253
|
+
with self._source_lock:self._descriptions[program['operation']]=tuple(metadata)
|
|
254
|
+
|
|
255
|
+
@staticmethod
|
|
256
|
+
def _columns(cursor, program):
|
|
257
|
+
if [c[0] for c in cursor.description] != [o['name'] for o in program['outputs']]:
|
|
258
|
+
raise SessionError('native read columns differ')
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
class SyncTableReader(_TableReader):
|
|
262
|
+
"""Synchronous declared reads through a per-call native session factory."""
|
|
263
|
+
def read(self, identity: SessionIdentity, operation: str, inputs: dict[str, object], *,
|
|
264
|
+
size: int | None = None, cursor: str | None = None) -> dict[str, object]:
|
|
265
|
+
try:
|
|
266
|
+
owned_inputs = copy.deepcopy(inputs)
|
|
267
|
+
prepared = self._prepare_owned(identity, operation, owned_inputs, size, cursor)
|
|
268
|
+
probe, program, scope, secret, _ = prepared
|
|
269
|
+
with self._session.open(identity, read_only=True) as native:
|
|
270
|
+
before = _drive(self._session, native, probe.operation_steps())
|
|
271
|
+
self._before(identity, prepared, before)
|
|
272
|
+
if self._needs_description(program):
|
|
273
|
+
with self._session.control_cursor(native) as description:
|
|
274
|
+
description.execute(program['nativeDescriptionSql'], native_arguments(program))
|
|
275
|
+
self._accept_description(description,program)
|
|
276
|
+
with self._session.control_cursor(native) as result:
|
|
277
|
+
result.execute(program['dbapiSql'], native_arguments(program))
|
|
278
|
+
self._columns(result, program)
|
|
279
|
+
rows = result.fetchall()
|
|
280
|
+
response = result_frame(program, rows, scope, secret)
|
|
281
|
+
return response
|
|
282
|
+
except SessionError:
|
|
283
|
+
raise
|
|
284
|
+
except Exception: # noqa: BLE001 -- sanitize optional native-driver/verifier errors at the SDK boundary
|
|
285
|
+
raise SessionError('native declared read failed') from None
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class AsyncTableReader(_TableReader):
|
|
289
|
+
"""Async declared reads; cancellation propagates after session cleanup."""
|
|
290
|
+
async def read(self, identity: SessionIdentity, operation: str, inputs: dict[str, object], *,
|
|
291
|
+
size: int | None = None, cursor: str | None = None) -> dict[str, object]:
|
|
292
|
+
try:
|
|
293
|
+
owned_inputs = copy.deepcopy(inputs)
|
|
294
|
+
prepared = await asyncio.to_thread(
|
|
295
|
+
self._prepare_owned, identity, operation, owned_inputs, size, cursor
|
|
296
|
+
)
|
|
297
|
+
probe, program, scope, secret, _ = prepared
|
|
298
|
+
async with self._session.open(identity, read_only=True) as native:
|
|
299
|
+
before = await _drive_async(self._session, native, probe.operation_steps())
|
|
300
|
+
self._before(identity, prepared, before)
|
|
301
|
+
if self._needs_description(program):
|
|
302
|
+
async with self._session.control_cursor(native) as description:
|
|
303
|
+
await description.execute(program['nativeDescriptionSql'], native_arguments(program))
|
|
304
|
+
self._accept_description(description,program)
|
|
305
|
+
async with self._session.control_cursor(native) as result:
|
|
306
|
+
await result.execute(program['dbapiSql'], native_arguments(program))
|
|
307
|
+
self._columns(result, program)
|
|
308
|
+
rows = await result.fetchall()
|
|
309
|
+
response = result_frame(program, rows, scope, secret)
|
|
310
|
+
return response
|
|
311
|
+
except SessionError:
|
|
312
|
+
raise
|
|
313
|
+
except Exception: # noqa: BLE001 -- sanitize optional native-driver/verifier errors at the SDK boundary
|
|
314
|
+
raise SessionError('native declared read failed') from None
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Declared atomic mutations and authenticated effect-only recovery over Weft."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import copy
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
from .head_session import _drive, _drive_async
|
|
10
|
+
from .operation_values import (
|
|
11
|
+
MAX_FRAME,
|
|
12
|
+
bounded_size,
|
|
13
|
+
digest,
|
|
14
|
+
loads,
|
|
15
|
+
native_arguments,
|
|
16
|
+
native_batch_arguments,
|
|
17
|
+
value_from_native,
|
|
18
|
+
)
|
|
19
|
+
from .outcome_values import (
|
|
20
|
+
outcome_from_record,
|
|
21
|
+
outcome_invocation,
|
|
22
|
+
outcome_record,
|
|
23
|
+
outcome_slot,
|
|
24
|
+
)
|
|
25
|
+
from .session_policy import SessionError, SessionIdentity
|
|
26
|
+
from .table_reads import _TableReader
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class WriteOutcomeUnknown(SessionError):
|
|
30
|
+
"""Commit/lease completion failed after execution; observe this key afresh."""
|
|
31
|
+
def __init__(self, key):
|
|
32
|
+
super().__init__('native write outcome is unknown; observe its outcome key')
|
|
33
|
+
self.key=key
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class _Frame:
|
|
38
|
+
statement: str
|
|
39
|
+
parameters: tuple
|
|
40
|
+
kind: str = 'frame'
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _effect_frames(program):
|
|
44
|
+
"""Decode the same ordered item results for scalar and set-based programs."""
|
|
45
|
+
outputs = program['outputs']
|
|
46
|
+
names = [output['name'] for output in outputs] + [program['result']['affectedMarker']]
|
|
47
|
+
count = len(program['nativeInputs'])
|
|
48
|
+
batch = program.get('nativeBatch')
|
|
49
|
+
batch_rows = None
|
|
50
|
+
if batch is not None:
|
|
51
|
+
columns, batch_rows = yield _Frame(batch['dbapiSql'], native_batch_arguments(program))
|
|
52
|
+
if columns != [batch['ordinalColumn'], *names] or len(batch_rows) != count:
|
|
53
|
+
raise SessionError('native batch mutation frame differs')
|
|
54
|
+
effects, frames, wire_size = [], [], 0
|
|
55
|
+
for index in range(count):
|
|
56
|
+
if batch_rows is None:
|
|
57
|
+
columns, rows = yield _Frame(program['dbapiSql'], native_arguments(program, index))
|
|
58
|
+
if columns != names:
|
|
59
|
+
raise SessionError('native mutation frame differs')
|
|
60
|
+
else:
|
|
61
|
+
row = batch_rows[index]
|
|
62
|
+
if not row or type(row[0]) is not int or row[0] != index:
|
|
63
|
+
raise SessionError('native batch mutation ordinal differs')
|
|
64
|
+
rows = [row[1:]]
|
|
65
|
+
if len(rows) > program['result']['maxRows']:
|
|
66
|
+
raise SessionError('native mutation frame differs')
|
|
67
|
+
decoded = []
|
|
68
|
+
for row in rows:
|
|
69
|
+
if len(row) != len(outputs) + 1 or type(row[-1]) is not int or row[-1] != 1:
|
|
70
|
+
raise SessionError('native effect marker differs')
|
|
71
|
+
if outputs:
|
|
72
|
+
decoded.append({out['field']['element']: value_from_native(value, out)
|
|
73
|
+
for out, value in zip(outputs, row[:-1], strict=True)})
|
|
74
|
+
frame = {'affectedCount': {'integerToken': str(len(rows))}, 'rows': decoded}
|
|
75
|
+
wire_size += bounded_size(frame)
|
|
76
|
+
if wire_size > MAX_FRAME:
|
|
77
|
+
raise SessionError('native mutation wire bound exceeded')
|
|
78
|
+
effects.append(len(rows))
|
|
79
|
+
frames.append(frame)
|
|
80
|
+
return effects, frames
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class _TableWriter(_TableReader):
|
|
84
|
+
_mutation=True
|
|
85
|
+
|
|
86
|
+
def __init__(self, session, bundle, reference, binding, *, outcome_secret: bytes, target='postgresql18', _source_owner=None):
|
|
87
|
+
super().__init__(session,bundle,reference,binding,cursor_secret=outcome_secret,target=target,_source_owner=_source_owner)
|
|
88
|
+
|
|
89
|
+
def _write_prepare(self, identity, operation, inputs, key, items):
|
|
90
|
+
owned_inputs, owned_items = copy.deepcopy((inputs, items))
|
|
91
|
+
return self._write_prepare_owned(identity, operation, owned_inputs, key, owned_items)
|
|
92
|
+
|
|
93
|
+
def _write_prepare_owned(self, identity, operation, inputs, key, items):
|
|
94
|
+
prepared=self._prepare_owned(identity,operation,inputs,None,None,key=key,items=items)
|
|
95
|
+
batch = prepared[1].get('nativeBatch')
|
|
96
|
+
if batch is not None and batch.get('version') != 'weft.table-insert-batch/0.1':
|
|
97
|
+
raise SessionError('unsupported native batch execution profile')
|
|
98
|
+
# Refuse old read-only installations before acquiring a lease.
|
|
99
|
+
prepared[0].outcome_steps('read',1,'0'*64)
|
|
100
|
+
return prepared
|
|
101
|
+
|
|
102
|
+
def _steps(self, identity, prepared, observe):
|
|
103
|
+
probe,program,scope,_,_=prepared
|
|
104
|
+
before=yield from probe.operation_steps()
|
|
105
|
+
self._before(identity,prepared,before)
|
|
106
|
+
key=program['idempotencyKey']
|
|
107
|
+
principal=before['principalOid']
|
|
108
|
+
slot=outcome_slot(identity,principal,scope,program['operation'],key)
|
|
109
|
+
yield from probe.outcome_steps('lock',principal,slot)
|
|
110
|
+
stored=yield from probe.outcome_steps('read',principal,slot)
|
|
111
|
+
scope_digest=digest({k:v for k,v in scope.items() if k!='inputsDigest'})
|
|
112
|
+
invocation=outcome_invocation(self._secret,[scope,program['declarationDigest'],program['callKind']])
|
|
113
|
+
metadata={k:scope[k] for k in ('module','operation','sourceDigest','configurationDigest','bundleDigest','headDigest')}
|
|
114
|
+
metadata.update(invocationDigest=invocation,scopeDigest=scope_digest)
|
|
115
|
+
if stored is not None:
|
|
116
|
+
receipt=outcome_from_record(self._secret,principal,slot,stored,metadata,
|
|
117
|
+
items=len(program['nativeInputs']),max_rows=program['result']['maxRows'])
|
|
118
|
+
response={'status':'recovered','receipt':receipt}
|
|
119
|
+
elif observe:
|
|
120
|
+
response={'status':'not-observed'}
|
|
121
|
+
else:
|
|
122
|
+
effects,frames=yield from _effect_frames(program)
|
|
123
|
+
fresh={'module':program['module'],'operation':program['operation'],'sourceDigest':scope['sourceDigest'],'items':frames}
|
|
124
|
+
bounded_size(fresh)
|
|
125
|
+
record=outcome_record(self._secret,principal,slot,metadata,effects,fresh)
|
|
126
|
+
yield from probe.outcome_steps('insert',principal,slot,record)
|
|
127
|
+
response={'status':'applied','result':fresh,'receipt':loads(record['payload'])}
|
|
128
|
+
response.update(version='umf.table-write-result/0.1',key=key,
|
|
129
|
+
commitResponsibility=self._session.transaction_owner,
|
|
130
|
+
durability='pending-caller-commit' if self._session.transaction_owner=='caller' else 'committed')
|
|
131
|
+
if response['status']=='not-observed':response['durability']='not-observed'
|
|
132
|
+
bounded_size(response)
|
|
133
|
+
return response
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class SyncTableWriter(_TableWriter):
|
|
137
|
+
"""Sync declared writes; no automatic retry and no historical row replay."""
|
|
138
|
+
def _invoke(self, identity, operation, inputs, key, items, observe):
|
|
139
|
+
response=None
|
|
140
|
+
try:
|
|
141
|
+
owned_inputs, owned_items = copy.deepcopy((inputs, items))
|
|
142
|
+
prepared=self._write_prepare_owned(identity,operation,owned_inputs,key,owned_items)
|
|
143
|
+
key=prepared[1]['idempotencyKey']
|
|
144
|
+
with self._session.open(identity,read_only=observe and self._session.transaction_owner=='adapter') as native:
|
|
145
|
+
response=_drive(self._session,native,self._steps(identity,prepared,observe))
|
|
146
|
+
return response
|
|
147
|
+
except Exception as error:
|
|
148
|
+
if response is not None:raise WriteOutcomeUnknown(key) from None
|
|
149
|
+
if isinstance(error,SessionError):raise
|
|
150
|
+
raise SessionError('native declared mutation failed') from None
|
|
151
|
+
|
|
152
|
+
def write(self, identity: SessionIdentity, operation: str, inputs: dict[str, object], *, key: str | None=None):
|
|
153
|
+
return self._invoke(identity,operation,inputs,key,None,False)
|
|
154
|
+
|
|
155
|
+
def write_batch(self, identity: SessionIdentity, operation: str, items: list[dict[str, object]], *, key: str | None=None):
|
|
156
|
+
return self._invoke(identity,operation,None,key,items,False)
|
|
157
|
+
|
|
158
|
+
def observe(self, identity: SessionIdentity, operation: str, inputs: dict[str, object], *, key: str):
|
|
159
|
+
return self._invoke(identity,operation,inputs,key,None,True)
|
|
160
|
+
|
|
161
|
+
def observe_batch(self, identity: SessionIdentity, operation: str, items: list[dict[str, object]], *, key: str):
|
|
162
|
+
return self._invoke(identity,operation,None,key,items,True)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class AsyncTableWriter(_TableWriter):
|
|
166
|
+
"""Async counterpart; cancellation propagates after shielded session cleanup."""
|
|
167
|
+
async def _invoke(self, identity, operation, inputs, key, items, observe):
|
|
168
|
+
response=None
|
|
169
|
+
try:
|
|
170
|
+
owned_inputs, owned_items = copy.deepcopy((inputs, items))
|
|
171
|
+
prepared=await asyncio.to_thread(
|
|
172
|
+
self._write_prepare_owned, identity, operation, owned_inputs, key, owned_items
|
|
173
|
+
)
|
|
174
|
+
key=prepared[1]['idempotencyKey']
|
|
175
|
+
async with self._session.open(identity,read_only=observe and self._session.transaction_owner=='adapter') as native:
|
|
176
|
+
response=await _drive_async(self._session,native,self._steps(identity,prepared,observe))
|
|
177
|
+
return response
|
|
178
|
+
except Exception as error:
|
|
179
|
+
if response is not None:raise WriteOutcomeUnknown(key) from None
|
|
180
|
+
if isinstance(error,SessionError):raise
|
|
181
|
+
raise SessionError('native declared mutation failed') from None
|
|
182
|
+
|
|
183
|
+
async def write(self, identity: SessionIdentity, operation: str, inputs: dict[str, object], *, key: str | None=None):
|
|
184
|
+
return await self._invoke(identity,operation,inputs,key,None,False)
|
|
185
|
+
|
|
186
|
+
async def write_batch(self, identity: SessionIdentity, operation: str, items: list[dict[str, object]], *, key: str | None=None):
|
|
187
|
+
return await self._invoke(identity,operation,None,key,items,False)
|
|
188
|
+
|
|
189
|
+
async def observe(self, identity: SessionIdentity, operation: str, inputs: dict[str, object], *, key: str):
|
|
190
|
+
return await self._invoke(identity,operation,inputs,key,None,True)
|
|
191
|
+
|
|
192
|
+
async def observe_batch(self, identity: SessionIdentity, operation: str, items: list[dict[str, object]], *, key: str):
|
|
193
|
+
return await self._invoke(identity,operation,None,key,items,True)
|