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,161 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Pure codecs and validation for the original owner-authority wire records."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import re
|
|
7
|
+
import uuid
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from ..canonical import canonical_json
|
|
11
|
+
|
|
12
|
+
OWNER_AUTHORITY_PROFILE = 'umf.configured-owner-authority/0.1'
|
|
13
|
+
OWNER_PURPOSES = ('production', 'native-acceptance')
|
|
14
|
+
OWNER_SCOPES = (
|
|
15
|
+
'local-target-creation', 'local-target-registration',
|
|
16
|
+
'native-principal-preparation', 'native-store-creation',
|
|
17
|
+
'disabled-epoch-provision', 'generation-ingress-transition',
|
|
18
|
+
)
|
|
19
|
+
_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
|
|
20
|
+
_B64URL = re.compile(r'^[A-Za-z0-9_-]+$')
|
|
21
|
+
_MAX_CONFIG = 1_048_576
|
|
22
|
+
_MAX_NODES = 100_000
|
|
23
|
+
_MAX_DEPTH = 48
|
|
24
|
+
_MAX_SAFE_INTEGER = 9_007_199_254_740_991
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class OwnerWireError(ValueError):
|
|
28
|
+
"""Fixed validation failure for original owner wire data."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, code: str = 'owner-authority-invalid') -> None:
|
|
31
|
+
super().__init__(code)
|
|
32
|
+
self.code = code
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _plain_json(value: object) -> object:
|
|
36
|
+
stack = [(value, 0)]
|
|
37
|
+
nodes = 0
|
|
38
|
+
while stack:
|
|
39
|
+
item, depth = stack.pop()
|
|
40
|
+
nodes += 1
|
|
41
|
+
if nodes > _MAX_NODES or depth > _MAX_DEPTH:
|
|
42
|
+
raise OwnerWireError('owner-authority-capacity')
|
|
43
|
+
if item is None or type(item) is bool:
|
|
44
|
+
continue
|
|
45
|
+
if type(item) is int:
|
|
46
|
+
if abs(item) > _MAX_SAFE_INTEGER:
|
|
47
|
+
raise OwnerWireError
|
|
48
|
+
elif type(item) is str:
|
|
49
|
+
if '\x00' in item:
|
|
50
|
+
raise OwnerWireError
|
|
51
|
+
try:
|
|
52
|
+
if len(item.encode('utf-8')) > _MAX_CONFIG:
|
|
53
|
+
raise OwnerWireError
|
|
54
|
+
except UnicodeEncodeError:
|
|
55
|
+
raise OwnerWireError from None
|
|
56
|
+
elif type(item) is list:
|
|
57
|
+
if len(item) > 4096:
|
|
58
|
+
raise OwnerWireError('owner-authority-capacity')
|
|
59
|
+
stack.extend((child, depth + 1) for child in item)
|
|
60
|
+
elif type(item) is dict:
|
|
61
|
+
if len(item) > 128 or any(type(key) is not str or not key.isascii()
|
|
62
|
+
for key in item):
|
|
63
|
+
raise OwnerWireError
|
|
64
|
+
stack.extend((key, depth + 1) for key in item)
|
|
65
|
+
stack.extend((child, depth + 1) for child in item.values())
|
|
66
|
+
else:
|
|
67
|
+
raise OwnerWireError
|
|
68
|
+
try:
|
|
69
|
+
if len(canonical_json(value).encode('utf-8')) > _MAX_CONFIG:
|
|
70
|
+
raise OwnerWireError('owner-authority-config-invalid')
|
|
71
|
+
except OwnerWireError:
|
|
72
|
+
raise
|
|
73
|
+
except (TypeError, ValueError, UnicodeError, RecursionError):
|
|
74
|
+
raise OwnerWireError from None
|
|
75
|
+
return value
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _closed(value: object, keys: set[str]) -> dict[str, Any]:
|
|
79
|
+
if type(value) is not dict or set(value) != keys:
|
|
80
|
+
raise OwnerWireError('owner-authority-config-invalid')
|
|
81
|
+
return value
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _text(value: object, maximum: int = 128) -> str:
|
|
85
|
+
if type(value) is not str or not value or '\x00' in value:
|
|
86
|
+
raise OwnerWireError
|
|
87
|
+
try:
|
|
88
|
+
if len(value.encode('utf-8')) > maximum:
|
|
89
|
+
raise OwnerWireError
|
|
90
|
+
except UnicodeEncodeError:
|
|
91
|
+
raise OwnerWireError from None
|
|
92
|
+
return value
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _uuid(value: object) -> str:
|
|
96
|
+
if type(value) is not str or not _UUID.fullmatch(value):
|
|
97
|
+
raise OwnerWireError
|
|
98
|
+
try:
|
|
99
|
+
if str(uuid.UUID(value)) != value:
|
|
100
|
+
raise OwnerWireError
|
|
101
|
+
except ValueError:
|
|
102
|
+
raise OwnerWireError from None
|
|
103
|
+
return value
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _base64url(value: object, size: int) -> bytes:
|
|
107
|
+
if type(value) is not str or not _B64URL.fullmatch(value):
|
|
108
|
+
raise OwnerWireError
|
|
109
|
+
try:
|
|
110
|
+
decoded = base64.urlsafe_b64decode(value + '=' * ((4 - len(value) % 4) % 4))
|
|
111
|
+
except (ValueError, TypeError):
|
|
112
|
+
raise OwnerWireError from None
|
|
113
|
+
if (len(decoded) != size
|
|
114
|
+
or base64.urlsafe_b64encode(decoded).decode('ascii').rstrip('=') != value):
|
|
115
|
+
raise OwnerWireError
|
|
116
|
+
return decoded
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def validate_owner_configuration(value: object) -> tuple[dict[str, Any], tuple[dict[str, Any], ...]]:
|
|
120
|
+
"""Validate the closed owner configuration used by both bootstrap and approval core."""
|
|
121
|
+
config = _plain_json(value)
|
|
122
|
+
_closed(config, {'profile', 'authorityId', 'policyRevision', 'purpose', 'keys'})
|
|
123
|
+
if config['profile'] != OWNER_AUTHORITY_PROFILE:
|
|
124
|
+
raise OwnerWireError('owner-authority-config-invalid')
|
|
125
|
+
_uuid(config['authorityId'])
|
|
126
|
+
_text(config['policyRevision'])
|
|
127
|
+
if config['purpose'] not in OWNER_PURPOSES:
|
|
128
|
+
raise OwnerWireError('owner-authority-config-invalid')
|
|
129
|
+
keys = config['keys']
|
|
130
|
+
if type(keys) is not list or not 1 <= len(keys) <= 32:
|
|
131
|
+
raise OwnerWireError('owner-authority-config-invalid')
|
|
132
|
+
seen: set[str] = set()
|
|
133
|
+
normalized: list[dict[str, Any]] = []
|
|
134
|
+
for item in keys:
|
|
135
|
+
key = _closed(item, {'keyId', 'publicKey', 'principalId', 'scopes',
|
|
136
|
+
'supervisorIds', 'providerIds', 'installationIds'})
|
|
137
|
+
key_id = _text(key['keyId'])
|
|
138
|
+
if key_id in seen:
|
|
139
|
+
raise OwnerWireError('owner-authority-config-invalid')
|
|
140
|
+
seen.add(key_id)
|
|
141
|
+
principal_id = _text(key['principalId'])
|
|
142
|
+
public_key = _base64url(key['publicKey'], 32)
|
|
143
|
+
scopes = key['scopes']
|
|
144
|
+
if (type(scopes) is not list or not scopes
|
|
145
|
+
or any(type(scope) is not str or scope not in OWNER_SCOPES for scope in scopes)
|
|
146
|
+
or len(scopes) != len(set(scopes))
|
|
147
|
+
or scopes != [scope for scope in OWNER_SCOPES if scope in scopes]):
|
|
148
|
+
raise OwnerWireError('owner-authority-config-invalid')
|
|
149
|
+
bounds: dict[str, tuple[str, ...]] = {}
|
|
150
|
+
for name in ('supervisorIds', 'providerIds', 'installationIds'):
|
|
151
|
+
entries = key[name]
|
|
152
|
+
if (type(entries) is not list or not 1 <= len(entries) <= 256
|
|
153
|
+
or any(type(entry) is not str for entry in entries)
|
|
154
|
+
or len(entries) != len(set(entries))):
|
|
155
|
+
raise OwnerWireError('owner-authority-config-invalid')
|
|
156
|
+
bounds[name] = tuple(_text(entry) if name == 'installationIds' else _uuid(entry)
|
|
157
|
+
for entry in entries)
|
|
158
|
+
normalized.append({'keyId': key_id, 'publicKey': public_key,
|
|
159
|
+
'principalId': principal_id, 'scopes': tuple(scopes),
|
|
160
|
+
**bounds})
|
|
161
|
+
return config, tuple(normalized)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Durable fail-closed fence for interrupted nontransactional migrations.
|
|
3
|
+
|
|
4
|
+
The fixed metadata head view is the ingress for every lifecycle data call.
|
|
5
|
+
Revoking its exact person/batch SELECT grants prevents using old references
|
|
6
|
+
between phases. The administrative source proof remains independent of clients.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from uuid import uuid4
|
|
12
|
+
|
|
13
|
+
from .catalog import CatalogError, _execute, _one, _q
|
|
14
|
+
from .head_view import HEAD, _create_head_view, _head_shape
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _head_grants(connection, source, enabled):
|
|
18
|
+
cfg=source['configuration']
|
|
19
|
+
relation=_q(cfg['schema'])+'.'+_q(HEAD)
|
|
20
|
+
roles=', '.join(_q(cfg[k]) for k in ('personRole','batchRole'))
|
|
21
|
+
_execute(connection,('GRANT SELECT ON TABLE '+relation+' TO ' if enabled else 'REVOKE SELECT ON TABLE '+relation+' FROM ')+roles)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _verify_phase_head(connection, source):
|
|
25
|
+
"""Accept only original fixed head shape, either live or exactly fenced."""
|
|
26
|
+
cfg=source['configuration'];schema=cfg['schema']
|
|
27
|
+
actual=_head_shape(connection,schema)
|
|
28
|
+
temporary='umf_verify_'+uuid4().hex
|
|
29
|
+
_create_head_view(connection,source,temporary)
|
|
30
|
+
expected=_head_shape(connection,schema,temporary)
|
|
31
|
+
if actual == expected:
|
|
32
|
+
_execute(connection,'DROP VIEW '+_q(schema)+'.'+_q(temporary))
|
|
33
|
+
return
|
|
34
|
+
ids={_one(connection,'SELECT oid FROM pg_catalog.pg_roles WHERE rolname=%s',(cfg[k],))[0] for k in ('personRole','batchRole')}
|
|
35
|
+
expected['acl']=[entry for entry in expected['acl'] if entry[1] not in ids]
|
|
36
|
+
if actual != expected:
|
|
37
|
+
raise CatalogError('head-view-catalog-mismatch')
|
|
38
|
+
_execute(connection,'DROP VIEW '+_q(schema)+'.'+_q(temporary))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@contextmanager
|
|
42
|
+
def _unfenced_verification(connection, source):
|
|
43
|
+
"""Grant only inside an always-rolled-back savepoint; other sessions stay fenced."""
|
|
44
|
+
class _RollbackVerification(Exception):
|
|
45
|
+
pass
|
|
46
|
+
try:
|
|
47
|
+
with connection.transaction():
|
|
48
|
+
_head_grants(connection,source,True)
|
|
49
|
+
yield
|
|
50
|
+
raise _RollbackVerification
|
|
51
|
+
except _RollbackVerification:
|
|
52
|
+
pass
|
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Trusted, source-independent G11 phase policy and accounting primitives.
|
|
3
|
+
|
|
4
|
+
These are host-side building blocks only. They do not install PostgreSQL
|
|
5
|
+
timeouts, authorize a provider, mint ingress capabilities, or qualify native
|
|
6
|
+
enforcement. The concrete adapter must install and verify transaction_timeout
|
|
7
|
+
before BEGIN, use :class:`PhaseDeadline` before every dispatch and COMMIT, and
|
|
8
|
+
record the returned budget receipt in the effect transaction.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from .catalog import CatalogError
|
|
20
|
+
|
|
21
|
+
DERIVED_ADMIN_MODULE_PROFILE = 'weft.table-operation-module/0.2'
|
|
22
|
+
EXECUTION_POLICY_PROFILE = 'umf.g11.execution-policy/0.1'
|
|
23
|
+
PHASE_BUDGET_PROFILE = 'umf.g11.phase-budget-receipt/0.1'
|
|
24
|
+
MAX_PHASE_FILL_EFFECTS = 256
|
|
25
|
+
MAX_PHASE_OPERATION_ID_UTF8 = 256
|
|
26
|
+
_POLICY_FIELDS = {
|
|
27
|
+
'phase_timeout_ms', 'aggregate_affected_rows',
|
|
28
|
+
'statement_timeout_ms', 'lock_timeout_ms',
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _canonical_bytes(value: Any) -> bytes:
|
|
33
|
+
"""RFC 8785 bytes for this closed integer/string/object subset."""
|
|
34
|
+
# JCS's UTF-8, lexically sorted object keys and compact separators match
|
|
35
|
+
# this subset; non-finite and non-JSON values are rejected.
|
|
36
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
37
|
+
separators=(',', ':'), allow_nan=False).encode('utf-8')
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _valid_operation_id(value: object) -> bool:
|
|
41
|
+
if type(value) is not str or not value or '\x00' in value:
|
|
42
|
+
return False
|
|
43
|
+
try:
|
|
44
|
+
return len(value.encode('utf-8')) <= MAX_PHASE_OPERATION_ID_UTF8
|
|
45
|
+
except UnicodeEncodeError:
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, slots=True)
|
|
50
|
+
class FieldReplacementExecutionPolicy:
|
|
51
|
+
"""Immutable trusted host settings; never sourced from plan/options JSON."""
|
|
52
|
+
|
|
53
|
+
phase_timeout_ms: int = 30_000
|
|
54
|
+
aggregate_affected_rows: int = 100_000
|
|
55
|
+
statement_timeout_ms: int = 30_000
|
|
56
|
+
lock_timeout_ms: int = 5_000
|
|
57
|
+
|
|
58
|
+
def __post_init__(self) -> None:
|
|
59
|
+
values = (self.phase_timeout_ms, self.aggregate_affected_rows,
|
|
60
|
+
self.statement_timeout_ms, self.lock_timeout_ms)
|
|
61
|
+
if any(type(value) is not int for value in values):
|
|
62
|
+
raise CatalogError('phase-policy-invalid')
|
|
63
|
+
if (not 1 <= self.phase_timeout_ms <= 300_000
|
|
64
|
+
or not 0 <= self.aggregate_affected_rows <= 1_000_000
|
|
65
|
+
or not 1 <= self.statement_timeout_ms <= self.phase_timeout_ms
|
|
66
|
+
or not 1 <= self.lock_timeout_ms <= self.statement_timeout_ms):
|
|
67
|
+
raise CatalogError('phase-policy-invalid')
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def from_trusted_mapping(cls, value: dict[str, Any]) -> FieldReplacementExecutionPolicy:
|
|
71
|
+
"""Build from a trusted host config, with closed keys and exact ints."""
|
|
72
|
+
if type(value) is not dict or set(value) - _POLICY_FIELDS:
|
|
73
|
+
raise CatalogError('phase-policy-invalid')
|
|
74
|
+
try:
|
|
75
|
+
return cls(**value)
|
|
76
|
+
except TypeError:
|
|
77
|
+
raise CatalogError('phase-policy-invalid') from None
|
|
78
|
+
|
|
79
|
+
def normal_form(self) -> dict[str, Any]:
|
|
80
|
+
return {
|
|
81
|
+
'version': EXECUTION_POLICY_PROFILE,
|
|
82
|
+
'phaseTimeoutMs': self.phase_timeout_ms,
|
|
83
|
+
'aggregateAffectedRows': self.aggregate_affected_rows,
|
|
84
|
+
'statementTimeoutMs': self.statement_timeout_ms,
|
|
85
|
+
'lockTimeoutMs': self.lock_timeout_ms,
|
|
86
|
+
'derivedModuleProfile': DERIVED_ADMIN_MODULE_PROFILE,
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
def canonical_bytes(self) -> bytes:
|
|
90
|
+
return _canonical_bytes(self.normal_form())
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def digest(self) -> str:
|
|
94
|
+
return hashlib.sha256(self.canonical_bytes()).hexdigest()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def require_original_policy(policy: FieldReplacementExecutionPolicy,
|
|
98
|
+
original_digest: str) -> None:
|
|
99
|
+
"""Refuse a resume whose trusted execution policy differs from approval."""
|
|
100
|
+
if (type(policy) is not FieldReplacementExecutionPolicy
|
|
101
|
+
or type(original_digest) is not str
|
|
102
|
+
or len(original_digest) != 64
|
|
103
|
+
or any(ch not in '0123456789abcdef' for ch in original_digest)
|
|
104
|
+
or policy.digest != original_digest):
|
|
105
|
+
raise CatalogError('phase-policy-mismatch')
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True, slots=True)
|
|
109
|
+
class DispatchTimeouts:
|
|
110
|
+
statement_timeout_ms: int
|
|
111
|
+
lock_timeout_ms: int
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class PhaseDeadline:
|
|
115
|
+
"""Monotonic absolute phase deadline and per-dispatch timeout clamp.
|
|
116
|
+
|
|
117
|
+
Injected clocks support deterministic source controls only. Native timeout
|
|
118
|
+
behavior must be proven by the PostgreSQL adapter integration tests.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
__slots__ = ('_clock_ns', '_deadline_ns', '_policy', '_started_ns')
|
|
122
|
+
|
|
123
|
+
def __init__(self, policy: FieldReplacementExecutionPolicy, *,
|
|
124
|
+
clock_ns: Callable[[], int] = time.monotonic_ns):
|
|
125
|
+
if type(policy) is not FieldReplacementExecutionPolicy:
|
|
126
|
+
raise CatalogError('phase-policy-invalid')
|
|
127
|
+
now = clock_ns()
|
|
128
|
+
if type(now) is not int or now < 0:
|
|
129
|
+
raise CatalogError('phase-clock-invalid')
|
|
130
|
+
self._policy = policy
|
|
131
|
+
self._started_ns = now
|
|
132
|
+
self._deadline_ns = now + policy.phase_timeout_ms * 1_000_000
|
|
133
|
+
self._clock_ns = clock_ns
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def started_ns(self) -> int:
|
|
137
|
+
return self._started_ns
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def deadline_ns(self) -> int:
|
|
141
|
+
return self._deadline_ns
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def native_transaction_timeout_ms(self) -> int:
|
|
145
|
+
"""Value the adapter must set and verify before BEGIN."""
|
|
146
|
+
return self._policy.phase_timeout_ms
|
|
147
|
+
|
|
148
|
+
def remaining_ms(self) -> int:
|
|
149
|
+
now = self._clock_ns()
|
|
150
|
+
if type(now) is not int or now < 0:
|
|
151
|
+
raise CatalogError('phase-clock-invalid')
|
|
152
|
+
remaining_ns = self._deadline_ns - now
|
|
153
|
+
remaining_ms = remaining_ns // 1_000_000
|
|
154
|
+
if remaining_ms <= 0:
|
|
155
|
+
raise CatalogError('phase-deadline-exceeded')
|
|
156
|
+
return remaining_ms
|
|
157
|
+
|
|
158
|
+
def before_dispatch(self) -> DispatchTimeouts:
|
|
159
|
+
remaining = self.remaining_ms()
|
|
160
|
+
statement = min(self._policy.statement_timeout_ms, remaining)
|
|
161
|
+
lock = min(self._policy.lock_timeout_ms, statement, remaining)
|
|
162
|
+
if statement <= 0 or lock <= 0:
|
|
163
|
+
raise CatalogError('phase-deadline-exceeded')
|
|
164
|
+
return DispatchTimeouts(statement, lock)
|
|
165
|
+
|
|
166
|
+
def before_commit(self) -> DispatchTimeouts:
|
|
167
|
+
return self.before_dispatch()
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@dataclass(frozen=True, slots=True)
|
|
171
|
+
class _ValidatedMarkerRows:
|
|
172
|
+
"""Private count created only after validating Weft's result marker rows."""
|
|
173
|
+
|
|
174
|
+
count: int
|
|
175
|
+
_seal: object
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
_MARKER_ROWS_SEAL = object()
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _validated_marker_rows(column_names: list[str], expected_marker: str,
|
|
182
|
+
rows: list[tuple[Any, ...]], max_rows: int) -> _ValidatedMarkerRows:
|
|
183
|
+
"""Validate the private affected marker shape and its per-fill bound."""
|
|
184
|
+
if (type(expected_marker) is not str or not expected_marker
|
|
185
|
+
or type(column_names) is not list or column_names != [expected_marker]
|
|
186
|
+
or type(rows) is not list or type(max_rows) is not int
|
|
187
|
+
or not 1 <= max_rows <= 10_000 or len(rows) > max_rows
|
|
188
|
+
or any(type(row) is not tuple or len(row) != 1
|
|
189
|
+
or type(row[0]) is not int or row[0] != 1 for row in rows)):
|
|
190
|
+
raise CatalogError('phase-budget-marker-invalid')
|
|
191
|
+
return _ValidatedMarkerRows(len(rows), _MARKER_ROWS_SEAL)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class PhaseBudgetCounter:
|
|
195
|
+
"""Whole-phase actual marker-row accounting, in dispatch order.
|
|
196
|
+
|
|
197
|
+
Charge only a validated private marker result after its own maxRows check.
|
|
198
|
+
Counts are per fill, so a business row affected by two fills is charged
|
|
199
|
+
twice. A rejected marker, identity, effect-count or aggregate check poisons
|
|
200
|
+
the phase, so no receipt/dispatch/commit is available afterward. This
|
|
201
|
+
bounded receipt is not authority for a selected plan: a concrete adapter
|
|
202
|
+
must bind each entry to the exact reviewed step order before recording it.
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
__slots__ = (
|
|
206
|
+
'_affected_rows',
|
|
207
|
+
'_deadline',
|
|
208
|
+
'_effect_step_ids',
|
|
209
|
+
'_effects',
|
|
210
|
+
'_poisoned',
|
|
211
|
+
'_policy',
|
|
212
|
+
'_policy_digest',
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
def __init__(self, policy: FieldReplacementExecutionPolicy, *,
|
|
216
|
+
clock_ns: Callable[[], int] = time.monotonic_ns):
|
|
217
|
+
if type(policy) is not FieldReplacementExecutionPolicy:
|
|
218
|
+
raise CatalogError('phase-policy-invalid')
|
|
219
|
+
self._policy = policy
|
|
220
|
+
self._policy_digest = policy.digest
|
|
221
|
+
self._affected_rows = 0
|
|
222
|
+
self._effects: list[dict[str, Any]] = []
|
|
223
|
+
self._effect_step_ids: set[str] = set()
|
|
224
|
+
self._deadline = PhaseDeadline(policy, clock_ns=clock_ns)
|
|
225
|
+
self._poisoned = False
|
|
226
|
+
|
|
227
|
+
def _require_usable(self) -> None:
|
|
228
|
+
if self._poisoned:
|
|
229
|
+
raise CatalogError('phase-budget-poisoned')
|
|
230
|
+
|
|
231
|
+
def _poison(self) -> None:
|
|
232
|
+
# Keep any already-observed effects in memory for diagnostics, but never
|
|
233
|
+
# let a failed phase produce a receipt or continue dispatch/commit.
|
|
234
|
+
self._poisoned = True
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def affected_rows(self) -> int:
|
|
238
|
+
return self._affected_rows
|
|
239
|
+
|
|
240
|
+
@property
|
|
241
|
+
def policy_digest(self) -> str:
|
|
242
|
+
return self._policy_digest
|
|
243
|
+
|
|
244
|
+
@property
|
|
245
|
+
def native_transaction_timeout_ms(self) -> int:
|
|
246
|
+
return self._deadline.native_transaction_timeout_ms
|
|
247
|
+
|
|
248
|
+
def before_dispatch(self) -> DispatchTimeouts:
|
|
249
|
+
self._require_usable()
|
|
250
|
+
try:
|
|
251
|
+
return self._deadline.before_dispatch()
|
|
252
|
+
except CatalogError:
|
|
253
|
+
self._poison()
|
|
254
|
+
raise
|
|
255
|
+
|
|
256
|
+
def before_commit(self) -> DispatchTimeouts:
|
|
257
|
+
self._require_usable()
|
|
258
|
+
try:
|
|
259
|
+
return self._deadline.before_commit()
|
|
260
|
+
except CatalogError:
|
|
261
|
+
self._poison()
|
|
262
|
+
raise
|
|
263
|
+
|
|
264
|
+
def charge_marker(self, *, step_id: str, operation: str,
|
|
265
|
+
column_names: list[str], expected_marker: str,
|
|
266
|
+
rows: list[tuple[Any, ...]], max_rows: int) -> None:
|
|
267
|
+
"""Validate and charge one actual marker result as one indivisible step."""
|
|
268
|
+
self._require_usable()
|
|
269
|
+
try:
|
|
270
|
+
validated = _validated_marker_rows(
|
|
271
|
+
column_names, expected_marker, rows, max_rows)
|
|
272
|
+
self.charge(step_id=step_id, operation=operation,
|
|
273
|
+
validated_rows=validated)
|
|
274
|
+
except CatalogError:
|
|
275
|
+
self._poison()
|
|
276
|
+
raise
|
|
277
|
+
|
|
278
|
+
def charge(self, *, step_id: str, operation: str,
|
|
279
|
+
validated_rows: _ValidatedMarkerRows) -> None:
|
|
280
|
+
self._require_usable()
|
|
281
|
+
try:
|
|
282
|
+
if (type(step_id) is not str
|
|
283
|
+
or len(step_id) != 10
|
|
284
|
+
or not step_id.startswith('step-')
|
|
285
|
+
or not step_id[5:].isascii()
|
|
286
|
+
or not step_id[5:].isdigit()
|
|
287
|
+
or not _valid_operation_id(operation)
|
|
288
|
+
or type(validated_rows) is not _ValidatedMarkerRows
|
|
289
|
+
or validated_rows._seal is not _MARKER_ROWS_SEAL
|
|
290
|
+
or type(validated_rows.count) is not int
|
|
291
|
+
or validated_rows.count < 0):
|
|
292
|
+
raise CatalogError('phase-budget-marker-invalid')
|
|
293
|
+
if step_id in self._effect_step_ids:
|
|
294
|
+
raise CatalogError('phase-budget-marker-invalid')
|
|
295
|
+
if len(self._effects) >= MAX_PHASE_FILL_EFFECTS:
|
|
296
|
+
raise CatalogError('phase-budget-marker-invalid')
|
|
297
|
+
total = self._affected_rows + validated_rows.count
|
|
298
|
+
if total > self._policy.aggregate_affected_rows:
|
|
299
|
+
raise CatalogError('phase-budget-exceeded')
|
|
300
|
+
self._effects.append({'stepId': step_id, 'operation': operation,
|
|
301
|
+
'rows': validated_rows.count})
|
|
302
|
+
self._effect_step_ids.add(step_id)
|
|
303
|
+
self._affected_rows = total
|
|
304
|
+
except CatalogError:
|
|
305
|
+
self._poison()
|
|
306
|
+
raise
|
|
307
|
+
|
|
308
|
+
def receipt(self) -> dict[str, Any]:
|
|
309
|
+
"""Return the exact closed receipt; persist only in the effect transaction."""
|
|
310
|
+
self._require_usable()
|
|
311
|
+
receipt = {
|
|
312
|
+
'profile': PHASE_BUDGET_PROFILE,
|
|
313
|
+
'policyDigest': self._policy_digest,
|
|
314
|
+
'affectedRows': self._affected_rows,
|
|
315
|
+
'fillEffects': [dict(effect) for effect in self._effects],
|
|
316
|
+
'nativeTransactionTimeoutMs': self._policy.phase_timeout_ms,
|
|
317
|
+
}
|
|
318
|
+
validate_phase_budget_receipt(receipt, self._policy)
|
|
319
|
+
return receipt
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def validate_phase_budget_receipt(receipt: dict[str, Any],
|
|
323
|
+
policy: FieldReplacementExecutionPolicy) -> None:
|
|
324
|
+
"""Verify the exact durable phase receipt shape and actual-count sum."""
|
|
325
|
+
if (type(policy) is not FieldReplacementExecutionPolicy
|
|
326
|
+
or type(receipt) is not dict
|
|
327
|
+
or set(receipt) != {'profile', 'policyDigest', 'affectedRows',
|
|
328
|
+
'fillEffects', 'nativeTransactionTimeoutMs'}
|
|
329
|
+
or receipt.get('profile') != PHASE_BUDGET_PROFILE
|
|
330
|
+
or receipt.get('policyDigest') != policy.digest
|
|
331
|
+
or type(receipt.get('affectedRows')) is not int
|
|
332
|
+
or not 0 <= receipt['affectedRows'] <= policy.aggregate_affected_rows
|
|
333
|
+
or receipt.get('nativeTransactionTimeoutMs') != policy.phase_timeout_ms
|
|
334
|
+
or type(receipt.get('nativeTransactionTimeoutMs')) is not int
|
|
335
|
+
or type(receipt.get('fillEffects')) is not list
|
|
336
|
+
or len(receipt['fillEffects']) > MAX_PHASE_FILL_EFFECTS):
|
|
337
|
+
raise CatalogError('phase-budget-receipt-invalid')
|
|
338
|
+
total = 0
|
|
339
|
+
step_ids: set[str] = set()
|
|
340
|
+
for item in receipt['fillEffects']:
|
|
341
|
+
if (type(item) is not dict or set(item) != {'stepId', 'operation', 'rows'}
|
|
342
|
+
or type(item.get('stepId')) is not str
|
|
343
|
+
or len(item['stepId']) != 10
|
|
344
|
+
or not item['stepId'].startswith('step-')
|
|
345
|
+
or not item['stepId'][5:].isascii()
|
|
346
|
+
or not item['stepId'][5:].isdigit()
|
|
347
|
+
or item['stepId'] in step_ids
|
|
348
|
+
or not _valid_operation_id(item.get('operation'))
|
|
349
|
+
or type(item.get('rows')) is not int or item['rows'] < 0):
|
|
350
|
+
raise CatalogError('phase-budget-receipt-invalid')
|
|
351
|
+
step_ids.add(item['stepId'])
|
|
352
|
+
total += item['rows']
|
|
353
|
+
if total != receipt['affectedRows']:
|
|
354
|
+
raise CatalogError('phase-budget-receipt-invalid')
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def require_retry_after_confirmed_abort(policy: FieldReplacementExecutionPolicy,
|
|
358
|
+
original_policy_digest: str,
|
|
359
|
+
native_abort_proof: object, *,
|
|
360
|
+
phase_binding_digest: str | None = None,
|
|
361
|
+
target_identity_digest: str | None = None,
|
|
362
|
+
attempt_id: str | None = None) -> None:
|
|
363
|
+
"""Require a private native proof before a caller creates a fresh retry budget.
|
|
364
|
+
|
|
365
|
+
The proof issuer is intentionally not defined in this source slice. A real
|
|
366
|
+
provider must mint it only after positively observing rollback and absence
|
|
367
|
+
of the committed phase-completion record for the same original phase/target.
|
|
368
|
+
READY progress may remain after a known abort and must not be deleted or
|
|
369
|
+
treated as evidence of a completed phase. Dictionaries, booleans and
|
|
370
|
+
process-local errors are never proofs.
|
|
371
|
+
"""
|
|
372
|
+
require_original_policy(policy, original_policy_digest)
|
|
373
|
+
if type(native_abort_proof) is not _ConfirmedAbortProof:
|
|
374
|
+
raise CatalogError('phase-retry-native-proof-required')
|
|
375
|
+
if (native_abort_proof._seal is not _ABORT_PROOF_SEAL
|
|
376
|
+
or native_abort_proof.phase_binding_digest != phase_binding_digest
|
|
377
|
+
or native_abort_proof.target_identity_digest != target_identity_digest
|
|
378
|
+
or native_abort_proof.attempt_id != attempt_id
|
|
379
|
+
or native_abort_proof.policy_digest != policy.digest
|
|
380
|
+
or native_abort_proof.rollback_confirmed is not True
|
|
381
|
+
or native_abort_proof.phase_completion_absent is not True):
|
|
382
|
+
raise CatalogError('phase-retry-native-proof-required')
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
class _ConfirmedAbortProof:
|
|
386
|
+
__slots__ = (
|
|
387
|
+
'_seal',
|
|
388
|
+
'attempt_id',
|
|
389
|
+
'phase_binding_digest',
|
|
390
|
+
'phase_completion_absent',
|
|
391
|
+
'policy_digest',
|
|
392
|
+
'rollback_confirmed',
|
|
393
|
+
'target_identity_digest',
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
def __init__(self, seal: object, *, phase_binding_digest: str,
|
|
397
|
+
target_identity_digest: str, attempt_id: str,
|
|
398
|
+
policy_digest: str, rollback_confirmed: bool,
|
|
399
|
+
phase_completion_absent: bool):
|
|
400
|
+
if seal is not _ABORT_PROOF_SEAL:
|
|
401
|
+
raise TypeError('native abort proof is provider-issued')
|
|
402
|
+
digests = (phase_binding_digest, target_identity_digest, policy_digest)
|
|
403
|
+
if (any(type(value) is not str or len(value) != 64
|
|
404
|
+
or any(ch not in '0123456789abcdef' for ch in value)
|
|
405
|
+
for value in digests)
|
|
406
|
+
or type(attempt_id) is not str or not attempt_id
|
|
407
|
+
or type(rollback_confirmed) is not bool
|
|
408
|
+
or type(phase_completion_absent) is not bool):
|
|
409
|
+
raise TypeError('invalid provider abort observation')
|
|
410
|
+
for name, value in (
|
|
411
|
+
('_seal', seal), ('phase_binding_digest', phase_binding_digest),
|
|
412
|
+
('target_identity_digest', target_identity_digest),
|
|
413
|
+
('attempt_id', attempt_id), ('policy_digest', policy_digest),
|
|
414
|
+
('rollback_confirmed', rollback_confirmed),
|
|
415
|
+
('phase_completion_absent', phase_completion_absent)):
|
|
416
|
+
object.__setattr__(self, name, value)
|
|
417
|
+
|
|
418
|
+
def __setattr__(self, name: str, value: object) -> None:
|
|
419
|
+
raise AttributeError('native abort proof is immutable')
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
_ABORT_PROOF_SEAL = object()
|