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,196 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Recoverable index-only phases on an explicitly supplied administrative session.
|
|
3
|
+
|
|
4
|
+
Native index shape is the progress witness. The same session-level lifecycle
|
|
5
|
+
lock spans autocommit builds and final transactional history publication.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
from uuid import uuid4
|
|
12
|
+
|
|
13
|
+
from .catalog import (
|
|
14
|
+
CatalogError,
|
|
15
|
+
_execute,
|
|
16
|
+
_index_shapes,
|
|
17
|
+
_installation,
|
|
18
|
+
_one,
|
|
19
|
+
_q,
|
|
20
|
+
verify_native_catalog,
|
|
21
|
+
)
|
|
22
|
+
from .ledger import (
|
|
23
|
+
_apply_table_migration,
|
|
24
|
+
_authorize_new_effects,
|
|
25
|
+
_history_rows,
|
|
26
|
+
_verified_plan,
|
|
27
|
+
)
|
|
28
|
+
from .ledger_schema import _verify_history_schema
|
|
29
|
+
from .phase_fence import _head_grants, _unfenced_verification, _verify_phase_head
|
|
30
|
+
from .privileges import verify_native_privileges
|
|
31
|
+
from .witness import _capture_witness
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _prefix_bundle(plan, completed):
|
|
35
|
+
from umf_codegen import compile_table_deployment
|
|
36
|
+
|
|
37
|
+
if plan['previous']['source']['format'] != 'json' or plan['next']['source']['format'] != 'json':
|
|
38
|
+
raise CatalogError('index-phase-json-source-required')
|
|
39
|
+
before = json.loads(plan['previous']['source']['utf8'])
|
|
40
|
+
after = json.loads(plan['next']['source']['utf8'])
|
|
41
|
+
old = next(m for m in before['modules'] if m['id'] == plan['next']['module'])['extensions']['umf.tables']
|
|
42
|
+
new = next(m for m in after['modules'] if m['id'] == plan['next']['module'])['extensions']['umf.tables']
|
|
43
|
+
selected = {(item['table'], item['index']) for item in completed}
|
|
44
|
+
for table, previous in zip(new['tables'], old['tables'], strict=True):
|
|
45
|
+
table['indexes'] = [index for index in table['indexes']
|
|
46
|
+
if any(i['id'] == index['id'] for i in previous['indexes'])
|
|
47
|
+
or (table['id'], index['id']) in selected]
|
|
48
|
+
result = compile_table_deployment(json.dumps(after,separators=(',', ':')),configuration=plan['next']['configuration'])
|
|
49
|
+
if result['status'] != 'compiled':
|
|
50
|
+
raise CatalogError('index-prefix-source-mismatch')
|
|
51
|
+
return result['bundle']
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _index_state(connection, schema, table, name):
|
|
55
|
+
shapes = _index_shapes(connection,schema,table,{})
|
|
56
|
+
return shapes.get(name)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _check_invalid_shape(connection, bundle, table, index, actual):
|
|
60
|
+
"""Reparse original column/index SQL; only validity/readiness may differ."""
|
|
61
|
+
schema = bundle['configuration']['schema']
|
|
62
|
+
temporary = 'umf_verify_' + uuid4().hex
|
|
63
|
+
relation = _q(schema)+'.'+_q(temporary)
|
|
64
|
+
columns = [c['definitionSql'] for c in bundle['expectedCatalog']['columns'] if c['table'] == table['id']]
|
|
65
|
+
_execute(connection,'CREATE TABLE '+relation+' ('+', '.join(columns)+')')
|
|
66
|
+
name = 'umf_verify_' + uuid4().hex
|
|
67
|
+
expected = next(i for i in bundle['expectedCatalog']['indexes'] if i['table'] == table['id'] and i['id'] == index['id'])
|
|
68
|
+
_execute(connection,'CREATE '+('UNIQUE ' if index['unique'] else '')+'INDEX '+_q(name)+' ON '+relation+' '+expected['definitionSql'])
|
|
69
|
+
reference = _index_shapes(connection,schema,temporary,{})[name]
|
|
70
|
+
if actual is None or actual[6] is not False or any(a != b for i,(a,b) in enumerate(zip(actual,reference,strict=True)) if i not in (6,7,8)):
|
|
71
|
+
raise CatalogError('invalid-index-shape-mismatch')
|
|
72
|
+
_execute(connection,'DROP TABLE '+relation)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def apply_concurrent_indexes(connection, plan, *, approved_digest, expected_head,
|
|
76
|
+
person_roles, repair_invalid=False, stop_after=None,
|
|
77
|
+
statement_timeout_ms=30_000, lock_timeout_ms=5_000, file_digest=None):
|
|
78
|
+
"""Build/resume source-selected indexes; commit final ledger on this session.
|
|
79
|
+
|
|
80
|
+
Requires autocommit, explicit NOLOGIN install owner via trusted SET ROLE,
|
|
81
|
+
pg_catalog search path and PostgreSQL18. No connection is opened or pooled.
|
|
82
|
+
repair_invalid approves dropping only a shape-verified failed selected index.
|
|
83
|
+
A failure never advances history; completed native indexes remain for resume.
|
|
84
|
+
"""
|
|
85
|
+
from psycopg import Error as NativeError
|
|
86
|
+
|
|
87
|
+
source_plan = _verified_plan(plan)
|
|
88
|
+
if approved_digest != source_plan['digest']:
|
|
89
|
+
raise CatalogError('approval-required')
|
|
90
|
+
selections = source_plan.get('options',{}).get('concurrentIndexes',[])
|
|
91
|
+
steps = source_plan['steps']
|
|
92
|
+
if (not selections or len(selections) != len(steps) or source_plan['previous'] is None
|
|
93
|
+
or source_plan['seedExecution'] != 'none'
|
|
94
|
+
or any(step['transaction'] != 'forbidden' or step['kind'] != 'index' for step in steps)):
|
|
95
|
+
raise CatalogError('index-phase-profile')
|
|
96
|
+
if type(repair_invalid) is not bool or stop_after is not None and (type(stop_after) is not int or stop_after < 1):
|
|
97
|
+
raise ValueError('invalid recovery options')
|
|
98
|
+
if not connection.autocommit or int(connection.info.transaction_status) != 0:
|
|
99
|
+
raise CatalogError('idle-autocommit-required')
|
|
100
|
+
bundle = source_plan['next']
|
|
101
|
+
schema = bundle['configuration']['schema']
|
|
102
|
+
# Check authority before acquiring a session lock or changing session settings.
|
|
103
|
+
with connection.transaction(), _installation(connection,bundle,statement_timeout_ms=statement_timeout_ms,lock_timeout_ms=lock_timeout_ms):
|
|
104
|
+
pass
|
|
105
|
+
lock = int.from_bytes(hashlib.sha256(('umf.table-lifecycle/0.1\0'+schema).encode()).digest()[:8],'big',signed=True)
|
|
106
|
+
if _one(connection,'SELECT pg_catalog.pg_try_advisory_lock(%s)',(lock,)) != (True,):
|
|
107
|
+
raise CatalogError('migration-busy')
|
|
108
|
+
previous_settings = None
|
|
109
|
+
publication_started = False
|
|
110
|
+
try:
|
|
111
|
+
previous_settings = _one(connection,"SELECT current_setting('statement_timeout'),current_setting('lock_timeout')")
|
|
112
|
+
_one(connection,"SELECT set_config('statement_timeout',%s,false),set_config('lock_timeout',%s,false)",(str(statement_timeout_ms),str(lock_timeout_ms)))
|
|
113
|
+
with connection.transaction():
|
|
114
|
+
if not _verify_history_schema(connection,bundle):
|
|
115
|
+
raise CatalogError('ledger-history-missing')
|
|
116
|
+
history = _history_rows(connection,schema)
|
|
117
|
+
if not history:
|
|
118
|
+
raise CatalogError('ledger-history-missing')
|
|
119
|
+
matches = [e for e in history if e['plan']['id'] == source_plan['id']]
|
|
120
|
+
if matches:
|
|
121
|
+
if matches[0]['plan']['digest'] != source_plan['digest']:
|
|
122
|
+
raise CatalogError('ledger-digest-conflict')
|
|
123
|
+
if history[-1]['plan']['toBundleDigest'] != bundle['bundleDigest']:
|
|
124
|
+
raise CatalogError('installed-generation-mismatch')
|
|
125
|
+
verify_native_catalog(connection,bundle)
|
|
126
|
+
return _apply_table_migration(connection,source_plan,approved_digest=approved_digest,expected_head=expected_head,
|
|
127
|
+
person_roles=person_roles,prebuilt_indexes=True,file_digest=file_digest)
|
|
128
|
+
if (history[-1]['entryDigest'] != expected_head
|
|
129
|
+
or source_plan['predecessor'] != {'id':history[-1]['plan']['id'],'digest':history[-1]['plan']['digest']}
|
|
130
|
+
or history[-1]['plan']['toBundleDigest'] != source_plan['fromBundleDigest']):
|
|
131
|
+
raise CatalogError('ledger-head-mismatch')
|
|
132
|
+
_authorize_new_effects(source_plan)
|
|
133
|
+
with connection.transaction():
|
|
134
|
+
observed = _capture_witness(connection,source_plan['previous'])
|
|
135
|
+
selected_names = {t['id']:{i['name'] for i in t['indexes'] if any(s['table']==t['id'] and s['index']==i['id'] for s in selections)} for t in bundle['expectedCatalog']['tables']}
|
|
136
|
+
for table in observed['tables']:
|
|
137
|
+
table['indexes'] = [row for row in table['indexes'] if row[0] not in selected_names[table['id']]]
|
|
138
|
+
if observed != history[-1]['witness']:
|
|
139
|
+
raise CatalogError('installed-generation-mismatch')
|
|
140
|
+
with connection.transaction():
|
|
141
|
+
_verify_phase_head(connection,bundle)
|
|
142
|
+
_head_grants(connection,bundle,False)
|
|
143
|
+
completed = []
|
|
144
|
+
# Follow compiler step order, independently of caller selection order.
|
|
145
|
+
ordered = []
|
|
146
|
+
for step in steps:
|
|
147
|
+
parts = step['sourcePath'].split('/')
|
|
148
|
+
table = bundle['expectedCatalog']['tables'][int(parts[6])]
|
|
149
|
+
index = table['indexes'][int(parts[8])]
|
|
150
|
+
ordered.append((step,table,index,{'table':table['id'],'index':index['id']}))
|
|
151
|
+
# Discover only a contiguous valid prefix. Later/foreign objects cause
|
|
152
|
+
# full source correspondence to refuse rather than being adopted.
|
|
153
|
+
for _,table,index,selection in ordered:
|
|
154
|
+
actual = _index_state(connection,schema,table['name'],index['name'])
|
|
155
|
+
if actual is None or actual[6] is not True:
|
|
156
|
+
break
|
|
157
|
+
completed.append(selection)
|
|
158
|
+
prefix = _prefix_bundle(source_plan,completed)
|
|
159
|
+
for step,table,index,selection in ordered[len(completed):]:
|
|
160
|
+
actual = _index_state(connection,schema,table['name'],index['name'])
|
|
161
|
+
if actual is not None:
|
|
162
|
+
with connection.transaction():
|
|
163
|
+
_check_invalid_shape(connection,bundle,table,index,actual)
|
|
164
|
+
if not repair_invalid:
|
|
165
|
+
raise CatalogError('invalid-index-repair-required')
|
|
166
|
+
_execute(connection,'DROP INDEX CONCURRENTLY '+_q(schema)+'.'+_q(index['name']))
|
|
167
|
+
with connection.transaction(), _unfenced_verification(connection,bundle):
|
|
168
|
+
verify_native_catalog(connection,prefix,statement_timeout_ms=statement_timeout_ms,lock_timeout_ms=lock_timeout_ms)
|
|
169
|
+
verify_native_privileges(connection,prefix,person_roles=person_roles)
|
|
170
|
+
_execute(connection,step['sql'])
|
|
171
|
+
completed.append(selection)
|
|
172
|
+
prefix = _prefix_bundle(source_plan,completed)
|
|
173
|
+
with connection.transaction(), _unfenced_verification(connection,bundle):
|
|
174
|
+
verify_native_catalog(connection,prefix,statement_timeout_ms=statement_timeout_ms,lock_timeout_ms=lock_timeout_ms)
|
|
175
|
+
if stop_after is not None and len(completed) >= stop_after:
|
|
176
|
+
return {'status':'in-progress','planDigest':source_plan['digest'],'completedIndexes':completed,'ledgerAdvanced':False}
|
|
177
|
+
publication_started = True
|
|
178
|
+
with connection.transaction():
|
|
179
|
+
_head_grants(connection,bundle,True)
|
|
180
|
+
verify_native_catalog(connection,bundle,statement_timeout_ms=statement_timeout_ms,lock_timeout_ms=lock_timeout_ms)
|
|
181
|
+
verify_native_privileges(connection,bundle,person_roles=person_roles)
|
|
182
|
+
result = _apply_table_migration(connection,source_plan,approved_digest=approved_digest,expected_head=expected_head,
|
|
183
|
+
person_roles=person_roles,prebuilt_indexes=True,
|
|
184
|
+
statement_timeout_ms=statement_timeout_ms,lock_timeout_ms=lock_timeout_ms,file_digest=file_digest)
|
|
185
|
+
return {**result,'status':'committed','commitResponsibility':'runner'}
|
|
186
|
+
except NativeError:
|
|
187
|
+
raise CatalogError('migration-outcome-unknown-observe-history' if publication_started else 'index-build-failed-inspect-before-resume') from None
|
|
188
|
+
finally:
|
|
189
|
+
try:
|
|
190
|
+
try:
|
|
191
|
+
if previous_settings is not None:
|
|
192
|
+
_one(connection,"SELECT set_config('statement_timeout',%s,false),set_config('lock_timeout',%s,false)",tuple(previous_settings))
|
|
193
|
+
finally:
|
|
194
|
+
_one(connection,'SELECT pg_catalog.pg_advisory_unlock(%s)',(lock,))
|
|
195
|
+
except NativeError:
|
|
196
|
+
raise CatalogError('migration-session-cleanup-failed-observe-history') from None
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Closed trusted policy profiles for G04 checked field conversion.
|
|
3
|
+
|
|
4
|
+
The policy binds the complete G11 phase policy and conversion resource limits.
|
|
5
|
+
Only trusted unsigned constructors supply defaults. Signed normal forms are
|
|
6
|
+
parsed as complete closed records so a resume cannot invent or raise capacity.
|
|
7
|
+
This module does not execute conversions or authorize a native provider.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .catalog import CatalogError
|
|
17
|
+
from .phase_policy import (
|
|
18
|
+
DERIVED_ADMIN_MODULE_PROFILE,
|
|
19
|
+
FieldReplacementExecutionPolicy,
|
|
20
|
+
)
|
|
21
|
+
from .phase_policy import (
|
|
22
|
+
EXECUTION_POLICY_PROFILE as G11_EXECUTION_POLICY_PROFILE,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
G04_EXECUTION_POLICY_01 = 'umf.g04.execution-policy/0.1'
|
|
26
|
+
G04_EXECUTION_POLICY_02 = 'umf.g04.execution-policy/0.2'
|
|
27
|
+
DEFAULT_CONVERSION_ENTRY_LIMIT = 100_000
|
|
28
|
+
MAX_CONVERSION_ENTRY_LIMIT = 1_000_000
|
|
29
|
+
DEFAULT_RETAINED_LOGICAL_BYTES_LIMIT = 67_108_864
|
|
30
|
+
MAX_RETAINED_LOGICAL_BYTES_LIMIT = 1_073_741_824
|
|
31
|
+
DEFAULT_MAX_ISSUED_INSTANCES = 1_000_000
|
|
32
|
+
MAX_ISSUED_INSTANCES = 1_000_000
|
|
33
|
+
|
|
34
|
+
_POLICY_01_KEYS = frozenset({
|
|
35
|
+
'version', 'phasePolicy', 'conversionEntryLimit', 'retainedLogicalBytesLimit',
|
|
36
|
+
})
|
|
37
|
+
_POLICY_02_KEYS = _POLICY_01_KEYS | {'maxIssuedInstances'}
|
|
38
|
+
_PHASE_KEYS = frozenset({
|
|
39
|
+
'version', 'phaseTimeoutMs', 'aggregateAffectedRows', 'statementTimeoutMs',
|
|
40
|
+
'lockTimeoutMs', 'derivedModuleProfile',
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _canonical_bytes(value: Any) -> bytes:
|
|
45
|
+
"""Serialize the validated JSON-value subset in deterministic compact form."""
|
|
46
|
+
try:
|
|
47
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
48
|
+
separators=(',', ':'), allow_nan=False).encode('utf-8')
|
|
49
|
+
except (TypeError, ValueError, UnicodeEncodeError):
|
|
50
|
+
raise CatalogError('g04-execution-policy-invalid') from None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _exact_int(value: object, minimum: int, maximum: int) -> bool:
|
|
54
|
+
return type(value) is int and minimum <= value <= maximum
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _phase_policy_from_normal_form(value: object) -> FieldReplacementExecutionPolicy:
|
|
58
|
+
if type(value) is not dict or set(value) != _PHASE_KEYS:
|
|
59
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
60
|
+
if (value['version'] != G11_EXECUTION_POLICY_PROFILE
|
|
61
|
+
or value['derivedModuleProfile'] != DERIVED_ADMIN_MODULE_PROFILE):
|
|
62
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
63
|
+
# The G11 policy constructor enforces exact integer types (not bools),
|
|
64
|
+
# complete fixed ranges and its timeout ordering.
|
|
65
|
+
try:
|
|
66
|
+
return FieldReplacementExecutionPolicy(
|
|
67
|
+
phase_timeout_ms=value['phaseTimeoutMs'],
|
|
68
|
+
aggregate_affected_rows=value['aggregateAffectedRows'],
|
|
69
|
+
statement_timeout_ms=value['statementTimeoutMs'],
|
|
70
|
+
lock_timeout_ms=value['lockTimeoutMs'],
|
|
71
|
+
)
|
|
72
|
+
except (CatalogError, TypeError):
|
|
73
|
+
raise CatalogError('g04-execution-policy-invalid') from None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True, slots=True)
|
|
77
|
+
class G04ExecutionPolicy:
|
|
78
|
+
"""Validated immutable G04 policy; construction never supplies defaults."""
|
|
79
|
+
|
|
80
|
+
version: str
|
|
81
|
+
phase_policy: FieldReplacementExecutionPolicy
|
|
82
|
+
conversion_entry_limit: int
|
|
83
|
+
retained_logical_bytes_limit: int
|
|
84
|
+
max_issued_instances: int | None = None
|
|
85
|
+
|
|
86
|
+
def __post_init__(self) -> None:
|
|
87
|
+
if type(self.version) is not str or type(self.phase_policy) is not FieldReplacementExecutionPolicy:
|
|
88
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
89
|
+
if not _exact_int(self.conversion_entry_limit, 0, MAX_CONVERSION_ENTRY_LIMIT):
|
|
90
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
91
|
+
if not _exact_int(self.retained_logical_bytes_limit, 0,
|
|
92
|
+
MAX_RETAINED_LOGICAL_BYTES_LIMIT):
|
|
93
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
94
|
+
if self.version == G04_EXECUTION_POLICY_01:
|
|
95
|
+
if self.max_issued_instances is not None:
|
|
96
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
97
|
+
elif self.version == G04_EXECUTION_POLICY_02:
|
|
98
|
+
if not _exact_int(self.max_issued_instances, 1, MAX_ISSUED_INSTANCES):
|
|
99
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
100
|
+
else:
|
|
101
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def trusted_nonretained(
|
|
105
|
+
cls,
|
|
106
|
+
*,
|
|
107
|
+
phase_policy: FieldReplacementExecutionPolicy | None = None,
|
|
108
|
+
conversion_entry_limit: int = DEFAULT_CONVERSION_ENTRY_LIMIT,
|
|
109
|
+
retained_logical_bytes_limit: int = DEFAULT_RETAINED_LOGICAL_BYTES_LIMIT,
|
|
110
|
+
) -> G04ExecutionPolicy:
|
|
111
|
+
"""Construct the finite .1 profile from trusted host settings."""
|
|
112
|
+
if phase_policy is None:
|
|
113
|
+
phase_policy = FieldReplacementExecutionPolicy()
|
|
114
|
+
return cls(
|
|
115
|
+
G04_EXECUTION_POLICY_01, phase_policy, conversion_entry_limit,
|
|
116
|
+
retained_logical_bytes_limit,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
@classmethod
|
|
120
|
+
def trusted_retained(
|
|
121
|
+
cls,
|
|
122
|
+
*,
|
|
123
|
+
phase_policy: FieldReplacementExecutionPolicy | None = None,
|
|
124
|
+
conversion_entry_limit: int = DEFAULT_CONVERSION_ENTRY_LIMIT,
|
|
125
|
+
retained_logical_bytes_limit: int = DEFAULT_RETAINED_LOGICAL_BYTES_LIMIT,
|
|
126
|
+
max_issued_instances: int = DEFAULT_MAX_ISSUED_INSTANCES,
|
|
127
|
+
) -> G04ExecutionPolicy:
|
|
128
|
+
"""Construct retained mode .2; capacity defaulting is trusted-only."""
|
|
129
|
+
if phase_policy is None:
|
|
130
|
+
phase_policy = FieldReplacementExecutionPolicy()
|
|
131
|
+
return cls(
|
|
132
|
+
G04_EXECUTION_POLICY_02, phase_policy, conversion_entry_limit,
|
|
133
|
+
retained_logical_bytes_limit, max_issued_instances,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
@classmethod
|
|
137
|
+
def from_signed_normal_form(
|
|
138
|
+
cls, value: object, *, retained_originals: bool,
|
|
139
|
+
) -> G04ExecutionPolicy:
|
|
140
|
+
"""Validate a decoded signed policy without filling any missing member.
|
|
141
|
+
|
|
142
|
+
The caller verifies the enclosing owner signature and digest. This
|
|
143
|
+
method validates the exact closed policy shape and mode/profile match.
|
|
144
|
+
"""
|
|
145
|
+
if type(retained_originals) is not bool or type(value) is not dict:
|
|
146
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
147
|
+
version = value.get('version')
|
|
148
|
+
if retained_originals:
|
|
149
|
+
if version != G04_EXECUTION_POLICY_02 or set(value) != _POLICY_02_KEYS:
|
|
150
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
151
|
+
elif version != G04_EXECUTION_POLICY_01 or set(value) != _POLICY_01_KEYS:
|
|
152
|
+
raise CatalogError('g04-execution-policy-invalid')
|
|
153
|
+
phase_policy = _phase_policy_from_normal_form(value['phasePolicy'])
|
|
154
|
+
return cls(
|
|
155
|
+
version,
|
|
156
|
+
phase_policy,
|
|
157
|
+
value['conversionEntryLimit'],
|
|
158
|
+
value['retainedLogicalBytesLimit'],
|
|
159
|
+
value.get('maxIssuedInstances'),
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
def normal_form(self) -> dict[str, Any]:
|
|
163
|
+
value: dict[str, Any] = {
|
|
164
|
+
'version': self.version,
|
|
165
|
+
'phasePolicy': self.phase_policy.normal_form(),
|
|
166
|
+
'conversionEntryLimit': self.conversion_entry_limit,
|
|
167
|
+
'retainedLogicalBytesLimit': self.retained_logical_bytes_limit,
|
|
168
|
+
}
|
|
169
|
+
if self.version == G04_EXECUTION_POLICY_02:
|
|
170
|
+
value['maxIssuedInstances'] = self.max_issued_instances
|
|
171
|
+
return value
|
|
172
|
+
|
|
173
|
+
def canonical_bytes(self) -> bytes:
|
|
174
|
+
return _canonical_bytes(self.normal_form())
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def digest(self) -> str:
|
|
178
|
+
return hashlib.sha256(self.canonical_bytes()).hexdigest()
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def require_original_policy(policy: G04ExecutionPolicy, original_digest: str) -> None:
|
|
182
|
+
"""Require the exact originally approved policy, including retained cap."""
|
|
183
|
+
if (type(policy) is not G04ExecutionPolicy
|
|
184
|
+
or type(original_digest) is not str
|
|
185
|
+
or len(original_digest) != 64
|
|
186
|
+
or any(ch not in '0123456789abcdef' for ch in original_digest)
|
|
187
|
+
or policy.digest != original_digest):
|
|
188
|
+
raise CatalogError('g04-execution-policy-mismatch')
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Live ordinary-principal installation checks; not an operation permit.
|
|
3
|
+
|
|
4
|
+
Expected table meaning is issued only after original-source native proof.
|
|
5
|
+
Current catalog/ACL/role observations never bless a new observed shape.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
from typing import Any, Literal
|
|
12
|
+
|
|
13
|
+
from .catalog import CatalogError
|
|
14
|
+
from .head import _head_steps, _normalized, _operation_head_steps, prepare_table_head
|
|
15
|
+
from .head_view import HEAD
|
|
16
|
+
from .ledger_schema import HISTORY
|
|
17
|
+
from .outcome_schema import OUTCOMES, _outcome_steps
|
|
18
|
+
from .privileges import _EXTERNAL
|
|
19
|
+
from .probe import _Query
|
|
20
|
+
from .roles import _role_scope_steps
|
|
21
|
+
from .table_boundary import TABLE_BOUNDARY
|
|
22
|
+
from .witness import _json_bytes, _witness_steps
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _principal(principal_role: str, audience: str) -> None:
|
|
26
|
+
if (audience not in ('person','batch') or type(principal_role) is not str or not principal_role
|
|
27
|
+
or '\0' in principal_role or len(principal_role.encode('utf-8'))>63):
|
|
28
|
+
raise ValueError('an explicit native principal and person/batch audience are required')
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class TableCorrespondenceProbe:
|
|
32
|
+
"""Prepared checks over a trusted source/reference and selected principal."""
|
|
33
|
+
def __init__(self, head, principal_role: str, audience: str):
|
|
34
|
+
_principal(principal_role,audience)
|
|
35
|
+
self._head,self._principal,self._audience = head,principal_role,audience
|
|
36
|
+
|
|
37
|
+
def for_principal(self, *, principal_role: str, audience: Literal['person','batch']) -> TableCorrespondenceProbe:
|
|
38
|
+
"""Reuse owned source metadata; every steps() observes live authority."""
|
|
39
|
+
return TableCorrespondenceProbe(self._head,principal_role,audience)
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def schema(self) -> str:
|
|
43
|
+
return self._head.schema
|
|
44
|
+
|
|
45
|
+
def steps(self):
|
|
46
|
+
head = self._head
|
|
47
|
+
return _correspondence_steps(head._source,head._expected,self._principal,self._audience,
|
|
48
|
+
head._statement_timeout_ms,head._lock_timeout_ms)
|
|
49
|
+
|
|
50
|
+
def operation_steps(self):
|
|
51
|
+
"""Observe only the selected operation's live head and role scope.
|
|
52
|
+
|
|
53
|
+
The shared lifecycle lock remains held by the caller's transaction.
|
|
54
|
+
Native table privileges and RLS govern the business statement itself;
|
|
55
|
+
this short observation deliberately does not re-audit catalog shapes.
|
|
56
|
+
Out-of-band DDL, ACL, or role changes require operator quiescence.
|
|
57
|
+
"""
|
|
58
|
+
head = self._head
|
|
59
|
+
return _operation_steps(head._source,head._expected,self._principal,self._audience)
|
|
60
|
+
|
|
61
|
+
def outcome_steps(self, action, principal_oid, key_digest, row=None):
|
|
62
|
+
"""Fixed receipt IO; callers keep verified principal/admission in one lease."""
|
|
63
|
+
if 'outcomeShape' not in self._head._expected:
|
|
64
|
+
raise CatalogError('outcome-storage-not-installed')
|
|
65
|
+
return _outcome_steps(self.schema,principal_oid,key_digest,action,row)
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def binding_context(self) -> dict[str, Any]:
|
|
69
|
+
"""Copied source pins for an SDK-owned operation compiler invocation."""
|
|
70
|
+
source,expected=self._head._source,self._head._expected
|
|
71
|
+
return {'module':source['configuration']['module'],'schema':self.schema,
|
|
72
|
+
'sourceUtf8':source['source']['utf8'],'sourceDigest':source['sourceDigest'],
|
|
73
|
+
'configurationDigest':source['configurationDigest'],'bundleDigest':source['bundleDigest'],
|
|
74
|
+
'headDigest':expected['headDigest'],'referenceDigest':expected['referenceDigest']}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def prepare_table_correspondence(bundle: dict[str, object], reference: dict[str, object], *,
|
|
78
|
+
principal_role: str, audience: Literal['person','batch'],
|
|
79
|
+
statement_timeout_ms: int = 30_000, lock_timeout_ms: int = 5_000) -> TableCorrespondenceProbe:
|
|
80
|
+
_principal(principal_role,audience)
|
|
81
|
+
head = prepare_table_head(bundle,reference,statement_timeout_ms=statement_timeout_ms,lock_timeout_ms=lock_timeout_ms)
|
|
82
|
+
return TableCorrespondenceProbe(head,principal_role,audience)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _table_boundaries(source, expected):
|
|
86
|
+
schema = source['configuration']['schema']
|
|
87
|
+
tables = expected['nativeWitness']['tables']
|
|
88
|
+
relation_ids = [table['relation'][0] for table in tables]
|
|
89
|
+
owner_id = expected['nativeWitness']['schema'][1]
|
|
90
|
+
heap = (yield _Query('one',"SELECT oid FROM pg_catalog.pg_am WHERE amname='heap'"))[0]
|
|
91
|
+
for table in source['expectedCatalog']['tables']:
|
|
92
|
+
actual = yield _Query('one',TABLE_BOUNDARY,(relation_ids,relation_ids,schema,table['name']))
|
|
93
|
+
if actual != ('r','p',True,True,False,False,False,'d',owner_id,heap,False,8,False,False):
|
|
94
|
+
raise CatalogError('table-boundary-mismatch')
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _schema_privileges(source, expected, roles):
|
|
98
|
+
cfg = source['configuration'];schema = cfg['schema']
|
|
99
|
+
schema_id,owner_id = expected['nativeWitness']['schema']
|
|
100
|
+
actual = yield _Query('all',"""SELECT x.grantor,x.grantee,x.privilege_type,x.is_grantable
|
|
101
|
+
FROM pg_catalog.pg_namespace n,LATERAL pg_catalog.aclexplode(COALESCE(n.nspacl,pg_catalog.acldefault('n',n.nspowner))) x
|
|
102
|
+
WHERE n.oid=%s ORDER BY 1,2,3,4""",(schema_id,))
|
|
103
|
+
acl = yield _Query('all',"""SELECT grantor,grantee,privilege_type,is_grantable
|
|
104
|
+
FROM pg_catalog.aclexplode(pg_catalog.acldefault('n',%s::pg_catalog.oid))""",(owner_id,))
|
|
105
|
+
for role in (cfg['personRole'],cfg['batchRole']):
|
|
106
|
+
acl.append((owner_id,roles['identities'][role],'USAGE',False))
|
|
107
|
+
if actual != sorted(acl):
|
|
108
|
+
raise CatalogError('privilege-mismatch')
|
|
109
|
+
inventory = yield _Query('all',"""SELECT c.relname FROM pg_catalog.pg_class c
|
|
110
|
+
WHERE c.relnamespace=%s AND c.relkind NOT IN ('i','I') ORDER BY c.relname""",(schema_id,))
|
|
111
|
+
names = sorted([(t['name'],) for t in source['expectedCatalog']['tables']]+[(HEAD,),(HISTORY,)])
|
|
112
|
+
if 'outcomeShape' in expected:
|
|
113
|
+
names=sorted([*names,(OUTCOMES,)])
|
|
114
|
+
if expected.get('version') == 'umf.table-installation/0.3':
|
|
115
|
+
from .approval import APPROVAL_PROFILE, _approval_shape_steps
|
|
116
|
+
|
|
117
|
+
if (expected.get('approvalProfile') != APPROVAL_PROFILE
|
|
118
|
+
or expected.get('approvalPlanDigest') != expected.get('planDigest')
|
|
119
|
+
or _normalized((yield from _approval_shape_steps(schema))) != expected.get('approvalShape')):
|
|
120
|
+
raise CatalogError('approval-catalog-mismatch')
|
|
121
|
+
names=sorted([*names,(APPROVAL_PROFILE['relation'],)])
|
|
122
|
+
if inventory != names:
|
|
123
|
+
raise CatalogError('catalog-mismatch')
|
|
124
|
+
for role in (cfg['ownerRole'],cfg['personRole'],cfg['batchRole']):
|
|
125
|
+
oid = roles['identities'][role]
|
|
126
|
+
if (yield _Query('one',_EXTERNAL,(oid,schema,oid,schema,oid,oid,schema,oid,oid,oid,oid,oid))) != (False,):
|
|
127
|
+
raise CatalogError('external-authority-present')
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _correspondence_steps(source, expected, principal, audience, statement_timeout_ms, lock_timeout_ms):
|
|
131
|
+
observed = yield from _head_steps(source,expected,statement_timeout_ms,lock_timeout_ms)
|
|
132
|
+
if observed['observedPrincipal'] != principal:
|
|
133
|
+
raise CatalogError('principal-mismatch')
|
|
134
|
+
roles = yield from _role_scope_steps(source,(principal,) if audience=='person' else (),
|
|
135
|
+
(principal,) if audience=='batch' else ())
|
|
136
|
+
yield from _table_boundaries(source,expected)
|
|
137
|
+
if (yield from _witness_steps(source)) != expected['nativeWitness']:
|
|
138
|
+
raise CatalogError('installed-generation-mismatch')
|
|
139
|
+
yield from _schema_privileges(source,expected,roles)
|
|
140
|
+
# Metadata checks cannot demand SELECT on deliberately denied tables. The
|
|
141
|
+
# shared module lock excludes compliant migrations; native statements take
|
|
142
|
+
# their own selected-table locks. External privileged changes require the
|
|
143
|
+
# same operator quiescence as role/ACL changes, not an inferred global lock.
|
|
144
|
+
yield from _table_boundaries(source,expected)
|
|
145
|
+
if (yield from _witness_steps(source)) != expected['nativeWitness']:
|
|
146
|
+
raise CatalogError('installed-generation-mismatch')
|
|
147
|
+
observed.update({'principalOid':roles['identities'][principal],'audience':audience,
|
|
148
|
+
'roleScopeDigest':hashlib.sha256(_json_bytes(_normalized({'roles':roles['facts']}))).hexdigest(),
|
|
149
|
+
'nativeTableCorrespondenceVerified':True,'operationAdmission':False})
|
|
150
|
+
return observed
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _operation_steps(source, expected, principal, audience):
|
|
154
|
+
observed = yield from _operation_head_steps(source,expected,principal)
|
|
155
|
+
cfg = source['configuration']
|
|
156
|
+
owner, person, batch = (cfg[key] for key in ('ownerRole','personRole','batchRole'))
|
|
157
|
+
groups = sorted(cfg['groupRoles'].items())
|
|
158
|
+
configured = {owner,person,batch,*cfg['groupRoles'].values()}
|
|
159
|
+
if audience == 'person' and principal in configured:
|
|
160
|
+
raise CatalogError('person-identity-required')
|
|
161
|
+
if audience == 'batch' and principal in configured-{batch}:
|
|
162
|
+
raise CatalogError('batch-identity-required')
|
|
163
|
+
audience_role = person if audience == 'person' else batch
|
|
164
|
+
if groups:
|
|
165
|
+
group_values = 'VALUES ' + ','.join('(%s::pg_catalog.text,%s::pg_catalog.text)' for _ in groups)
|
|
166
|
+
else:
|
|
167
|
+
group_values = 'SELECT NULL::pg_catalog.text,NULL::pg_catalog.text WHERE FALSE'
|
|
168
|
+
group_params = tuple(value for pair in groups for value in pair)
|
|
169
|
+
row = yield _Query('one', """SELECT p.oid,a.oid,pg_catalog.pg_has_role(p.oid,a.oid,'USAGE'),
|
|
170
|
+
COALESCE((SELECT pg_catalog.jsonb_agg(pg_catalog.jsonb_build_array(g.alias,g.native_role,r.oid::pg_catalog.int8,
|
|
171
|
+
pg_catalog.pg_has_role(p.oid,r.oid,'MEMBER')) ORDER BY g.alias COLLATE pg_catalog."C",
|
|
172
|
+
g.native_role COLLATE pg_catalog."C",r.oid)::pg_catalog.text
|
|
173
|
+
FROM (""" + group_values + """) AS g(alias,native_role)
|
|
174
|
+
LEFT JOIN pg_catalog.pg_roles r ON r.rolname=g.native_role),'[]')
|
|
175
|
+
FROM pg_catalog.pg_roles p
|
|
176
|
+
JOIN pg_catalog.pg_roles a ON a.rolname=%s
|
|
177
|
+
WHERE p.rolname=%s""", (*group_params,audience_role,principal))
|
|
178
|
+
if row is None:
|
|
179
|
+
raise CatalogError('role-scope-mismatch')
|
|
180
|
+
try:
|
|
181
|
+
principal_oid, audience_oid = row[0], row[1]
|
|
182
|
+
audience_member = row[2]
|
|
183
|
+
groups_facts = json.loads(row[3])
|
|
184
|
+
except (TypeError,ValueError,IndexError):
|
|
185
|
+
raise CatalogError('role-scope-mismatch') from None
|
|
186
|
+
if (type(principal_oid) is not int or type(audience_oid) is not int
|
|
187
|
+
or audience_member is not True
|
|
188
|
+
or type(groups_facts) is not list or len(groups_facts) != len(groups)):
|
|
189
|
+
raise CatalogError('role-scope-mismatch')
|
|
190
|
+
facts = []
|
|
191
|
+
for fact, (alias,native_role) in zip(groups_facts,groups):
|
|
192
|
+
if (type(fact) is not list or len(fact) != 4 or fact[0] != alias or fact[1] != native_role
|
|
193
|
+
or type(fact[2]) is not int or type(fact[3]) is not bool):
|
|
194
|
+
raise CatalogError('role-scope-mismatch')
|
|
195
|
+
facts.append([alias,native_role,fact[2],fact[3]])
|
|
196
|
+
role_scope = {'version':'umf.operation-role-scope/0.1',
|
|
197
|
+
'principal':[principal,principal_oid],
|
|
198
|
+
'audience':[audience,audience_role,audience_oid],
|
|
199
|
+
'groups':facts}
|
|
200
|
+
observed.update({'principalOid':principal_oid,'audience':audience,
|
|
201
|
+
'roleScopeDigest':hashlib.sha256(_json_bytes(role_scope)).hexdigest(),
|
|
202
|
+
'operationAdmission':False})
|
|
203
|
+
return observed
|